尝试使用FTP over SSL / TLS将文件推送到远程ftp服务器时,我遇到了一个奇怪的错误。我在网上找不到任何解决方案:/请帮助。
这是我的代码:
from ftplib import FTP_TLS
import sys, os
root = "\\home\\user\\test.txt"
dest = "/Destdir"
ftps = FTP_TLS('xxx.xxx.xxx.xxx')
ftps.set_debuglevel(1)
ftps.set_pasv(False)
ftps.connect(port=21, timeout=80)
ftps.login('user', 'pass')
ftps.prot_p()
ftps.ccc()
try:
ftps.cwd(dest)
except Exception as e:
print(e)
try:
file = open('test.txt', 'rb')
ftps.storbinary('STOR test.txt', file)
file.close()
except Exception as e:
print(e)
ftps.close()
这是脚本的输出:
*resp* '220 nas FTP server ready.'
*cmd* 'AUTH TLS'
*resp* '234 AUTH TLS command successful.'
*cmd* 'USER user'
*resp* '331 Password required for user.'
*cmd* 'PASS **********'
*resp* '230 User user logged in.'
*cmd* 'PBSZ 0'
*resp* '200 PBSZ command successful (PBSZ=0).'
*cmd* 'PROT P'
*resp* '200 Protection level set to Private.'
*cmd* 'CCC'
*resp* '200 Clearing control channel protection.'
*cmd* 'CWD /Destdir'
*resp* '250 CWD command successful.'
*cmd* 'TYPE I'
*resp* '200 Type set to I.'
*cmd* 'PORT 10,10,99,11,220,211'
*resp* '200 PORT command successful.'
*cmd* 'STOR test.txt'
*resp* "150 Opening BINARY mode data connection for 'test.txt'."
_ssl.c:704: The handshake operation timed out
由于与远程FTP服务器的连接很好,我认为这不是防火墙问题。
注意:远程FTP服务器是Synology NAS,具有最新的操作系统。
EDIT_0:
使用被动模式的另一次尝试给出了结果:
*resp* '220 nas FTP server ready.'
*cmd* 'AUTH TLS'
*resp* '234 AUTH TLS command successful.'
*cmd* 'USER user'
*resp* '331 Password required for user.'
*cmd* 'PASS **********'
*resp* '230 User user logged in.'
*cmd* 'PBSZ 0'
*resp* '200 PBSZ command successful (PBSZ=0).'
*cmd* 'PROT P'
*resp* '200 Protection level set to Private.'
*cmd* 'CCC'
*resp* '200 Clearing control channel protection.'
*cmd* 'CWD /Destdir'
*resp* '250 CWD command successful.'
*cmd* 'TYPE I'
*resp* '200 Type set to I.'
*cmd* 'PASV'
*resp* '227 Entering Passive Mode (xxx,xxx,xxx,xxx,216,241)'
*cmd* 'STOR test.txt'
*resp* "150 Opening BINARY mode data connection for 'test.txt'."
_ssl.c:704: The handshake operation timed out
我现在也试过扩展被动模式,但它也没有帮助:
*resp* '250 CWD command successful.'
*cmd* 'TYPE I'
*resp* '200 Type set to I.'
*cmd* 'EPSV'
*resp* '229 Entering Extended Passive Mode (|||55536|)'
*cmd* 'STOR test.txt'
*resp* "150 Opening BINARY mode data connection for 'test.txt'."
_ssl.c:704: The handshake operation timed out
EDIT_1:所以脚本部分工作,它能够打开连接,开始传输文件。文件get是在远程服务器上创建的,但它不包含与源文件相同的数据。目标文件最终只有1KB大小和一些随机字符(文件是ANSII编码,而源文件是UTF8。同时我能够使用WinSCP成功上传文件。
您使用FTP活动模式:
ftps.set_pasv(False)
从你的评论来看,你看起来没有充分的理由这样做。
FTP活动模式通常不起作用,因为它要求客户端能够接受传入连接。如果不打开本地(Windows和本地网络)防火墙和/或配置NAT,通常是不可能的。除非您有非常具体的理由,否则甚至不要尝试使用活动模式。使用被动模式。只需删除ftps.set_pasv
电话。被动模式是ftplib中的默认模式。
有关详细信息,请参阅我在FTP connection modes上的文章。
这可能是防火墙问题。 FTP非常特殊,因为它每次传输使用不同的连接。当前根据您的跟踪工作的连接是命令连接,该连接由客户端建立并且以服务器FTP端口为目标(通常为21)。
数据连接是一个独立的连接。在活动模式下,它由服务器建立,源自FTP-DATA端口(20)并且目标是客户端在其PORT
命令中发送的端口。在被动模式下,服务器在其对PASV命令的响应中发送将侦听数据连接的端口,并且客户端尝试打开与该(几乎随机)端口的新连接。
这意味着除非防火墙允许大地址范围,或者防火墙软件实现特殊处理以动态允许FTP命令中传递的地址,否则防火墙可以允许命令连接,然后阻止任何数据连接。
参考文献: