无法使用 ftplib 列出 FTP 目录 - 但 FTP 客户端可以工作

Hen*_*ang 6 python ftp ftplib

我正在尝试连接到 FTP,但无法运行任何命令。

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()
Run Code Online (Sandbox Code Playgroud)

ftp.nlst引发此错误:

错误:
[WinError 10060] 连接尝试失败,因为连接方在一段时间后没有正确响应,或者因为连接的主机没有响应而建立连接失败


我已经使用 FileZilla(在同一台机器上运行)测试了连接,它工作正常。

这是 FileZilla 日志:

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()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ryl 10

状态:服务器发送带有不可路由地址的被动回复

以上表示FTP服务器配置错误。它将其内部网络 IP 发送到外部网络(到客户端 – FileZilla 或 Python ftplib),在那里它是无效的。FileZilla 可以检测到并自动回退到服务器的原始 IP 地址。

Python ftplib 不做这种检测。

您需要修复您的 FTP 服务器以返回正确的 IP 地址。


如果修复服务器不可行(它不是你的并且管理员不合作),你可以让 ftplib 忽略返回的(无效)IP 地址并通过覆盖使用原始地址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
Run Code Online (Sandbox Code Playgroud)

另一种解决方案可能是使用 IPv6。请参阅Python 3.8.5 FTPS 连接

  • 你是最棒的。我很惊讶互联网上关于这件事的信息如此之少 (2认同)