Python Paramiko: Connect over SSH and Run Remote Commands
Use Python Paramiko to SSH into a server, authenticate with a password or key, execute commands, check output, and close connections cleanly.

Paramiko is a Python library for working with the SSH protocol. With SSHClient, you can open an SSH connection to a remote server, run commands with exec_command, read their output, and close the connection when done.
Connecting with Paramiko
The minimal connection looks like this:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('example.com', username='user', password='pass')AutoAddPolicy automatically accepts an unfamiliar host key. That is convenient for testing, but it skips host key verification and is not recommended for production. The security section below shows a stricter alternative.
Authenticating with Password or SSH Key
Paramiko supports password authentication and key-based authentication. For a private key, pass the key path to connect or load the key first:
key = paramiko.RSAKey.from_private_key_file('/path/to/id_rsa')
client.connect('example.com', username='user', pkey=key)If the key is protected by a passphrase, provide it with the password parameter:
key = paramiko.RSAKey.from_private_key_file('/path/to/id_rsa', password='passphrase')Password authentication is simpler, but avoid hardcoding passwords in source code. Read them from environment variables or a secrets manager instead.
Executing Commands on the Remote Host
exec_command sends one command to the remote host and returns three file-like objects: stdin, stdout, and stderr.
stdin, stdout, stderr = client.exec_command('ls -la')
print(stdout.read().decode())The SSH server normally invokes the command through the user's shell, so shell features such as pipes and redirection usually work. The command is not an interactive terminal session, so if you build commands from dynamic values, quote them carefully or use a library such as shlex.quote.
Handling Command Output and Exit Status
For commands that produce a moderate amount of output, read both stdout and stderr before checking the exit status:
stdin, stdout, stderr = client.exec_command('ls -la')
out = stdout.read().decode()
err = stderr.read().decode()
exit_status = stdout.channel.recv_exit_status()
if exit_status == 0:
print('Success:', out)
else:
print('Error:', err)Do not call recv_exit_status() before reading the output streams. If the command produces enough output to fill the channel buffers, the remote process can block before it exits. For large output, read the streams incrementally or concurrently so the remote command can keep writing.
Error Handling and Connection Robustness
Authentication and network failures raise exceptions. Catch the relevant Paramiko exceptions and OSError for network-level errors:
try:
client.connect('example.com', username='user', password='pass')
except paramiko.AuthenticationException:
print('Authentication failed')
except paramiko.SSHException as e:
print('SSH error:', e)
except OSError as e:
print('Network error:', e)Set a timeout on connect() so the call does not hang indefinitely:
client.connect('example.com', username='user', password='pass', timeout=10)Security Considerations for SSH Automation
Host key verification protects against man-in-the-middle attacks. For production automation, load the system known-hosts file and reject unknown host keys instead of using AutoAddPolicy:
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.RejectPolicy())Keep credentials out of code. Use environment variables, a secrets manager, or an SSH agent, and avoid hardcoding passwords.
Reusing Connections and Resource Cleanup
Opening a new SSH connection for every command is expensive. Reuse the same SSHClient for multiple commands, then close it when your script is done:
client.close()SSHClient does not implement the context manager protocol directly, so use try/finally or wrap it in your own context manager:
client = paramiko.SSHClient()
try:
client.connect('example.com', username='user', password='pass')
# run your commands
finally:
client.close()For long-running scripts, plan to reconnect after network failures or server timeouts.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.