【问题标题】:Python Sockets connect to FTP don't receive what I expectPython Sockets 连接到 FTP 没有收到我所期望的
【发布时间】:2014-11-03 13:10:46
【问题描述】:

我正在使用 python 套接字连接到 ftp.reiris.es,但在发送数据后我没有收到我期望的答案。我用我的代码和答案更好地解释了这一点: 这是我的代码(test.py)

#!/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

我已经在通往 www.google.com 的端口 80 上尝试过这个,发送一个 GET / HTTP/1.1\r\n\r\n 并且完美地看到了标题。 发生什么了?我没有将命令直接发送到服务器吗?提前谢谢你

【问题讨论】:

  • 有关 FTP 协议的描述,请参阅 RFC959 并实现您在其中找到的内容。不要试图猜测协议。

标签: python sockets tcp ftp serversocket


【解决方案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/

话虽如此,但不完全确定您为什么没有选择更合适的模块,例如 ftplibtelnetlib

【讨论】:

  • 真的非常感谢,这很有帮助。因此,为了确保我已经理解,我的代码无法正常工作,因为我太早发送“帮助”了,对吧?在收到所有我需要收到的东西之前。而你把代码放在了为什么?因为你一直都在接受,不是吗?我没有使用其他库,因为我习惯了套接字我是新来的,想从基础开始。
  • @user3515313,是和否。你的s.recv(65535) 也应该是按块读取(我已经更新到 1024)。在套接字中,不能保证您收到的消息,具体取决于网络负载等,因此最好尝试包装在while 循环中,这样在您到达可以向服务器发送消息的点之前不会丢失任何数据。也就是说,您的原始代码也可以(通常)工作,并且您需要处理一些极端情况(连接失败等)。 except 可能有很多例外,但这是我们如何处理向 telnet/ftp 发送命令的一般思路
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 2013-12-14
  • 2017-08-21
  • 2014-01-30
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多