Learning Python Network Programming

(Sean Pound) #1

Interacting with Remote Systems


In this example, a file has been downloaded with the help of SFTP. Notice,
how paramiko has created the SFTP session by using the SFTPClient.from_
transport(ssh_transport) class.


The script can be run as shown in the following screenshot. Here, we will first create
a temporary file called /tmp/test.txt, then complete the SSH login, and then
download that file by using SFTP. Lastly, we will check the content of the file.


Transferring files with FTP


Unlike SFTP, FTP uses the plain-text file transfer method. This means any
username or password transferred through the wire can be detected by an
unrelated third-party. Even though FTP is a very popular file transfer protocol,
people frequently use this for transferring a file from their PCs to the remote servers.


In Python, ftplib is a built-in module used for transferring the files to and from
the remote machines. You can create an anonymous FTP client connection with the
FTP() class.


ftp_client = ftplib.FTP(path, username, email)

Then you can invoke the normal FTP commands, such as CWD. In order to download
a binary file, you need to create a file-handler such as the following:


file_handler = open(DOWNLOAD_FILE_NAME, 'wb')

In order to retrieve the binary file from the remote host, the syntax shown here can
be used along with the RETR command:


ftp_client.retrbinary('RETR remote_file_name', file_handler.write)
Free download pdf