Python SCP Client

0.15.0 · active · verified Mon Apr 06

The `scp.py` module, currently at version 0.15.0, provides a pure-Python implementation of the SCP1 (Secure Copy Protocol) client. It leverages the `paramiko` library for SSH transport, enabling secure file transfers over SSH connections, mirroring the functionality of the OpenSSH `scp` program. The library is actively maintained but follows an irregular release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SSH connection using `paramiko.SSHClient` and then use `scp.SCPClient` to upload and download a file. It includes important considerations for host key policy and proper connection closure.

import os
from paramiko import SSHClient, AutoAddPolicy
from scp import SCPClient

# Configuration from environment variables for security
HOSTNAME = os.environ.get('SCP_HOSTNAME', 'your_remote_host')
USERNAME = os.environ.get('SCP_USERNAME', 'your_username')
PASSWORD = os.environ.get('SCP_PASSWORD', '') # Use SSH keys in production

local_file = 'local_test_file.txt'
remote_path = '/tmp/remote_test_file.txt'

# Create a dummy local file for the example
with open(local_file, 'w') as f:
    f.write('Hello from scp.py!')

ssh = SSHClient()
# Set policy to auto-add host keys for demo. In production, use ssh.load_system_host_keys() or HostKeys().add().
ssh.set_missing_host_key_policy(AutoAddPolicy()) 

try:
    # Connect to the remote server
    ssh.connect(hostname=HOSTNAME, username=USERNAME, password=PASSWORD, port=22)
    print(f"Connected to {HOSTNAME}")

    # SCPCLient takes a paramiko transport as an argument
    with SCPClient(ssh.get_transport()) as scp:
        # Upload a file
        scp.put(local_file, remote_path)
        print(f"Uploaded '{local_file}' to '{remote_path}'")

        # Download the file back to verify
        downloaded_file = 'downloaded_test_file.txt'
        scp.get(remote_path, downloaded_file)
        print(f"Downloaded '{remote_path}' to '{downloaded_file}'")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    ssh.close()
    print("SSH connection closed.")

# Clean up dummy files
import os
if os.path.exists(local_file):
    os.remove(local_file)
if os.path.exists(downloaded_file):
    os.remove(downloaded_file)

view raw JSON →