Python FTP目录列表挂起

时间:2015-01-06 16:18:11

标签: python list ftp ftplib

经过大量搜索Google并查看了许多stackoverflow问题,我仍然感到茫然。我尝试获取目录列表的每个方法都以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

1 个答案:

答案 0 :(得分:2)

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

ftp.set_pasv(False)

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

相关问题