Learning Python Network Programming

(Sean Pound) #1
Chapter 5

In the following code snippet, an example of a full FTP file download can be seen:


#!/usr/bin/env python
import ftplib

FTP_SERVER_URL = 'ftp.kernel.org'
DOWNLOAD_DIR_PATH = '/pub/software/network/tftp'
DOWNLOAD_FILE_NAME = 'tftp-hpa-0.11.tar.gz'

def ftp_file_download(path, username, email):
# open ftp connection
ftp_client = ftplib.FTP(path, username, email)
# list the files in the download directory
ftp_client.cwd(DOWNLOAD_DIR_PATH)
print("File list at %s:" %path)
files = ftp_client.dir()
print(files)
# downlaod a file
file_handler = open(DOWNLOAD_FILE_NAME, 'wb')
#ftp_cmd = 'RETR %s ' %DOWNLOAD_FILE_NAME
ftp_client.retrbinary('RETR tftp-hpa-0.11.tar.gz',
file_handler.write)
file_handler.close()
ftp_client.quit()

if __name__ == '__main__':
ftp_file_download(path=FTP_SERVER_URL, username='anonymous',
email='[email protected]')

The preceding code illustrates how an anonymous FTP can be downloaded from
ftp.kernel.org, which is the official website that hosts the Linux kernel. The FTP()
class takes three arguments, such as the initial filesystem path on the remote server,
the username, and the email address of the ftp user. For anonymous downloads,
no username and password is required. So, the script can be downloaded from the
tftp-hpa-0.11.tar.gz file, which can be found on the /pub/software/network/
tftp path.

Free download pdf