Python套接字连接FTP未收到预期数据
我正在使用Python的socket库连接ftp.rediris.es,但在发送数据后没有收到我期待的回复。我用我的代码和回复来更清楚地说明这个问题:
#!/usr/bin/env python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket Created"
port = 21
host = "ftp.rediris.es"
ip = socket.gethostbyname(host)
print ip
print "ip of " +host+ " is " +ip
s.connect ((ip, port))
print "Socket Connected to "+host+" on ip "+ ip
message = "HELP\r\n"
s.sendall(message)
reply = s.recv(65565)
print reply
这是我运行代码时得到的回复:
python test.py
Socket Created
130.206.1.5
ip of ftp.rediris.es is 130.206.1.5
Socket Connected to ftp.rediris.es on ip 130.206.1.5
220- Bienvenido al FTP anónimo de RedIRIS.
220-Welcome to the RedIRIS anonymous FTP server.
220 Only anonymous FTP is allowed here
而这是我期待的回复:
telnet
telnet> open ftp.rediris.es 21
Trying 130.206.1.5...
Connected to zeppo.rediris.es.
Escape character is '^]'.
220- Bienvenido al FTP anónimo de RedIRIS.
220-Welcome to the RedIRIS anonymous FTP server.
220 Only anonymous FTP is allowed here
HELP
214-The following SITE commands are recognized
ALIAS
CHMOD
IDLE
UTIME
我在端口80上尝试过连接www.google.com,发送了GET / HTTP/1.1\r\n\r\n,并且完美地看到了头信息。 这是怎么回事呢?我是不是没有正确地向服务器发送命令呢?谢谢大家!
1 个回答
1
你可以在发送 HELP
消息之前,先检查一下最后一行是否收到了 220 Only anonymous FTP is allowed here
,这就像在 telnetlib 中使用 read_until
一样。
像这样,我试过是有效的:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket Created"
port = 21
host = "ftp.rediris.es"
ip = socket.gethostbyname(host)
print ip
print "ip of " +host+ " is " +ip
s.connect ((ip, port))
print "Socket Connected to "+host+" on ip "+ ip
reply = ''
while True:
message = "HELP\r\n"
reply += s.recv(1024)
if not reply:
break
if '220 Only anonymous FTP is allowed here' in reply:
s.sendall(message)
break
reply += s.recv(65535)
print reply
输出结果:
Socket Created
130.206.1.5
ip of ftp.rediris.es is 130.206.1.5
Socket Connected to ftp.rediris.es on ip 130.206.1.5
220- Bienvenido al FTP anónimo de RedIRIS.
220-Welcome to the RedIRIS anonymous FTP server.
220 Only anonymous FTP is allowed here
214-The following SITE commands are recognized
ALIAS
CHMOD
IDLE
UTIME
214 Pure-FTPd - http://pureftpd.org/
不过,我有点不明白你为什么一开始没有选择更合适的模块,比如 ftplib
或 telnetlib
。