Paramiko is a powerful Python library used for SSH (Secure Shell) automation. It allows you to automate remote server access, execute commands, transfer files, and manage SSH connections.
1. Installing Paramiko
Before using Paramiko, install it via pip:
pip install paramiko
2. Establishing an SSH Connection
To connect to a remote server using username & password:
import paramiko
host = "your.server.com"
port = 22
username = "your_username"
password = "your_password"
# Create SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Auto-accepts unknown hosts
# Connect to the server
ssh.connect(hostname=host, port=port, username=username, password=password)
# Run a command
stdin, stdout, stderr = ssh.exec_command("ls -l")
print(stdout.read().decode()) # Output the command result
# Close the connection
ssh.close()
✔ set_missing_host_key_policy(paramiko.AutoAddPolicy())
→ Automatically accepts unknown SSH keys.
✔ exec_command("command")
→ Runs a shell command remotely.
3. Using SSH Key Authentication
For more security, use SSH keys instead of passwords:
private_key_path = "/path/to/private/key"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Load private key
private_key = paramiko.RSAKey(filename=private_key_path)
# Connect using the private key
ssh.connect(hostname=host, port=port, username=username, pkey=private_key)
stdin, stdout, stderr = ssh.exec_command("whoami")
print(stdout.read().decode())
ssh.close()
✔ Uses RSA private key authentication instead of passwords.
✔ More secure and avoids storing plaintext passwords.
4. Transferring Files via SFTP
Paramiko supports SFTP (Secure File Transfer Protocol) to upload and download files.
📂 Uploading a File
sftp = ssh.open_sftp()
sftp.put("local_file.txt", "/remote/path/remote_file.txt")
sftp.close()
ssh.close()
✔ put(local, remote)
→ Uploads a local file to a remote server.
📂 Downloading a File
sftp = ssh.open_sftp()
sftp.get("/remote/path/remote_file.txt", "local_file.txt")
sftp.close()
ssh.close()
✔ get(remote, local)
→ Downloads a file from the remote server.
5. Automating Multiple Commands
Instead of opening multiple connections, use shell interaction:
shell = ssh.invoke_shell()
shell.send("cd /var/logs\n")
shell.send("ls -la\n")
shell.send("exit\n")
output = shell.recv(4096)
print(output.decode())
ssh.close()
✔ invoke_shell()
→ Opens an interactive SSH session.
✔ send("command\n")
→ Sends commands like a real SSH session.
6. Running Commands on Multiple Servers
Automate SSH tasks across multiple servers:
servers = [
{"host": "server1.com", "user": "user1", "password": "pass1"},
{"host": "server2.com", "user": "user2", "password": "pass2"},
]
for server in servers:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server["host"], username=server["user"], password=server["password"])
stdin, stdout, stderr = ssh.exec_command("uptime")
print(f"Server: {server['host']} - Uptime: {stdout.read().decode()}")
ssh.close()
✔ Loops through multiple servers, executing the same command remotely.
✔ Useful for batch server automation.
7. Handling Errors Gracefully
Always handle exceptions to avoid script crashes:
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="wrong_host", username="user", password="pass")
except paramiko.AuthenticationException:
print("Authentication failed.")
except paramiko.SSHException as e:
print(f"SSH error: {e}")
finally:
ssh.close()
✔ Catches authentication and SSH errors.
✔ finally
ensures proper cleanup.
8. Automating SSH Commands on a Schedule
Use cron jobs (Linux) or Task Scheduler (Windows) to run scripts at intervals.
Example: Automate server monitoring every hour:
import paramiko
import time
def monitor_server():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="your.server.com", username="your_user", password="your_pass")
stdin, stdout, stderr = ssh.exec_command("df -h")
print(stdout.read().decode())
ssh.close()
while True:
monitor_server()
time.sleep(3600) # Run every 1 hour
✔ Checks disk space (df -h
) every hour.
✔ Can be modified for CPU, memory, or log monitoring.
9. Deploying Paramiko Scripts on a Server
- Upload your script to a Linux server.
- Make it executable:
chmod +x script.py
- Run it in the background: bashCopyEdit
nohup python3 script.py &