Cross-Platform System Health Snapshots with Python
This guide creates a small Python monitor that gathers CPU, memory, and disk metrics with the third-party psutil package. It prints one JSON snapshot, marks threshold breaches in the status field, and can append scheduled runs to a JSON Lines file. It does not send notifications or replace a monitoring platform.
Step 1: Create an Isolated Environment
Install psutil in a Virtual Environment
Environment SetupUse the same paths for the virtual environment and script in the later steps. These commands install psutil without changing the system Python packages.
mkdir -p "$HOME/opt/healthmon"python3 -m venv "$HOME/opt/healthmon/venv""$HOME/opt/healthmon/venv/bin/python" -m pip install --upgrade pip psutil$ProjectDir = Join-Path $env:LOCALAPPDATA "HealthMon"New-Item -ItemType Directory -Force -Path $ProjectDirpython -m venv (Join-Path $ProjectDir "venv")& (Join-Path $ProjectDir "venv\Scripts\python.exe") -m pip install --upgrade pip psutil❯ View Expected Console Output
Successfully installed psutilStep 2: Save the Cross-Platform Snapshot Script
Collect Metrics and Report Threshold Status
Python ScriptSave the script as ~/opt/healthmon/monitor.py on Linux or macOS, or $env:LOCALAPPDATA\HealthMon\monitor.py on Windows. On Windows it defaults to the current user’s system drive; set HEALTHMON_DISK_PATH to inspect another mounted volume.
#!/usr/bin/env python3import argparseimport jsonimport osimport socketfrom pathlib import Path
import psutil
def get_system_telemetry(): cpu_percent = psutil.cpu_percent(interval=1) memory = psutil.virtual_memory() disk_path = os.environ.get("HEALTHMON_DISK_PATH") if not disk_path: disk_path = Path.home().anchor if os.name == "nt" else "/" disk = psutil.disk_usage(disk_path)
report = { "hostname": socket.gethostname(), "cpu_percent": cpu_percent, "ram_used_percent": round(memory.percent, 1), "ram_available_gb": round(memory.available / (1024**3), 2), "disk_path": disk_path, "disk_used_percent": round(disk.percent, 1), "disk_free_gb": round(disk.free / (1024**3), 2), "status": "HEALTHY", } if cpu_percent > 85 or memory.percent > 90 or disk.percent > 90: report["status"] = "WARNING_THRESHOLD_EXCEEDED" return report
def main(): parser = argparse.ArgumentParser( description="Print one system health snapshot as JSON." ) parser.add_argument( "--output", type=Path, help="append the JSON snapshot to this JSON Lines file", ) args = parser.parse_args()
output = json.dumps(get_system_telemetry(), sort_keys=True) print(output) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) with args.output.open("a", encoding="utf-8") as log_file: log_file.write(output + "\n")
if __name__ == "__main__": main()❯ View Expected Console Output
{"hostname":"srv-app-01","cpu_percent":12.4,"disk_free_gb":84.15,"disk_path":"/","disk_used_percent":62.8,"ram_available_gb":18.75,"ram_used_percent":41.2,"status":"HEALTHY"}Step 3: Run a Snapshot and Choose an Output File
Review the JSON Output
ExecutionRun the script directly for a one-time snapshot. Add —output to append one JSON object per line so scheduled runs can be reviewed later.
"$HOME/opt/healthmon/venv/bin/python" "$HOME/opt/healthmon/monitor.py""$HOME/opt/healthmon/venv/bin/python" "$HOME/opt/healthmon/monitor.py" --output "$HOME/opt/healthmon/telemetry.jsonl"$ProjectDir = Join-Path $env:LOCALAPPDATA "HealthMon"& (Join-Path $ProjectDir "venv\Scripts\python.exe") (Join-Path $ProjectDir "monitor.py")& (Join-Path $ProjectDir "venv\Scripts\python.exe") (Join-Path $ProjectDir "monitor.py") --output (Join-Path $ProjectDir "telemetry.jsonl")❯ View Expected Console Output
The snapshot is printed to the terminal and appended to telemetry.jsonl when --output is set.Step 4: Schedule a Snapshot Every 15 Minutes
Schedule JSON Lines Collection
AutomationThe Linux example runs as the current user and appends output to that user’s project directory while the systemd user manager is active. Enable user lingering if it must run after logout or before the next login. The Windows task runs only while the selected user is logged on. Its repetition is explicitly bounded to ten years; renew it before then. Rotate or archive the JSON Lines file according to your retention policy.
mkdir -p "$HOME/.config/systemd/user"
cat > "$HOME/.config/systemd/user/healthmon.service" <<'EOF'[Unit]Description=Append a system health JSON snapshot
[Service]Type=oneshotExecStart=%h/opt/healthmon/venv/bin/python %h/opt/healthmon/monitor.py --output %h/opt/healthmon/telemetry.jsonlEOF
cat > "$HOME/.config/systemd/user/healthmon.timer" <<'EOF'[Unit]Description=Run the health monitor every 15 minutes
[Timer]OnCalendar=*:0/15Persistent=true
[Install]WantedBy=timers.targetEOF
systemctl --user daemon-reloadsystemctl --user enable --now healthmon.timersystemctl --user list-timers healthmon.timer$ProjectDir = Join-Path $env:LOCALAPPDATA "HealthMon"$PythonPath = Join-Path $ProjectDir "venv\Scripts\python.exe"$ScriptPath = Join-Path $ProjectDir "monitor.py"$OutputPath = Join-Path $ProjectDir "telemetry.jsonl"$Argument = '"{0}" --output "{1}"' -f $ScriptPath, $OutputPath$Action = New-ScheduledTaskAction -Execute $PythonPath -Argument $Argument$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 15) -RepetitionDuration (New-TimeSpan -Days 3650)$Principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel LimitedRegister-ScheduledTask -TaskName "PythonHealthMonitor" -Action $Action -Trigger $Trigger -Principal $Principal -Force❯ View Expected Console Output
Linux: healthmon.timer is enabled and the next run is listed.Windows: PythonHealthMonitor is registered for the current interactive user.