Transferring files through SFTP

SSH can be used effectively for securely transferring files between two computer nodes. The protocol used in this case is the secure file transfer protocol (SFTP). The Python paramiko module will supply the classes required for creating the SFTP session. This session can then perform a regular SSH login.

ssh_transport = paramiko.Transport(hostname, port)
ssh_transport.connect(username='username', password='password')

The SFTP session can be created from the SSH transport. The paramiko's working in the SFTP session will support the normal FTP commands such as get().

 sftp_session = paramiko.SFTPClient.from_transport(ssh_transport)
 sftp_session.get(source_file, target_file)

As you can see, the SFTP get command requires the source file's path and the target file's path. In the following example, the script will download a test.txt file, which is located on the user's home directory, through SFTP:

#!/usr/bin/env python3

import getpass
import paramiko

HOSTNAME = 'localhost'
PORT = 22
FILE_PATH = '/tmp/test.txt'

def sftp_download(username, password, hostname=HOSTNAME, port=PORT):
    ssh_transport = paramiko.Transport(hostname, port)
    ssh_transport.connect(username=username, password=password)
    sftp_session = paramiko.SFTPClient.from_transport(ssh_transport)
    file_path = input("Enter filepath: ") or FILE_PATH
    target_file = file_path.split('/')[-1]
    sftp_session.get(file_path, target_file)
    print("Downloaded file from: %s" %file_path)
    sftp_session.close()
    
if __name__ == '__main__':
    hostname = input("Enter the target hostname: ")
    port = input("Enter the target port: ")
    username = input("Enter yur username: ")
    password = getpass.getpass(prompt="Enter your password: ")
    sftp_download(username, password, hostname, int(port))

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 through SFTP
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.37.12