March 29, 2018
By: Wayne Dyck

How to copy a file to a remote server in Python using SCP

The easiest way I have found to securely copy a file to a remote server is using scpclient. scpclient is a python library that implements the client side of the SCP protocol. It is designed to be used with paramiko, a library for making SSH2 connections.

import paramiko
import scpclient

def scp_to_server():
    """ Securely copy the file to the server. """
    ssh_client = paramiko.SSHClient()
    ssh_client.connect("EXAMPLE.COM", username="USER_NAME", password="PASSWORD")

    with scpclient.closing(scpclient.Write(ssh_client.get_transport(), "~/")) as scp:
        scp.send_file("LOCAL_FILENAME", remote_filename="REMOTE_FILENAME")

If you didn't want to be dependent on third party libraries you could use the subprocess module. This module is included in the Python standard library. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes and obtain their return codes and is meant to replace older modules and functions like os.system.

Tags: Python