Python SSH Remote Host Automation with Paramiko or Fabric Prompt
Generate safe, idempotent remote-host automation in Python using Fabric or Paramiko — connection reuse, command checks, file transfer, and proper failure handling across many hosts.
- Target user
- DevOps engineers automating tasks across remote servers in Python
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a senior infrastructure engineer who automates remote servers without turning a fleet into a smoking crater.
I will provide:
- The hosts (inventory source) and how I authenticate (key, agent, bastion/jump host)
- The tasks to perform (run commands, deploy files, restart services)
- Whether tasks must be idempotent and whether they can run in parallel
Build a Python tool using **Fabric** (preferred for ergonomics) or **Paramiko** (when low-level control is needed) that:
1. **Connects safely** — load keys from the agent or a path, verify host keys (do NOT auto-add unknown keys in prod — use a known_hosts policy), and support a jump/bastion host. Never embed passwords; pull secrets from env/secret manager.
2. **Runs commands with checks** — capture stdout/stderr and exit code; treat non-zero as failure unless explicitly allowed (`warn=True`). Set per-command timeouts so a hung host can't block the run.
3. **Is idempotent** — guard mutating actions ("install only if absent", "write file only if checksum differs", "restart only if config changed"). Re-running should be a no-op when nothing changed.
4. **Transfers files correctly** — checksum before/after, set ownership/permissions explicitly, and write to a temp path then move into place on the remote.
5. **Handles many hosts** — run across the fleet with bounded parallelism; collect per-host results; one host's failure must not abort the others. Print a clear pass/fail summary table at the end.
6. **Supports dry-run** — a `--check`/`--dry-run` mode that prints what WOULD change without executing mutations.
7. **Cleans up** — close connections in `finally`/context managers; no leaked sessions.
8. **Is observable** — structured per-host logs, and a non-zero overall exit code if any host failed.
Output: (a) the connection/runner module, (b) a task definition for my use case, (c) the parallel fleet driver with the summary table, (d) a dry-run example, (e) notes on host-key policy and secrets.
Bias toward: idempotent guards, explicit host-key verification, bounded concurrency, and failures that are loud and isolated.