手动上传FTP文件成功,但使用Python ftplib失败

6 投票
1 回答
10322 浏览
提问于 2025-04-16 01:56

我在一台 Debian 服务器上安装了 vsFTP。当我手动使用 ftp 命令上传文件时,一切正常。也就是说,下面的操作是可以成功的:

john@myhost:~$ ftp xxx.xxx.xxx.xxx 5111
Connected to xxx.xxx.xxx.xxx.
220 Hello,Welcom to my FTP server.
Name (xxx.xxx.xxx.xxx:john): ftpuser
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> put st.zip
local: st.zip remote: st.zip
200 PORT command successful. Consider using PASV.
150 Ok to send data.
226 File receive OK.
12773 bytes sent in 0.00 secs (277191.8 kB/s)
ftp> 221 Goodbye.

(请注意,我把 vsFTP 服务器配置成使用一个非默认的端口,比如 5111,出于某种原因)

现在,当我写一个 Python 脚本来程序化地上传文件时,它失败了。错误提示是“超时”,如下所示:

john@myhost:~$ ipython
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14) 
Type "copyright", "credits" or "license" for more information.

IPython 0.8.4 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import ftplib

In [2]: ftp=ftplib.FTP()                                                    

In [3]: ftp.connect('xxx.xxx.xxx.xxx','5111')                                
Out[3]: "220 Hello,Welcom to my FTP server."

In [4]: ftp.login('ftpuser','ftpuser')                              
Out[4]: '230 Login successful.'

In [5]: f=open('st.zip','rb')                              

In [6]: ftp.storbinary('STOR %s' % 'my_ftp_file.zip', f)                            
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)

...

/usr/lib/python2.5/ftplib.pyc in ntransfercmd(self, cmd, rest)
    322             af, socktype, proto, canon, sa = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
    323             conn = socket.socket(af, socktype, proto)
--> 324             conn.connect(sa)
    325             if rest is not None:
    326                 self.sendcmd("REST %s" % rest)

/usr/lib/python2.5/socket.pyc in connect(self, *args)

error: (110, 'Connection timed out')

我猜我的 vsFTP 服务器配置有问题,但我搞不清楚具体哪里出错了。有没有人能帮忙?

我的 vsFTP 配置是:


listen=YES

connect_from_port_20=YES
listen_port=5111
ftp_data_port=5110

# Passive FTP mode allowed
pasv_enable=YES
pasv_min_port=5300
pasv_max_port=5400

max_per_ip=2

1 个回答

7

超时问题是在你尝试发送数据时才会出现,所以你能够成功连接到服务器。我看到的唯一不同是,ftplib 默认使用被动模式,而你的命令行客户端似乎没有使用这个模式。试着在开始传输之前执行

ftp.set_pasv(False)

看看会发生什么。

需要注意的是,非被动模式基本上已经过时了,因为它无法穿越 NAT 防火墙,所以你可能应该配置 vsFTP 以允许被动模式。

撰写回答