Why Python for System Administration?
Python has become the language of choice for system administrators and DevOps engineers. Its readable syntax, extensive standard library, and powerful third-party packages make it perfect for automation tasks that would take hours manually.
This guide introduces Python concepts specifically relevant to system administration, with practical examples you can use immediately.
Getting Started with Python
Most Linux distributions include Python. Check your version:
python3 --version
For system administration scripts, always use Python 3.8+ for security and feature support.
Essential Python Concepts
Working with Files
File operations are fundamental to system administration:
import os
from pathlib import Path
# Read a configuration file
config_file = Path('/etc/myapp/config.conf')
if config_file.exists():
content = config_file.read_text()
# Write log data
log_file = Path('/var/log/myscript.log')
log_file.write_text(f"Script executed at {datetime.now()}\n")
# List directory contents
for file in Path('/var/log').glob('*.log'):
print(f"{file.name}: {file.stat().st_size} bytes")
Running System Commands
The subprocess module executes shell commands safely:
import subprocess
# Run a command and capture output
result = subprocess.run(
['df', '-h'],
capture_output=True,
text=True
)
print(result.stdout)
# Check command success
if result.returncode == 0:
print("Command succeeded")
else:
print(f"Error: {result.stderr}")
Practical Automation Scripts
Log File Analyzer
#!/usr/bin/env python3
"""Analyze log files for errors and warnings."""
from pathlib import Path
from collections import Counter
import re
def analyze_log(log_path):
error_pattern = re.compile(r'(ERROR|WARN|CRITICAL)', re.IGNORECASE)
errors = Counter()
with open(log_path, 'r') as f:
for line in f:
match = error_pattern.search(line)
if match:
errors[match.group(1).upper()] += 1
return errors
if __name__ == '__main__':
log_file = Path('/var/log/syslog')
results = analyze_log(log_file)
for level, count in results.most_common():
print(f"{level}: {count} occurrences")
Disk Space Monitor
#!/usr/bin/env python3
"""Monitor disk space and alert when threshold exceeded."""
import shutil
import smtplib
from email.mime.text import MIMEText
def check_disk_space(path, threshold=80):
"""Check if disk usage exceeds threshold percentage."""
usage = shutil.disk_usage(path)
percent_used = (usage.used / usage.total) * 100
return percent_used > threshold, percent_used
def send_alert(message):
"""Send email alert."""
msg = MIMEText(message)
msg['Subject'] = 'Disk Space Alert'
msg['From'] = 'monitor@example.com'
msg['To'] = 'admin@example.com'
with smtplib.SMTP('localhost') as smtp:
smtp.send_message(msg)
if __name__ == '__main__':
paths_to_check = ['/', '/home', '/var']
for path in paths_to_check:
exceeded, usage = check_disk_space(path)
if exceeded:
send_alert(f"Warning: {path} is at {usage:.1f}% capacity")
Useful Libraries for Sysadmins
Paramiko - SSH Connections
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('server.example.com', username='admin', key_filename='~/.ssh/id_rsa')
stdin, stdout, stderr = ssh.exec_command('uptime')
print(stdout.read().decode())
ssh.close()
Requests - HTTP Interactions
import requests
# Check web service health
response = requests.get('http://localhost:8080/health', timeout=5)
if response.status_code == 200:
print("Service healthy")
else:
print(f"Service returned {response.status_code}")
Schedule - Task Scheduling
import schedule
import time
def backup_job():
print("Running backup...")
# Your backup logic here
schedule.every().day.at("02:00").do(backup_job)
while True:
schedule.run_pending()
time.sleep(60)
Best Practices
- Use virtual environments to isolate dependencies
- Handle exceptions gracefully with try/except
- Log your scripts using the logging module
- Use configuration files instead of hardcoded values
- Write unit tests for critical automation
Conclusion
Python automation transforms system administration from repetitive manual tasks to efficient, reliable processes. Start with simple scripts and gradually tackle more complex challenges.
Our Python automation eBooks provide comprehensive guidance with real-world projects to build your skills.