用class定义ftp工具的各种方法
import os,sysfrom ftplib import FTPfrom mimetypes import guess_type,add_typefrom getpass import getpass#定义默认配置dfltSite = '192.168.191.1'dfltUser = ()dfltRdir = '.'class FtpTools: #allows these 3 to be redefined def getlocaldir(self): return (len(sys.argv) > 1 and sys.argv[1]) or '.' #返回本地路径 def getcleanall(self): return input( 'Clean local directory first? ')[:1] in ['y','Y'] #是否清除所有 #暂且不用 # def getpassword(self): # print('password') # return getpass('Password for %s on %s'%(self.remoteuser,self.remotesite)) #键入密码 #配置 def configTransfer(self,site=dfltSite,rdir=dfltRdir,user=dfltUser): self.nonpassive = False # passive FTP by default self.remotesite = site self.remotedir = rdir # FTP的路径 self.remoteuser = user # 因为我没设置密码,所以为空集 self.localdir =self.getlocaldir() self.cleanall = self.getcleanall() self.remotepass = '' #密码 #判断文件格式 def isTextKind(self,remotename,trance=True): ''' use mimetypes to guess if filanme means text or binary''' add_type('text/x-python-win','.pyw') #not in tables mimetype, encoding = guess_type(remotename,strict=False) #allow extras mimetype = mimetype or '?/?' mimetype = mimetype.split('/')[0] if trance: print(mimetype,encoding or '') return mimetype == 'text' and encoding == None #连接服务器 def connectFtp(self): # 连接PFTP print('connecting...') connection = FTP(self.remotesite) connection.login(self.remoteuser,self.remotepass) connection.cwd(self.remotedir) #most do passive if self.nonpassive: connection.set_pasv(False) self.connection = connection #清除本地文件 def cleanLocals(self): '''try to delete all local files first to remove garbage''' #清除本地文件 if self.cleanall: for localname in os.listdir(self.localdir): try: print('deleting local', localname) os.remove(os.path.join(self.remotedir, localname)) except: print('cannot delete', localname) #清除远程文件 def cleanRemotes(self): '''try to delete all remote files to remove garbage''' if self.cleanall: for remotename in self.connection.nlst(): try: print('deleting local', remotename) self.connection.delete(remotename) except: print('cannot delete', remotename) #下载文件 def downloadOne(self,remotename,localpath): if self.isTextKind(remotename): localfile = open(localpath,'w',encoding=self.connection.encoding) def callback(line): localfile.write(line + '\n') self.connection.retrlines('RETR '+remotename,callback) else: localfile = open(localpath,'wb') self.connection.retrbinary('RETR ' + remotename, localfile.write) localfile.close() #上传文件 def uploadOne(self, localname,remotename, localpath): if self.isTextKind(localname): localfile = open(localpath,'rb') self.connection.storlines('RETR ' + remotename, localfile) else: localfile = open(localpath, 'rb') self.connection.storbinary('RETR '+remotename,localfile) localfile.close() #下载目录 def downloadDir(self): remotefiles = self.connection.nlst() for remotename in remotefiles: if remotename in ('.', '..') or not '.' in remotename: continue # 判断是否目录,这里根据实际情况更改 localpath = os.path.join(self.localdir, remotename) print('downing', remotename, 'to', localpath, 'as',end=' ') self.downloadOne(remotename,localpath) print('Done',len(remotefiles),'files downloaded') #上传目录 def uploadDir(self): localfiles = os.listdir(self.localdir) for localname in localfiles: localpath = os.path.join(self.localdir, localname) print('uploading', localpath, 'to', localname, 'as',end=' ') self.uploadOne(localname,localpath,localname) print('Done',len(localfiles),'files uploaded') def run(self,cleanTarget=lambda:None, transferAct=lambda:None): self.connectFtp() cleanTarget() transferAct() self.connection.quit()if __name__ == '__main__': ftp = FtpTools() xfermode = 'download' if len(sys.argv) > 1: xfermode = sys.argv.pop(1) if xfermode == 'download': ftp.configTransfer() ftp.run(cleanTarget=ftp.cleanLocals, transferAct=ftp.downloadDir) if xfermode == 'upload': ftp.configTransfer(site='192.168.191.1') #根据自己情况更改IP ftp.run(cleanTarget=ftp.cleanRemotes, transferAct=ftp.uploadDir) else: print('Usage: ftptools.py["download/upload"] [loacldir] ')