博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2.5 定义FTP工具的各种方法
阅读量:5293 次
发布时间:2019-06-14

本文共 5269 字,大约阅读时间需要 17 分钟。

用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] ')

 

转载于:https://www.cnblogs.com/fg2312/p/7650220.html

你可能感兴趣的文章
Django 模型层
查看>>
第8章-方法
查看>>
dedecms讲解-arc.listview.class.php分析,列表页展示
查看>>
Microsoft SQL Server Transact-SQL
查看>>
Font: a C++ class
查看>>
Extjs6 经典版 combo下拉框数据的使用及动态传参
查看>>
Java四种引用包括强引用,软引用,弱引用,虚引用
查看>>
【NodeJS】http-server.cmd
查看>>
iOS bundle identifier 不一致,target general的Bundle Identifier后面总是有三条灰色的横线...
查看>>
研磨JavaScript系列(五):奇妙的对象
查看>>
对比传统的Xilinx AMP方案和OPENAMP方案-xapp1078和ug1186
查看>>
面试题2
查看>>
selenium+java iframe定位
查看>>
js基础
查看>>
P2P综述
查看>>
细读 php json数据和JavaScript json数据
查看>>
第五章 如何使用Burp Target
查看>>
Sprint阶段测试评分总结
查看>>
Servlet3.0新特性
查看>>
java内存溢出怎么解决
查看>>