Interview Prep/Python for DevOps/Kubernetes, Docker & SSH clients

What is paramiko, and how do you run a command over SSH with it?

BeginnerConceptKubernetes, Docker & SSH clients
Answer

paramiko is a pure-Python SSHv2 implementation.

import paramiko
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
ssh.connect("10.0.1.15", username="ec2-user", key_filename="~/.ssh/ops.pem", timeout=10)
stdin, stdout, stderr = ssh.exec_command("uptime")
rc = stdout.channel.recv_exit_status()
print(rc, stdout.read().decode())
ssh.close()

AutoAddPolicy is convenient but trusts any host key on first connect (MITM risk); in production pre-populate known_hosts and reject unknown keys.

All Python for DevOps questions Roadmap: Python for automation

More on Kubernetes, Docker & SSH clients