Lesson 26 of 34
Paramiko: SSH & SFTP
Paramiko lets Python securely run commands and transfer files over SSH. Use it for systems you own or are explicitly authorized to administer.
python -m pip install paramiko
# Prefer an SSH key protected by a passphrase
ssh-keygen -t ed25519 -C "automation"
# Add the public key to the authorized server by an approved methodfrom pathlib import Path
import os
import paramiko
host = os.environ["DEPLOY_HOST"]
user = os.environ["DEPLOY_USER"]
key_path = Path.home() / ".ssh" / "id_ed25519"
client = paramiko.SSHClient()
# Load known_hosts and reject unknown or changed host keys.
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.RejectPolicy())
try:
client.connect(
hostname=host,
username=user,
key_filename=str(key_path),
timeout=10,
banner_timeout=10,
auth_timeout=10,
)
stdin, stdout, stderr = client.exec_command("uptime", timeout=15)
exit_code = stdout.channel.recv_exit_status()
output = stdout.read().decode().strip()
errors = stderr.read().decode().strip()
if exit_code != 0:
raise RuntimeError(errors or f"remote exit code {exit_code}")
print(output)
finally:
client.close()# SFTP uses the same encrypted SSH connection
with paramiko.SSHClient() as client:
client.load_system_host_keys()
client.connect(host, username=user, key_filename=str(key_path))
with client.open_sftp() as sftp:
sftp.put("report.csv", "/srv/reports/report.csv")
sftp.get("/srv/reports/result.json", "result.json")
for item in sftp.listdir_attr("/srv/reports"):
print(item.filename, item.st_size)
# For many hosts, put connection logic in a function, collect a result
# object per host, limit concurrency, and log failures without abandoning
# the rest of the fleet.Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.