
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to copy a file to a remote server in Python using SCP or SSH?
When we want to transfer files from our local system to a remote server securely, Python provides possible ways to do the file transfer using the Paramiko and SCP libraries.
These libraries support SSH-based file transfer, which is secure and reliable.
Installing Required Libraries
Before we start with file transfer, we need to install all the required libraries with the help of below commands -
pip install paramiko scp
Using paramiko and SCP/SSH
Paramiko is a third-party library available in Python, which is used to transfer a file to a remote server without using an external SCP module. This provides both SSH and SFTP functionality with the help of the SSHv2 protocol.
SCP stands for Secure Copy Protocol, which is used to copy files between computers over a secure SSH connection. SSH stands for Secure Shell, and it provides a secure channel over an unsecured network.
By combining the SCP and SSH tools with Paramiko in Python, we can perform secure file transfers by using a Python script.
Following is the Python script which copies a file to a server in Python using SCP or SSH tools -
import paramiko from scp import SCPClient # Remote server credentials hostname = '192.168.1.10' port = 22 username = 'admin' password = 'mypassword' # File to be copied local_file_path = 'sample.txt' remote_path = './home/admin/sample.txt' # Create SSH client ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Connect to the server ssh.connect(hostname=hostname, port=port, username=username, password=password) # SCP file transfer with SCPClient(ssh.get_transport()) as scp: scp.put(local_file_path, remote_path) print("File copied successfully!") except Exception as e: print(f"Error: {e}") finally: ssh.close()
The above program prints the text "File copied successfully" if the transfer is done; otherwise raises an error.