Language: Python
Networking/CLI
Paramiko was created by Robey Pointer in 2003 to provide a pure-Python implementation of the SSHv2 protocol. It became a popular tool for automating server administration, remote command execution, and secure file transfers in Python applications.
Paramiko is a Python library for SSH2 protocol, providing both client and server functionality. It allows you to securely connect to remote machines, execute commands, transfer files over SFTP, and manage SSH sessions programmatically.
pip install paramikoconda install -c conda-forge paramikoParamiko provides SSH client and server implementations. You can connect to remote servers, run shell commands, upload and download files using SFTP, and handle keys and authentication. It supports password and key-based authentication, as well as SSH agent integration.
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('example.com', username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('ls -l')
print(stdout.read().decode())
ssh.close()Connects to a remote server via SSH, executes the `ls -l` command, prints the output, and closes the connection.
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
private_key = paramiko.RSAKey.from_private_key_file('/path/to/key.pem')
ssh.connect('example.com', username='user', pkey=private_key)
stdin, stdout, stderr = ssh.exec_command('uptime')
print(stdout.read().decode())
ssh.close()Uses an RSA private key for authentication instead of a password to connect to a remote server.
import paramiko
transport = paramiko.Transport(('example.com', 22))
transport.connect(username='user', password='pass')
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put('local_file.txt', 'remote_file.txt')
sftp.get('remote_file.txt', 'local_copy.txt')
sftp.close()
transport.close()Uploads a local file to a remote server and downloads a file back using SFTP.
import paramiko
with paramiko.SSHClient() as ssh:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('example.com', username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('whoami')
print(stdout.read().decode())Uses a context manager to automatically handle SSH connection closing.
import paramiko
agent = paramiko.Agent()
keys = agent.get_keys()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('example.com', username='user', pkey=keys[0])Uses keys from an SSH agent for authentication.
Always handle missing host keys with `AutoAddPolicy()` or manually add known hosts.
Prefer key-based authentication over passwords for better security.
Close SSH and SFTP connections properly to release resources.
Use paramiko logging to debug connection and authentication issues.
For long-running scripts, handle network interruptions and reconnections.