Skip to content

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

01

Install psutil in a Virtual Environment

Environment Setup

Use the same paths for the virtual environment and script in the later steps. These commands install psutil without changing the system Python packages.

Terminal window
mkdir -p "$HOME/opt/healthmon"
python3 -m venv "$HOME/opt/healthmon/venv"
"$HOME/opt/healthmon/venv/bin/python" -m pip install --upgrade pip psutil
❯ View Expected Console Output
Successfully installed psutil

Step 2: Save the Cross-Platform Snapshot Script

02

Collect Metrics and Report Threshold Status

Python Script

Save 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 python3
import argparse
import json
import os
import socket
from 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

03

Review the JSON Output

Execution

Run the script directly for a one-time snapshot. Add —output to append one JSON object per line so scheduled runs can be reviewed later.

Terminal window
"$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"
❯ 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

04

Schedule JSON Lines Collection

Automation

The 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.

Terminal window
mkdir -p "$HOME/.config/systemd/user"
cat > "$HOME/.config/systemd/user/healthmon.service" <<'EOF'
[Unit]
Description=Append a system health JSON snapshot
[Service]
Type=oneshot
ExecStart=%h/opt/healthmon/venv/bin/python %h/opt/healthmon/monitor.py --output %h/opt/healthmon/telemetry.jsonl
EOF
cat > "$HOME/.config/systemd/user/healthmon.timer" <<'EOF'
[Unit]
Description=Run the health monitor every 15 minutes
[Timer]
OnCalendar=*:0/15
Persistent=true
[Install]
WantedBy=timers.target
EOF
systemctl --user daemon-reload
systemctl --user enable --now healthmon.timer
systemctl --user list-timers healthmon.timer
❯ View Expected Console Output
Linux: healthmon.timer is enabled and the next run is listed.
Windows: PythonHealthMonitor is registered for the current interactive user.

Comments