Python is the system administrator's secret weapon. With the right libraries, you can automate virtually any infrastructure task. These 10 libraries are essential for every sysadmin who uses Python in their daily work.
1. Paramiko ā SSH Automation
Execute commands on remote servers programmatically:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.1.10", username="admin", key_filename="/home/user/.ssh/id_ed25519")
stdin, stdout, stderr = ssh.exec_command("df -h")
print(stdout.read().decode())
ssh.close()
2. psutil ā System Monitoring
Get real-time system information ā CPU, memory, disk, network:
import psutil
# CPU usage
print(f"CPU: {psutil.cpu_percent(interval=1)}%")
# Memory
mem = psutil.virtual_memory()
print(f"RAM: {mem.percent}% used ({mem.used // (1024**3)}GB / {mem.total // (1024**3)}GB)")
# Disk
for partition in psutil.disk_partitions():
usage = psutil.disk_usage(partition.mountpoint)
print(f"{partition.mountpoint}: {usage.percent}% used")
3. Requests ā HTTP API Calls
import requests
# Check website status
response = requests.get("https://example.com", timeout=10)
print(f"Status: {response.status_code}")
# API call with authentication
api_response = requests.get(
"https://api.example.com/servers",
headers={"Authorization": "Bearer YOUR_TOKEN"}
)
servers = api_response.json()
4. Click ā CLI Tool Builder
import click
@click.command()
@click.option("--server", required=True, help="Server hostname")
@click.option("--action", type=click.Choice(["start", "stop", "restart"]))
def manage_server(server, action):
"""Manage remote server services."""
click.echo(f"Performing {action} on {server}...")
if __name__ == "__main__":
manage_server()
5. Jinja2 ā Configuration Templates
from jinja2 import Template
template = Template("""
server {
listen {{ port }};
server_name {{ domain }};
root {{ webroot }};
}
""")
config = template.render(
port=443,
domain="example.com",
webroot="/var/www/example"
)
print(config)
6. PyYAML ā YAML Configuration
import yaml
# Read YAML configuration
with open("config.yml", "r") as f:
config = yaml.safe_load(f)
# Write YAML
data = {"servers": ["web01", "web02"], "port": 8080}
with open("output.yml", "w") as f:
yaml.dump(data, f, default_flow_style=False)
7. Schedule ā Task Scheduling
import schedule
import time
def check_disk_space():
print("Checking disk space...")
def backup_database():
print("Running database backup...")
schedule.every(5).minutes.do(check_disk_space)
schedule.every().day.at("02:00").do(backup_database)
while True:
schedule.run_pending()
time.sleep(1)
8. Watchdog ā File System Monitoring
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class ConfigChangeHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"Config changed: {event.src_path}")
observer = Observer()
observer.schedule(ConfigChangeHandler(), path="/etc/nginx/", recursive=True)
observer.start()
9. Fabric ā Remote Execution
from fabric import Connection
# Execute commands on remote server
c = Connection("web01.example.com", user="admin")
result = c.run("uptime", hide=True)
print(f"Server uptime: {result.stdout.strip()}")
# Deploy application
c.put("deploy.sh", remote="/tmp/deploy.sh")
c.run("bash /tmp/deploy.sh")
10. Rich ā Beautiful Terminal Output
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(title="Server Status")
table.add_column("Server", style="cyan")
table.add_column("Status", style="green")
table.add_column("CPU", justify="right")
table.add_column("Memory", justify="right")
table.add_row("web01", "Online", "45%", "62%")
table.add_row("web02", "Online", "38%", "55%")
table.add_row("db01", "Online", "72%", "81%")
console.print(table)
Master these libraries and Python becomes the most powerful tool in your system administration toolkit.