How to transfer files and directories using paramiko

Paramiko is a popular Python library used for SSH remote server automation. We guide you through the process of transferring files and directories using Paramiko.

Setting Up

Ensure you have Paramiko installed:

pip install paramiko

Establishing SSH Connection


import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='your_hostname', username='your_username', password='your_password')

            

Transferring Files

To transfer files, use the SFTP client as follows:


sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)  # For uploading
sftp.get(remotepath, localpath)  # For downloading
sftp.close()

            

Transferring Directories

Paramiko does not directly support transferring directories. You’ll need to create a recursive function to handle directories.

See also  Reconnecting with Paramiko After a Reboot in Python

Closing the Connection

Don’t forget to close your connection after the transfer is complete:


ssh.close()