In this chapter, we’ll concentrate on the FTP and email protocol modules in Python, and we’ll peek at a few others along the way (NNTP news, HTTP web pages, and so on).
FTP lets us ask for files from any server machine that supports FTP, without requiring that it run our custom getfile script. FTP also supports more advanced op- erations such as uploading files to the server, getting remote directory listings, and more.
Really, FTP runs on top of two sockets: one for passing control commands between client and server (port 21), and another for transferring bytes. By using a two-socket model, FTP avoids the possibility of deadlocks (i.e., transfers on the data socket do not block dialogs on the control socket). Ultimately, though, Python’s ftplib support module allows us to upload and download files at a remote server machine by FTP, without dealing in raw socket calls or FTP protocol details.
A Python script to download and play a media file by FTP. Uses ftplib, the ftp protocol handler which uses sockets. Ftp runs on 2 sockets (one for data, one for control--on ports 20 and 21) and imposes message text formats, but Python's ftplib module hides most of this protocol's details. Change for your site/file.
import sys
from getpass import getpass
from ftplib import FTP
nonpassive = False
fliename = 'monkeys.jpg'
dirname = '.'
sitename = 'ftp.rmi.net'
userinfo = ('lutz', getpass('Pswd?'))
if len(sys.argv) > 1:filename = sys.argv[1]
print 'Connecting...'
conncetion = FTP(sitename)
conncetion.login(*useinfo)
conncetion.cwd(dirname)
if nonpassive: # force active FTP if server requires
connection.set_pasv(False)
print 'Downloading'
localfile = open(filename,'wb')
conncetion.retrbinary('RETR ' + filename, localfile.write, 1024)
connection.quit()
localfile.close()
if input('Open file?') in ['Y', 'y']:
from PP4E.System.Media.playfile import playfile
playfile(filename)
connection.retrbinary('RETR ' + filename, localfile.write, 1024)
Once we’re in the target remote directory, we simply call the retrbinary method to download the target server file in binary mode. The retrbinary call will take a while to complete, since it must download a big file. It gets three arguments:
format for FTP retrievals.
bytes; here, the write method of a newly created and opened local file.
the default is reasonable if this argument is omitted.