# Ftptest.py - An example application using Python's ftplib module # Author: Matt Croydon
# Import the FTP Object from FTPLIBFROM FTPLIB IMPORT FTP
# This will handle the data being downloaded # It will be explained shortlydef handleDownload (block): "." File.write (block) print, # Create an instance of the FTP object # Optionally, you could specify username and password: # FTP ('Hostname', 'PASSWORD') FTP = FTP ('ftp.cdrom.com')
print 'Welcome to Matt's ftplib example' # Log in to the serverprint # You can specify username and password here if you like 'Logging in.': # ftp.login ( 'username', 'password') # Otherwise, it defaults to AnonymousPrint ftp.login ()
# This is the directory that we want to go todirectory = 'pub / simtelnet / trumpet / winsock' # Let's change to that directory. You kids might call these 'folders'print' Changing to ' directoryftp.cwd (directory)
#Print the contents of the directoryftp.retrlines ('list')
# Here's a file for us to play with. Remember Trumpet Winsock? Filename = 'WinAP
21F
.zip '
# Open the file for Writing in binary modeprint 'opening local file' filenamefile = Open (filename, 'wb')
# Download the file a chunk at a time # Each chunk is sent to handleDownload # We append the chunk to the file and then print a '.' For progress # RETR is an FTP commandprint 'Getting' filenameftp.retrbinary ( 'RETR' FileName, Handledownload # Clean Up TimePrint 'Closing File' FileNameFile.Close ()
Print 'Closing FTP Connection'Print ftp.close ()