def getPublicIp(): # get socket object # socket = SysMgr.getPkg('socket', False) if not socket: return from socket import socket, AF_INET, SOCK_DGRAM, SOCK_STREAM ret = None try: s = socket(AF_INET, SOCK_STREAM) s.settimeout(0.3) # connect to google public IP # s.connect(("8.8.8.8", 53)) ret = s.getsockname()[0] except SystemExit: sys.exit(0) except: SysMgr.printWarn("Fail to get public IP address") if not ret: ret = NetworkMgr.getMainIp() return ret
def onRun(req, onlySocket): # parse command # origReq = req command = req.split('|', 1)[1] # parse addr # addr = '%s:%s' % (self.ip, self.port) if not onlySocket: SysMgr.printInfo(\ "'%s' is executed from %s\n" % (command, addr)) # return just the connected socket # if onlySocket: return self # get select object # selectObj = SysMgr.getPkg('select') print(oneLine) # run mainloop # isPrint = False while 1: try: [readSock, writeSock, errorSock] = \ selectObj.select([self.socket], [], []) # receive packet # output = self.getData() if not output: break print(output[:-1]) isPrint = True except: break # print output from server # if not isPrint: print('No response') print(oneLine) # close connection # try: self.close() except: pass
def recvfrom(self, size=0, noTimeout=False, verbose=True): if self.ip is None or self.port is None: SysMgr.printErr(\ "Fail to use IP address for server because it is not set") return False elif not self.socket: SysMgr.printErr(\ "Fail to use socket for client because it is not set") return False # get socket object # socket = SysMgr.getPkg('socket', False) # set recv size # if size == 0: size = self.recvSize while 1: try: message, address = self.socket.recvfrom(size) return (message, address) except socket.timeout: if noTimeout: continue SysMgr.printWarn(\ "Fail to receive data from %s:%d as client because %s" % \ (self.ip, self.port, 'timeout')) return None except KeyboardInterrupt: sys.exit(0) except SystemExit: sys.exit(0) except: if verbose: SysMgr.printWarn(\ "Fail to receive data from %s:%d as client because %s" % \ (self.ip, self.port, SysMgr.getErrReason())) return None
def onDownload(req): # parse path # plist = req.split('|', 1)[1] path = plist.split(',') origPath = path[0].strip() targetPath = path[1].strip() receiver = self targetIp = self.ip targetPort = self.port # get select object # selectObj = SysMgr.getPkg('select') # receive file # try: curSize = long(0) totalSize = None dirPos = targetPath.rfind('/') if dirPos >= 0 and \ not os.path.isdir(targetPath[:dirPos]): os.makedirs(targetPath[:dirPos]) # receive file size # while 1: size = receiver.recv(receiver.recvSize) if not size: continue else: totalSize = long(size.decode()) receiver.send('ACK'.encode()) break # receive file # with open(targetPath, 'wb') as fd: while 1: selectObj.select([receiver.socket], [], [], 3) buf = receiver.recv(receiver.recvSize) if buf: curSize += len(buf) fd.write(buf) else: break # print progress # UtilMgr.printProgress(curSize, totalSize) UtilMgr.deleteProgress() SysMgr.printInfo(\ "%s [%s] is downloaded from %s:%s:%s successfully\n" % \ (targetPath, \ UtilMgr.convertSize2Unit(os.path.getsize(targetPath)), targetIp, targetPort, origPath)) except: err = SysMgr.getErrReason() SysMgr.printErr(\ 'Fail to download %s from %s:%s:%s because %s' % \ (origPath, targetIp, targetPort, targetPath, err)) finally: receiver.close()
def handleServerRequest(self, req, onlySocket=False): def onDownload(req): # parse path # plist = req.split('|', 1)[1] path = plist.split(',') origPath = path[0].strip() targetPath = path[1].strip() receiver = self targetIp = self.ip targetPort = self.port # get select object # selectObj = SysMgr.getPkg('select') # receive file # try: curSize = long(0) totalSize = None dirPos = targetPath.rfind('/') if dirPos >= 0 and \ not os.path.isdir(targetPath[:dirPos]): os.makedirs(targetPath[:dirPos]) # receive file size # while 1: size = receiver.recv(receiver.recvSize) if not size: continue else: totalSize = long(size.decode()) receiver.send('ACK'.encode()) break # receive file # with open(targetPath, 'wb') as fd: while 1: selectObj.select([receiver.socket], [], [], 3) buf = receiver.recv(receiver.recvSize) if buf: curSize += len(buf) fd.write(buf) else: break # print progress # UtilMgr.printProgress(curSize, totalSize) UtilMgr.deleteProgress() SysMgr.printInfo(\ "%s [%s] is downloaded from %s:%s:%s successfully\n" % \ (targetPath, \ UtilMgr.convertSize2Unit(os.path.getsize(targetPath)), targetIp, targetPort, origPath)) except: err = SysMgr.getErrReason() SysMgr.printErr(\ 'Fail to download %s from %s:%s:%s because %s' % \ (origPath, targetIp, targetPort, targetPath, err)) finally: receiver.close() def onUpload(req): # parse path # plist = req.split('|', 1)[1] path = plist.split(',') origPath = path[0].strip() targetPath = path[1].strip() sender = self targetIp = self.ip targetPort = self.port addr = '%s:%s' % (targetIp, targetPort) # check file # if not os.path.isfile(origPath): SysMgr.printErr(\ 'Failed to find %s to transfer' % origPath) return convert = UtilMgr.convertSize2Unit try: # receive file size # stat = os.stat(origPath) st_size = '%s' % stat.st_size sender.send(st_size) # read for ACK # while 1: ret = sender.recv(3) if ret is None: continue elif ret is False: sys.exit(0) else: break # transfer file # curSize = long(0) totalSize = long(st_size) with open(origPath, 'rb') as fd: buf = fd.read(sender.sendSize) while buf: # print progress # UtilMgr.printProgress(curSize, totalSize) ret = sender.send(buf) if not ret: raise Exception() else: curSize = len(buf) buf = fd.read(sender.sendSize) UtilMgr.deleteProgress() SysMgr.printInfo(\ "%s [%s] is uploaded to %s:%s successfully\n" % \ (origPath, convert(os.path.getsize(origPath)), \ addr, targetPath)) except: err = SysMgr.getErrReason() SysMgr.printErr(\ "Fail to upload %s to %s:%s because %s" % \ (origPath, addr, targetPath, err)) finally: sender.close() def onRun(req, onlySocket): # parse command # origReq = req command = req.split('|', 1)[1] # parse addr # addr = '%s:%s' % (self.ip, self.port) if not onlySocket: SysMgr.printInfo(\ "'%s' is executed from %s\n" % (command, addr)) # return just the connected socket # if onlySocket: return self # get select object # selectObj = SysMgr.getPkg('select') print(oneLine) # run mainloop # isPrint = False while 1: try: [readSock, writeSock, errorSock] = \ selectObj.select([self.socket], [], []) # receive packet # output = self.getData() if not output: break print(output[:-1]) isPrint = True except: break # print output from server # if not isPrint: print('No response') print(oneLine) # close connection # try: self.close() except: pass # get select object to check # SysMgr.getPkg('select') # unmarshalling # if type(req) is tuple: try: req = req[0].decode() except: req = req[0] # handle request # if not req: return elif req.upper().startswith('DOWNLOAD'): return onDownload(req) elif req.upper().startswith('UPLOAD'): return onUpload(req) elif req.upper().startswith('RUN'): return onRun(req, onlySocket) elif req.startswith('ERROR'): err = req.split('|', 1)[1] errMsg = err.split(':', 1)[0] SysMgr.printErr(errMsg) else: SysMgr.printErr(\ "Fail to recognize '%s' request" % req) elif not req: SysMgr.printErr(\ "No response from server") else: SysMgr.printErr(\ "received wrong reply '%s'" % req)
def __init__(\ self, mode, ip, port, blocking=True, tcp=False, anyPort=False): self.mode = mode self.ip = None self.port = None self.socket = None self.request = None self.status = None self.ignore = long(0) self.fileno = -1 self.time = None self.sendSize = 32767 self.recvSize = 32767 self.tcp = tcp self.connected = False # get socket object # socket = SysMgr.getPkg('socket') try: from socket import socket, AF_INET, SOCK_DGRAM, \ SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR, SO_SNDBUF, SO_RCVBUF, \ SOL_TCP, TCP_NODELAY, SO_RCVTIMEO, SO_SNDTIMEO except: return None try: # set socket type # if tcp: self.socket = socket(AF_INET, SOCK_STREAM) else: self.socket = socket(AF_INET, SOCK_DGRAM) self.fileno = self.socket.fileno() # increate socket buffer size to 1MB # self.socket.setsockopt(SOL_SOCKET, SO_SNDBUF, 1 << 20) self.socket.setsockopt(SOL_SOCKET, SO_RCVBUF, 1 << 20) # get buffer size # self.sendSize = self.socket.getsockopt(SOL_SOCKET, SO_SNDBUF) self.recvSize = self.socket.getsockopt(SOL_SOCKET, SO_RCVBUF) # set REUSEADDR # self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # set SENDTIMEOUT # ''' sec = 1 usec = long(0) timeval = struct.pack('ll', sec, usec) self.socket.setsockopt(SOL_SOCKET, SO_SNDTIMEO, timeval) ''' # set NODELAY # ''' self.socket.setsockopt(SOL_TCP, TCP_NODELAY, 1) ''' # set IP & PORT # self.ip = ip self.port = port if mode == 'server': # IP # if not ip: self.ip = '0.0.0.0' # PORT # if anyPort: self.port = long(0) elif not port: self.port = SysMgr.defaultPort # bind # try: self.socket.bind((self.ip, self.port)) except: self.socket.bind((self.ip, self.port)) # get bind port # self.port = self.socket.getsockname()[1] if not blocking: self.socket.setblocking(0) except: err = SysMgr.getErrReason() if err.startswith('13') and \ not SysMgr.isRoot() and \ port < 1024: feedback = ', use port bigger than 1024' else: feedback = '' SysMgr.printErr(\ "Fail to create socket with %s:%s as server because %s%s" % \ (self.ip, self.port, err, feedback)) ''' if error "99 Cannot assign requested address" occurs: add "net.ipv4.ip_nonlocal_bind = 1" in /etc/sysctl.conf execute sysctl -p /etc/sysctl.conf ''' self.ip = None self.port = None return None