尝试使用Python FTP_TLS对象下载文件时获取AttributeError?

时间:2017-04-06 23:36:02

标签: python python-2.7 sockets ftp

from ftplib import FTP_TLS
import socket
import ssl

class tyFTP(FTP_TLS):
    def __init__(self, host='', user='', passwd='', acct='', keyfile=None, certfile=None, timeout=60):
        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

# FTP_ROOT_PATH = "/outgoing/"
FTP_SITE = "..."
# FTP_SITE = "..."
FTP_PORT = 990

UPLOAD = {
    "USERNAME": "...",
    "PASSWORD": "..."
}

DOWNLOAD = {
    "USERNAME": "...",
    "PASSWORD": "..."
}

remote_file = "..."
local_filepath = "..."

server = tyFTP()
server.connect(host=FTP_SITE, port=990)
server.login(user=DOWNLOAD['USERNAME'], passwd=DOWNLOAD['PASSWORD'])
server.prot_p()
server.retrbinary("RETR " + remote_file, open(local_filepath, "wb").write)

我已经从这篇帖子中复制了一些代码Python FTP implicit TLS connection issue。我对代码中发生的所有事情都有很好的理解,但完全没有错误。问题是,当我调用retrbinary函数时,我可以运行所有操作,直到最后一行。我收到了错误:

AttributeError: 'int' object has no attribute 'wrap_socket'

完整的错误对话是:

File "sample.py", line 48, in <module>
server.retrbinary("RETR " + remote_file, open(local_filepath, "wb").write)
File "C:\Users\Alex\Anaconda2\lib\ftplib.py", line 718, in retrbinary
conn = self.transfercmd(cmd, rest)
File "C:\Users\Alex\Anaconda2\lib\ftplib.py", line 376, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "C:\Users\Alex\Anaconda2\lib\ftplib.py", line 712, in ntransfercmd
conn = self.context.wrap_socket(conn,
AttributeError: 'int' object has no attribute 'wrap_socket'

有没有人对罪魁祸首是什么有任何见解?

1 个答案:

答案 0 :(得分:3)

你对超时arg(这是一个int)的使用是在这一行的上下文变量的PLACE中:

FTP_TLS.__init__(self, host, user, passwd, acct, keyfile, certfile, timeout)

应该是:

FTP_TLS.__init__(self, host, user, passwd, acct, keyfile, certfile, context, timeout)

请参阅: https://docs.python.org/2/library/ftplib.html