Search code examples
pythonsocketstcpftpserversocket

Python Sockets connect to FTP don't receive what I expect


I am using python socket to connect to ftp.rediris.es and I don't receive the answer I expect after sending data. I explain this better with my code and answers: This is my code (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

This is the answer when I run the code:

 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

And this is what I expect:

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

I have tried this on the port 80 towards www.google.com, sending a GET / HTTP/1.1\r\n\r\n and seen the header perfectly. What happens¿? Am I not sending the command right to the server¿? Thank you in advance


Solution

  • You may check if the last line of 220 Only anonymous FTP is allowed here has been received before sending the HELP message, something like read_until in telnetlib.

    Like this, it works for me:

    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
    

    Printout:

    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/
    

    That said though, not entirely sure why you haven't chosen the more suitable modules like ftplib or telnetlib to begin with.