Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~2 min readPython
#paramiko#ssh#python#remote-commands
Illustration of a Python script using Paramiko to connect to a remote server and execute commands over SSH.

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:

python
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:

python
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:

python
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.

python
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:

python
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:

python
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:

python
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:

python
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:

python
client.close()

SSHClient does not implement the context manager protocol directly, so use try/finally or wrap it in your own context manager:

python
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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.