0

我正在尝试使用 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 等任何命令时出现错误

提前致谢

4

1 回答 1

1

因为 FTPS 需要 diff 实现

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

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() 登录

于 2012-10-12T12:35:14.687 回答