Python FTP 目录列表挂起

Python FTP Directory Listing Hangs

在 Google 上进行了大量搜索并查看了许多 Whosebug 问题后,我仍然一头雾水。我尝试获取目录列表的每一种方法都以 Python 发送两个命令 TYPE A 和 PASV 结尾,然后它就停止说话了。有什么建议吗?

我的 Python (2.7.6) 代码:

from ftplib import FTP

port_num = 21
host_str = "xxxxxx"
ftp = FTP(host_str)
ftp.set_debuglevel(1)
ftp.connect(host_str, port_num)
ftp.getwelcome()
ftp.login("xxxxxx", "xxxxxx")
print "==Getting DIR..."
lines = ftp.retrlines("NLST")
print "==Got DIR..."
print "Returned files list:\n", lines

输出:

*resp* '220 Microsoft FTP Service'
*welcome* '220 Microsoft FTP Service'
*cmd* 'USER c680-750'
*resp* '331 Password required for c680-750'
*cmd* 'PASS *******'
*resp* '230 User c680-750 logged in'
==Getting DIR...
*cmd* 'TYPE A'
*resp* '200 Command okay.'
*cmd* 'PASV'
*resp* '227 Entering Passive Mode (204,77,162,69,218,190)' Traceback (most recent call last): ...
    raise err error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

FileZilla 在成功连接时显示的内容:

Status: Resolving address of xxxx
Status: Connecting to xxx.xx.xxx.xx:21...
Status: Connection established, waiting for welcome message...
Response:   220 Microsoft FTP Service
Command:    USER xxxx
Response:   331 Password required for xxxx
Command:    PASS *******
Response:   230 User xxxx logged in
Command:    SYST
Response:   215 UNIX Type: L8
Command:    FEAT
Response:   211-Extensions supported:
Response:    MDTM
Response:    SIZE
Response:   211 END
Status: Server does not support non-ASCII characters.
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "xxxx" is the current directory
Command:    TYPE I
Response:   200 Command okay.
Command:    PORT 167,186,116,227,234,64
Response:   200 PORT command successful.
Command:    LIST
Response:   150 File status okay; about to open data connection.
Response:   226 Transfer complete, closing data connection.
Status: Directory listing successful

FileZilla 使用主动模式 (PORT),其中数据连接是从服务器到客户端建立的。您的 python 代码改为使用 PASV 模式,其中数据连接是从客户端到服务器建立的。使用 python

的被动模式
ftp.set_pasv(False)

虽然通常首选被动模式,因为如果客户端在某些 NAT 路由器后面(即典型的家庭设置),它可以工作,但如果服务器本身在某些防火墙或 NAT 设备后面,它可能会失败。在这种情况下,您需要使用主动模式。