2014-11-03 58 views
0

我正在使用python套接字連接到ftp.rediris.es,並且在發送數據後我沒有收到我期望的答案。我用我的代碼和答案更好地解釋這一點: 這是我的代碼(test.py)連接到FTP的Python套接字沒有收到我期望的內容

#!/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和完全看到的報頭。 會發生什麼?我是不是將命令發送給服務器?謝謝你在前進

+0

有關FTP協議的描述,請參閱RFC959,並實現您在那裏找到的內容。不要試圖猜測協議。 – 2014-11-03 14:21:01

回答

1

您可以檢查的220 Only anonymous FTP is allowed here最後一行已在telnetlib發送HELP消息,像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到首先。

+0

非常感謝你,這很有幫助。所以爲了確保我已經明白了,我的代碼無法正常工作,因爲我發送「HELP」的時間太快了?在收到我需要接收的所有信息之前。你把代碼放在那邊,爲什麼?因爲你一直都在接受你不是嗎?我沒有使用其他庫,因爲我習慣了套接字,我是新手,想從基礎開始。 – aDoN 2014-11-03 19:46:09

+0

@ user3515313,是和否。你的'.recv(65535)'應該真的是大塊讀取,而不是(我已經更新到1024)。在套接字中,您收到的消息不能保證,具體取決於網絡負載等,因此最好在「while」循環中嘗試換行,這樣在到達可以將消息發送到服務器的位置之前不會丟失任何數據。也就是說,你的原始代碼通常會起作用,並且你需要處理一些特殊情況(連接失敗等)。 *除*之外可能有許多例外,但這是一個普遍的想法,我們如何處理將命令發送到telnet/ftp – Anzel 2014-11-04 12:04:44