System Administration Scripts
Monitor system health, automate backups, and manage processes with Python.
The Admin's Swiss Army Knife
Python is the perfect language for system glue code. It replaces complex shell scripts with readable, maintainable logic.
System Monitoring (psutil)
psutil provides cross-platform info on CPU, memory, disks, and network.
import psutil
# CPU Usage
print(f"CPU: {psutil.cpu_percent()}%")
# Memory Usage
mem = psutil.virtual_memory()
print(f"Memory: {mem.percent}%")
# Disk Usage
disk = psutil.disk_usage('/')
print(f"Disk Space: {disk.percent}%")
# CPU Usage
print(f"CPU: {psutil.cpu_percent()}%")
# Memory Usage
mem = psutil.virtual_memory()
print(f"Memory: {mem.percent}%")
# Disk Usage
disk = psutil.disk_usage('/')
print(f"Disk Space: {disk.percent}%")
Executing Commands (subprocess)
Use subprocess.run to call external binaries safely.
import subprocess
# Run a command and get output
res = subprocess.run(['ls', '-la'], capture_output=True, text=True)
print(res.stdout)
# Run a command and get output
res = subprocess.run(['ls', '-la'], capture_output=True, text=True)
print(res.stdout)
Automated Backups
import shutil
from datetime import datetime
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
shutil.make_archive(f"backup_{timestamp}", 'zip', '/path/to/source')
from datetime import datetime
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
shutil.make_archive(f"backup_{timestamp}", 'zip', '/path/to/source')
Log Parsing
Combine re (regex) with file I/O to extract insights from logs.
import re
error_pattern = re.compile(r"ERROR|CRITICAL")
with open("app.log", "r") as f:
errors = [line for line in f if error_pattern.search(line)]
print(f"Found {len(errors)} critical lines.")
error_pattern = re.compile(r"ERROR|CRITICAL")
with open("app.log", "r") as f:
errors = [line for line in f if error_pattern.search(line)]
print(f"Found {len(errors)} critical lines.")
โ Practice (30 minutes)
- Write a script that monitors CPU and sends an email if it stays above 90% for 1 minute.
- Create a cleanup script that deletes files older than 30 days in a specific folder.
- Parse a web server log and count the number of 404 errors.
- Schedule your Python script using crontab (Linux) or Task Scheduler (Windows).