Skip to main content
 首页 » 编程设计

python之Python 和 ftplib 的 FTP 上传错误。

2025年05月04日8Renyi-Fan

我正在尝试运行一个简单的 ftps 脚本,以定期将文件从 Linux 机器上传到在 Windows Server 2012 上运行的 ftps 实例。当我尝试在我的桌面 (OS x) 上测试该脚本时,脚本错误:

Error uploading file: [Errno 54] Connection reset by peer

如果我在 linux 机器上运行脚本,同样的错误,除了 104 而不是 54:

Error uploading file: [Errno 104] Connection reset by peer

我正在上传的文件要么是空的,要么是 8 字节的。我已验证 ftps 正在与我桌面上的其他 2 个客户端一起使用。我错过/忽视了什么?

#!/usr/bin/env python 
from ftplib import FTP_TLS 
import fnmatch 
import os 
import ssl 
import sys 
 
server = '192.168.1.2' 
user = 'myUsername' 
passwd = 'myPassword' 
 
def connect_ftp(): 
    ftp = FTP_TLS(server, user, passwd) 
    ftp.set_pasv(True) 
    ftp.prot_p() 
 
    return ftp 
 
def upload_file(ftp_connection, upload_file_path): 
    try: 
        upload_file = open("/tmp/test/" + upload_file_path, 'r') 
        print('Uploading ' + upload_file_path + "...") 
        ftp_connection.storbinary('STOR ' + upload_file_path, upload_file) 
        ftp_connection.quit() 
        ftp_connection.close() 
        upload_file.close() 
        print('Upload finished.') 
 
    except Exception, e: 
        print("Error uploading file: " + str(e)) 
 
ftp_conn = connect_ftp() 
 
 
for file in os.listdir('/tmp/test'): 
        if fnmatch.fnmatch(file, 'bt_*.txt'): 
            upload_file(ftp_conn, file) 

请您参考如下方法:

我认为这个问题只出现在 MS FTP 服务器上。 首先开启debug

ftp.set_debuglevel(2) 

在我的情况下传输挂起

put 'STOR test.xml\r\n'

get '125 Data connection already open; Transfer starting.\n'

resp '125 Data connection already open; Transfer starting.'

然后我发现了这个建议http://www.sami-lehtinen.net/blog/python-32-ms-ftps-ssl-tls-lockup-fix 我试过了(在 storbinary 中评论了 conn.unwrap() ),它成功了! 在我的例子中是第 513 行

        # shutdown ssl layer 
        if _SSLSocket is not None and isinstance(conn, _SSLSocket): 
            pass #conn.unwrap() 

这显然是非常糟糕的 hack,但我找不到更好的东西。