无法使用 ftplib 列出 FTP 目录 - 但 FTP 客户端可以工作
问题描述
我正在尝试连接到 FTP,但我无法运行任何命令.
I'm trying to connect to an FTP but I am unable to run any commands.
ftp_server = ip
ftp_username = username
ftp_password = password
ftp = ftplib.FTP(ftp_server)
ftp.login(ftp_username, ftp_password)
'230 Logged on'
ftp.nlst()
ftp.nlst
抛出此错误:
错误:
[WinError 10060] 连接尝试失败,因为连接的一方在一段时间后没有正确响应,或者连接的主机没有响应,建立连接失败
Error:
[WinError 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 测试了连接(在同一台机器上运行),它工作正常.
I've tested the connection using FileZilla (running on the same machine) and it works fine.
这是 FileZilla 日志:
This is FileZilla log:
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in Status: Retrieving directory listing...
Status: Server sent passive reply with unroutable address. Using server address instead.
Status: Directory listing of "/" successful
解决方案
状态:服务器发送了带有不可路由地址的被动回复
Status: Server sent passive reply with unroutable address
以上表示FTP服务器配置错误.它将其内部网络 IP 发送到外部网络(发送到客户端 - FileZilla 或 Python ftplib),在该位置它是无效的.FileZilla 可以检测到并自动回退到服务器的原始 IP 地址.
The above means that the FTP server is misconfigured. It sends its internal network IP to outside network (to the client – FileZilla or Python ftplib), where it is invalid. FileZilla can detect that and automatically fall back to the original IP address of the server.
Python ftplib 不做这种检测.
Python ftplib does not do this kind of detection.
您需要修复您的 FTP 服务器以返回正确的 IP 地址.
You need to fix your FTP server to return the correct IP address.
如果修复服务器不可行(它不是你的并且管理员不合作),你可以通过覆盖 FTP.makepasv 让 ftplib 忽略返回的(无效的)IP 地址并使用原始地址
:
If it is not feasible to fix the server (it's not yours and the admin is not cooperative), you can make ftplib ignore the returned (invalid) IP address and use the original address instead by overriding FTP.makepasv
:
class SmartFTP(FTP):
def makepasv(self):
invalidhost, port = super(SmartFTP, self).makepasv()
return self.host, port
ftp = SmartFTP(ftp_server)
# the rest of the code is the same
另一种解决方案可能是使用 IPv6.请参阅 Python 3.8.5 FTPS 连接.
对于具有类似后果的不同问题,请参阅 vsftpd 返回 0,0,0,0 以响应 PASV一个>.
相关文章