Python Paramiko SSH Connect Execute Commands
python paramiko ssh connect execute commands: Learn how to use Python Paramiko to SSH connect and execute remote commands, handle output, and manage authentication sec...
python paramiko ssh connect execute commands requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.
When you need to use Python Paramiko to SSH connect and execute commands on a remote server, the library provides a straightforward API. The typical workflow is to create an SSHClient, set a policy for unknown host keys, connect with credentials, and then run commands using exec_command.
Here's a minimal connection:
import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('example.com', username='user', password='pass')
AutoAddPolicy automatically adds the host key to known hosts, which is convenient for testing but not recommended for production. We'll cover host key verification later.
Authenticating with Password or SSH Key
Paramiko supports password and key-based authentication. For key-based, you can pass the path to a private key or load it explicitly.
key = paramiko.RSAKey.from_private_key_file('/path/to/id_rsa') client.connect('example.com', username='user', pkey=key)
If your key is encrypted, you can provide a passphrase:
key = paramiko.RSAKey.from_private_key_file('/path/to/id_rsa', password='passphrase')
Password authentication is simpler but less secure if the password is hardcoded. Prefer environment variables or a secrets manager.
Executing Commands on the Remote Host
The exec_command method sends a command to the remote shell and returns three file-like objects: stdin, stdout, and stderr.
stdin, stdout, stderr = client.exec_command('ls -la') print(stdout.read().decode())
The command runs in the user's default shell, so you can use shell features like pipes and redirection. However, be careful with quoting when passing dynamic arguments.
Handling Command Output and Exit Status
After reading stdout and stderr, check the exit status using recv_exit_status().
exit_status = stdout.channel.recv_exit_status() if exit_status == 0: print('Success') else: print('Error:', stderr.read().decode())
Reading stdout before checking status can block if the command produces a lot of output. Use read() with caution or read line by line for large outputs.
Error Handling and Connection Robustness
Network issues and authentication failures raise exceptions. Catch paramiko.AuthenticationException, socket.error, and paramiko.SSHException to handle them gracefully.
try: client.connect(...) except paramiko.AuthenticationException: print('Authentication failed') except paramiko.SSHException as e: print('SSH error:', e)
Set a connection timeout to avoid hanging:
client.connect(..., timeout=10)
Security Considerations for SSH Automation
Host key verification is critical. AutoAddPolicy is vulnerable to man-in-the-middle attacks. Instead, load the known hosts file and use RejectPolicy or WarningPolicy.
client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.RejectPolicy())
Store credentials in environment variables or use an SSH agent. Avoid hardcoding passwords in source code.
Reusing Connections and Resource Cleanup
Creating a new SSH connection for each command is expensive. Reuse the same client for multiple commands, and close it when done.
client.close()
Use context managers if available (Paramiko's SSHClient does not implement __enter__ directly, but you can wrap it). For long-running scripts, consider keeping the connection alive and reconnecting on failure.