Python Remote Commands with Paramiko
paramiko gives you SSH without shelling out to ssh, which means the host key check, the exit status and every timeout become your decisions rather than OpenSSH's. This guide makes each of them explicitly: AutoAddPolicy is what StrictHostKeyChecking=no looks like in Python, a failing command raises nothing at all, a remote command gets a non-login shell, and a command that outlives its timeout carries on running on the far end.
Remote Hosts and CI/CD Guide 31 of 39 Advanced
- Control nodeUbuntu 26.04 LTS
- Managed hostsRHEL 10.0
- Python3.14.4
- requests2.34.2
- TimeAbout 22 min
paramiko 5.0.0. paramiko.RejectPolicy is the default and always has been. Note paramiko depends on invoke, which imports the stdlib pty - which is why one step here fails.
- paramiko5.0.0
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
| RHCSA-A01 | 192.168.0.31 | RHEL 10.0 | Managed host - reached over SSH from the control node | 2 Core | 4 GB | 50 GB |
| RHCSA-B01 | 192.168.0.33 | RHEL 10.0 | Second managed host - so an inventory has more than one row | 2 Core | 4 GB | 50 GB |
This guide includes
Use this to run commands on other hosts without shelling out to ssh. This matters because paramiko makes the host key policy your decision - and a remote command gets a non-login shell with almost no environment.
- connecting and running one command, then trusting the keys ssh already holds
- seeing the host key policy for what it is, a security decision
- handling a command that fails, and reading the environment a remote command gets
- meeting the filename that breaks the import, and getting a pseudo-terminal once it is renamed
- setting all four timeouts, and reducing the whole thing to one helper
Before you start
- guide 17 - the local equivalent, and the argument list.
- guide 19 - the environment question, again.
- guide 21 - timeouts, now across a network.
-
The two hosts, and what ssh already knows about them
-
A first connection, and one command
-
The host key policy, which is a security decision
-
So use the keys ssh already trusts
-
A command that fails
-
The environment a remote command gets
-
A filename that breaks the import
-
So rename it, and get_pty works
-
Timeouts, of which there are four
-
One helper, used twice