Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

python - Cannot list FTP directory using ftplib – but FTP client works

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()

The ftp.nlst throws this error:

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


I've tested the connection using FileZilla (running on the same machine) and it works fine.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Status: Server sent passive reply with unroutable address

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 does not do this kind of detection.

You need to fix your FTP server to return the correct IP address.


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

Another solution may be to use IPv6. See Python 3.8.5 FTPS connection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...