I automated routine Linux administration with Python, using psutil for resource metrics and subprocess for safe command execution. Scheduled health and cleanup scripts replaced manual checks and surfaced disk and memory pressure before it caused outages.

Objective & Context

Repetitive admin tasks are error-prone when done by hand. This lab builds idempotent Python scripts that gather metrics, act on thresholds, and run under systemd timers, the toolkit that underpins the IR automation and vulnerability labs.

Environment & Prerequisites

  • Linux host with Python 3.11 and psutil.
  • systemd for scheduling (timer + service unit).
  • Permissions appropriate to the managed resources.

Step-by-Step Execution

1. Gather metrics with psutil

import psutil
disk = psutil.disk_usage("/").percent
mem  = psutil.virtual_memory().percent
if disk > 85 or mem > 90:
    alert(disk, mem)

2. Run a command safely with subprocess

python -c "import subprocess; print(subprocess.run(['df','-h','/'],capture_output=True,text=True).stdout)"

3. Schedule via systemd timer [ROOT REQUIRED]

systemctl enable --now health.timer && systemctl list-timers health.timer
NEXT                        UNIT          ACTIVATES
2026-06-17 10:00:00 UTC     health.timer  health.service

Validation & Testing

Fill a test filesystem past the threshold and confirm the script alerts and runs cleanup, then verify the timer fires on schedule. Pass criteria: threshold logic triggers correctly, subprocess uses a list (no shell injection), and the timer runs reliably.

Advanced: Troubleshooting
  • Shell injection risk: pass args as a list, never shell=True with user input.
  • Timer not firing: check systemctl status health.timer and journal logs.
  • Permission denied: run the service as a user with the needed access, not blanket root.

Key Results

  • Replaced manual checks with scheduled health monitoring.
  • Surfaced disk/memory pressure before it caused service impact.
  • Eliminated shell-injection risk via list-form subprocess calls.
  • Ran idempotent cleanup automatically under systemd timers.