FTP in Python
In Python, to create and maintain a FTP communication, the ftplib or urllib (explained in a future post) can be used.
Creating a FTP connection
from ftplib import FTP
try:
conn = FTP('almightybuserror.com')
except:
print "Could not connect to almightybuserror.com."
return
Logging in…
For anonymous log in:
try:
conn.login()
except:
print "No anonymous connections allowed."
return
Otherwise:
try:
conn.login(user, passwd)
print conn.getwelcome()
except:
print "Wrong username or password."
return
Sending commands and handling response.
To send commands (or requests) to the server there is a method for each command which can be consulted here, however I will show an example of an binary file download request.
try:
conn.cwd('/stuff/more/misc/stuff/')
except:
print "No such folder!"
return
file = open('stuff', 'w')
try: # file.write acts as a function pointer
conn.retrbinary('RETR stuff', file.write)
except:
print "Couldn't download stuff..."
finally:
file.close()
Check downloader.py in github for a more complete example.