Skip to content

Lesson 4 of 9 · 25m

SSH Automation Without a Pile of shell=True

Using ssh, paramiko, and rsync deliberately: host-key checking, quoting remote commands, batching, sudo, and failure isolation.

SSH automation fails in boring ways until it fails spectacularly. The boring failures are host-key prompts, quoting mistakes, and one dead server blocking the rest. The spectacular failure is pushing the same bad command to four hundred machines because nobody built a blast-radius control.

Start with the real ssh client

For one host or a handful of hosts, OpenSSH is often better than a library because it uses existing keys, jump hosts, agents, and ~/.ssh/config:

cmd = [
    'ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8',
    '-o', 'StrictHostKeyChecking=accept-new',
    f'{user}@{host}', remote_command,
]
subprocess.run(cmd, check=True, timeout=30, capture_output=True, text=True)

BatchMode=yes turns interactive password and passphrase prompts into immediate failure. Automation should fail fast, not hang a scheduler.

Remote shell quoting is a separate problem

The remote side usually executes your command through a shell. Quote every variable with shlex.quote:

remote = 'systemctl restart ' + shlex.quote(service_name)

This is not optional merely because the value came from trusted YAML. Trusted coworkers paste strange strings; hostile input is only the final form of the problem.

rsync for trees, paramiko for sessions

Use rsync when moving directories; it understands incremental transfer and permissions better than handmade tar pipelines:

subprocess.run([
    'rsync', '-az', '--delete', '-e', 'ssh -o BatchMode=yes',
    str(local_dir) + '/', f'{user}@{host}:{remote_dir}/',
], check=True, timeout=600)

Trailing slashes matter: src/ means the contents of src, while src means the directory itself. --delete makes the mirror exact, which also means it can delete remote files; dry-run with -n when adapting a sync job.

Use paramiko when you need persistent sessions, SFTP, or channel control. Never use AutoAddPolicy in production — it disables server identity verification. Load system host keys, pin keys, or use SSH certificates.

Fleet execution is an operational plan

Capture per-host results, continue after individual failures, and report clearly. Then decide policy before running: canary first, concurrency limit, stop after N failures. Those are not library features; they are your safety design. sudo over SSH usually needs sudo -n, because an interactive password prompt is just another way to hang forever.

Field notes

  • Set explicit timeouts at connect, auth, command, and total-job layers where possible.
  • Kill a hanging SSH invocation and treat the host as unknown, not successful.
  • Prefer machine-readable probes (systemctl show -p ActiveState --value) over scraping human output.
  • Host-key verification authenticates the server; disabling it makes credential theft easy.

Was this lesson helpful?

Sign in to rate