【问题标题】:FTP upload error with Python and ftplib.Python 和 ftplib 的 FTP 上传错误。
【发布时间】:2015-06-03 19:53:42
【问题描述】:

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

上传文件时出错:[Errno 54] Connection reset by peer

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

上传文件时出错:[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)

【问题讨论】:

    标签: python ftplib ftps


    【解决方案1】:

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

    ftp.set_debuglevel(2)
    

    在我的情况下,转移挂起

    put 'STOR test.xml\r\n'

    get '125 数据连接已打开;传输开始。\n'

    resp '125 数据连接已打开;转移开始。'

    然后我找到了这个建议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,但我找不到更好的方法。

    【讨论】:

    • 六年后,当我使用 python 3.9.7 将文件上传到 FileZilla FTP 服务器 v1.0.1 时,我仍然遇到了这个问题...脚本挂在 conn.unwrap() 并注释掉工作!当然,FTP 服务器现在抱怨客户端没有正确关闭连接。但没关系。但是,该解决方案有效。我只是希望我确切地知道为什么 unwarp() 函数挂起。
    【解决方案2】:

    我遇到了同样的问题,并成功地用这行解决了它:

    ftps = FTP_TLS(server)
    ftps.set_debuglevel(2) # To show logs
    ftps.ssl_version = ssl.PROTOCOL_TLS
    ftps.set_pasv(True)
    ftps.login(user="user", passwd="passwd")
    

    我从Python 3.5.1 切换到Python 3.8.3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2020-04-17
      • 2021-07-12
      相关资源
      最近更新 更多