基本信息
源码名称:Python 自定义FTP功能 实例源码
源码大小:9.92KB
文件格式:.py
开发语言:Python
更新时间:2015-02-11
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
#!/usr/bin/env python # -*- coding:utf-8 -*- "Program for ftp server" from socketserver import * from time import * import os import loginauth import traceback import subprocess import codecs import logging def GetParentPath(strPath): if not strPath: return None; lsPath = os.path.split(strPath); if lsPath[1]: return lsPath[0]; lsPath = os.path.split(lsPath[0]); return lsPath[0]; def ReadFile(filePath,encoding="utf-8"): with codecs.open(filePath,"r",encoding) as f: return f.read() class MyFtp(StreamRequestHandler): def handle(self): logger = logging.getLogger("FTP") logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler("ftp.log") fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) fh.setFormatter(formatter) # add the handlers to logger logger.addHandler(ch) logger.addHandler(fh) # "application" code __devilcomment = ''' logger.debug("debug message") logger.info("info message") logger.warn("warn message") logger.error("error message") logger.critical("critical message") ''' self.client_address[0] logger.info('%s connected'%self.client_address[0]) self.request.sendall(b'auth') logger.info('%s Authenticating'%self.client_address[0]) while True: try: name,password = self.request.recv(BUFSIZ).decode('utf-8').split() except: self.request.sendall(b'fail2login') continue auth_result = loginauth.user_Auth(name,password) if auth_result == 0: logger.info('%s log in'% name) self.request.sendall(b'ok2login') homePath = os.path.abspath('.') break elif auth_result == 1: logger.info('%s Authentiation failed'% name) self.request.sendall(b'fail2login') sleep(1) continue while True: try: recv_data = self.request.recv(BUFSIZ).decode('utf-8') command = recv_data.split() if command==[]: continue logger.info ('command: ' ' '.join(command)) if command[0] == 'rls': result = os.popen('dir').read().encode('utf-8') self.request.sendall(result) continue if command[0] == '?' or recv_data[0] == 'help': send_help = ''' ?\help: Get help. Get: Downlaod file from remote server. Send: Send local file to remote server. ls: List local file. rls: List remote server file. quit\exit: Quit the application. ''' self.request.sendall(send_help.encode('utf-8')) continue if command[0] == 'send': filename = ' '.join(command[1:-1]) totalSize = int(command[-1]) logger.info ('待接收文件%s总大小:%sKB'%(filename,totalSize)) self.request.sendall(b'ok2send') revSize=0 logger.info ('Recieving....') with open(filename,'wb') as f: while 1: recv_data = self.request.recv(BUFSIZ) revSize =len(recv_data) percent=str(revSize*100//totalSize) '% ' #logger.info (percent) #if recv_data==b'send over!': # break f.write(recv_data) self.request.send(percent.encode('utf-8')) if revSize>=totalSize : sleep(0.5) self.request.sendall(b'File transfer successed!') break #self.request.sendall('\033[33;1mFile transfer successed!!!\033[0m') logger.info('File transfer successed!') continue if command[0] == 'get': filename = command[1] if os.path.isfile(filename): msg='ok2get' ' ' str(os.stat(filename)[6]) self.request.sendall(msg.encode('utf-8')) if self.request.recv(BUFSIZ) == b'ok2send': self.request.sendall(b'sending') sleep(0.5) file_data = open(filename,'rb') file_tmp = file_data.read() self.request.sendall(file_tmp) file_data.close() sleep(1) self.request.sendall(b'Downloading completed!') else: msg='fail2get' errInfo=' %s not found!'% filename logger.info(errInfo) msg =errInfo self.request.sendall(msg.encode('utf-8')) logger.info('%s Downloading failed!'% self.client_address[0]) continue if command[0] == 'cd' or (command[0][0:2]=='cd' and len(command)==1): nowPath=os.path.abspath('.') path = ' '.join(command).replace('cd ','') if path=='.' or recv_data == 'cd' or recv_data == 'cd.': nowPath=os.path.abspath('.') self.request.sendall(nowPath.encode('utf-8')) elif path=='~' or recv_data =='cd~': lastPath=os.path.abspath('.') os.chdir(homePath) nowPath=os.path.abspath('.') self.request.sendall(nowPath.encode('utf-8')) elif path=='-' or recv_data == 'cd-': if 'lastPath' in locals().keys(): path=lastPath lastPath=os.path.abspath('.') os.chdir(path) else: os.chdir('.') nowPath=os.path.abspath('.') self.request.sendall(nowPath.encode('utf-8')) elif path=='..' or recv_data =='cd..': lastPath=os.path.abspath('.') os.chdir(GetParentPath(nowPath)) nowPath=os.path.abspath('.') self.request.sendall(nowPath.encode('utf-8')) elif os.path.exists(path): lastPath=os.path.abspath('.') os.chdir(path) nowPath=os.path.abspath('.') self.request.sendall(nowPath.encode('utf-8')) else: self.request.sendall(b'No such directory!') self.request.sendall(b'data transfer over!') continue if command[0]=='type' or command[0]=='cat' : filename = recv_data.replace('type','').replace('get','').lstrip() if os.path.isfile(filename): try: content = ReadFile(filename).encode('utf-8') except: self.request.sendall(b'Can\'t read file!') self.request.sendall(b'data transfer over!') continue self.request.sendall(content) else: self.request.sendall(b'File not found!') self.request.sendall(b'data transfer over!') continue status,result=subprocess.getstatusoutput(recv_data) if len(result.strip())!=0: self.request.sendall(result.encode('utf-8')) else: self.request.send(b'done') self.request.sendall(b'data transfer over!') continue except KeyboardInterrupt: break except ConnectionError: logger.error('%s\'s connection closed!!'% self.client_address[0]) break except: #traceback.print_exc() logger.info('error!') self.request.sendall(b'error!') continue if __name__ == '__main__': HOST,PORT = ' ',9889 ADDR = (HOST,PORT) BUFSIZ = 8192 try: server = ThreadingTCPServer(ADDR,MyFtp) server.serve_forever() except ConnectionError: logger.error('%s\'s connection closed!!'% self.client_address[0]) except KeyboardInterrupt: server.shutdown() logger.error('Forced to quit!!') except: pass