无法使用python从FTP下载文件。 [Errno 10054]远程主机强行关闭现有连接

时间:2012-08-23 14:11:23

标签: python ftp errno ftplib

我正在尝试使用python 2.7从FTP下载文件。在Windows XP上

我可以连接FTP,但会收到以下错误

[Errno 10054]远程主机强行关闭现有连接

以下是我的代码。

import os
from time import strftime
from ftplib import FTP

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders


def ftp_connect(path):
    link = FTP(host = 'myservername', timeout = 5) #Keep low timeout
    link.login(passwd = 'mypassword', user = 'myusername')
    debug("%s - Connected to FTP" % strftime("%d-%m-%Y %H.%M"))
    link.cwd(path)
    return link

def writeline(line):
    file.write(line + "\n")


downloaded = open('myfile.txtx', 'wb')

def debug(txt):
    print txt

path="mydir"
filename="myfilename"

link = ftp_connect(path)
file_size = link.size(filename)

max_attempts = 5 #I dont want death loops.

while file_size != downloaded.tell():
    try:
        debug("%s while > try, run retrbinary\n" % strftime("%d-%m-%Y %H.%M"))
        if downloaded.tell() != 0:
            link.retrbinary('RETR ' + filename, downloaded.write, downloaded.tell())
        else:
            link.retrbinary('RETR ' + filename, downloaded.write)
    except Exception as myerror:
        if max_attempts != 0:
            debug("%s while > except, something going wrong: %s\n \tfile lenght is: %i > %i\n" %
                (strftime("%d-%m-%Y %H.%M"), myerror, file_size, downloaded.tell())
            )
            link = ftp_connect(path)
            max_attempts -= 1
        else:
            break
debug("Done with file, attempt to download m5dsum")

我单独测试登录FTP并成功。 但是在执行任何命令时,例如retrbinary或者retrlist上面的错误

提前致谢

1 个答案:

答案 0 :(得分:0)

因为FTPS需要差异化实施

使用下面的代码解决我的问题

ftps = FTP_TLS(server)
ftps.debug(3)
ftps.connect(host=server,port=portno,timeout=60)
ftps.auth()
ftps.login(username, password )
ftps.prot_p()

首先连接到ftps服务器,然后使用auth()和prot_p()

登录