学以致用

focus on Python , C++, and some interest in Go and R

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

对于Python2.7来说,内置的FTP_TLS类并不支持Implicit FTP Over TLS加密方式的FTP Server操作,为支持Implicit FTP Over TLS加密方式,必须重载内置的FTP_TLS类,具体代码如下:

import ftplib

class FTP_TLS(ftplib.FTP_TLS):
    def __init__(self, host='', user='', passwd='', acct='', keyfile=None, certfile=None, timeout=180):
        ftplib.FTP_TLS.__init__(self, host, user, passwd, acct, keyfile, certfile, timeout)
    def connect(self, host='', port=0, timeout=-999):
        if host != '':
            self.host = host
        if port > 0:
            self.port = port
        if timeout != -999:
            self.timeout = timeout

        try:
            self.sock = socket.create_connection((self.host, self.port), self.timeout)
            self.af = self.sock.family
            self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ssl_version=ssl.PROTOCOL_TLSv1)
            self.file = self.sock.makefile('rb')
            self.welcome = self.getresp()
        except Exception as e:
            print e
        return self.welcome
    def download(self, remote_file_name, local_file_name):
        with open(local_file_name, 'wb') as fp:
            self.retrbinary('RETR %s' % remote_file_name, fp.write)

下载的示例代码如下所示:

    host = 'XXX'
    port = 2222
    user = 'user'
    password = 'pass'
    local_dir = './data'

    ftp = FTP_TLS()
    ftp.connect(host, port)
    LOG.debug('begin to login')
    ftp.login(user, password)
    LOG.debug('login succeed')
    LOG.debug('welcome info = %s', ftp.getwelcome())
    ftp.prot_p()

    ftp.cwd('/crexbatch')
    ftp.download('People.zip', 'People.zip')
    ftp.retrlines('LIST')
    fnames = ftp.nlst()
    open('crexbatch.txt', 'wb').write('\r\n'.join(fnames))

 

posted on 2015-09-11 15:29  Jerry.Kwan  阅读(2672)  评论(0编辑  收藏  举报