Last active
April 7, 2025 02:54
-
-
Save nakagami/64364dde25711dd4d5d3f811571176f2 to your computer and use it in GitHub Desktop.
Upload files recursive via scp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copy directory recursive to remote SFTP server by scp | |
# scp use SFTP protocol | |
# need to install `parammiko` and `scp` | |
# https://pypi.org/project/paramiko/ | |
# https://pypi.org/project/scp/ | |
import paramiko | |
import scp | |
# Change these to their actual values | |
HOSTNAME = "hostname" | |
PORT = 22 | |
USERNAME = "username" | |
PRIVATE_KEY_PATH = "/absolute/path/to/private_key" | |
SRC_DIR = "/absolute/path/to/src_dir" | |
DEST_DIR = "/absolute/path/to/dest_dir" | |
REMOTE_DIR = "somewhere/relative" | |
# for Ed25519 key | |
# pkey = paramiko.Ed25519Key.from_private_key_file(PRIVATE_KEY_PATH) | |
# for RSA key | |
pkey = paramiko.RSAKey.from_private_key_file(PRIVATE_KEY_PATH) | |
with paramiko.SSHClient() as ssh_client: | |
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
ssh_client.connect(HOSTNAME, PORT, USERNAME, pkey=pkey) | |
# Upload | |
# Make directory `somewhere/relative/src_dir` on remote server `hostname` automaticary, | |
# and copy under `/absolute/path/to/src_dir` files | |
with scp.SCPClient(ssh_client.get_transport()) as scp_client: | |
scp_client.put(SRC_DIR, REMOTE_DIR, recursive=True) | |
# Donwload | |
# Make sub directory to local DEST_DIR directory | |
with scp.SCPClient(ssh_client.get_transport()) as scp_client: | |
scp_client.get(REMOTE_DIR, DEST_DIR, recursive=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment