Build a Linux Service Monitor With Python

Build a Linux Service Monitor With Python

Overview

In this tutorial we build a minimal monitor on a single Linux host. The same ideas extend to every device in your fleet once an agent reports state centrally.

What We'll Build

  1. Read systemd unit state
  2. Detect failures or changes
  3. Emit a structured event
 1import hashlib
 2import subprocess
 3import time
 4from pathlib import Path
 5
 6CONFIG = Path("/etc/myapp/config.ini")
 7
 8def unit_active(name: str) -> str:
 9    result = subprocess.run(
10        ["systemctl", "is-active", name],
11        capture_output=True,
12        text=True,
13        check=False,
14    )
15    return result.stdout.strip()
16
17def file_hash(path: Path) -> str:
18    return hashlib.sha256(path.read_bytes()).hexdigest()
19
20if __name__ == "__main__":
21    last = file_hash(CONFIG) if CONFIG.exists() else None
22    while True:
23        state = unit_active("nginx")
24        if state != "active":
25            print({"event": "service.degraded", "unit": "nginx", "state": state})
26        current = file_hash(CONFIG) if CONFIG.exists() else None
27        if current != last:
28            print({"event": "config.changed", "path": str(CONFIG)})
29            last = current
30        time.sleep(30)

Why This Matters at Fleet Scale

The same pattern repeats per device with central aggregation. Run this on one device and you have a hack. Run it everywhere with centralized events and you have observability.

How EdgeProtocol Helps

EdgeProtocol's agent extends this pattern across your fleet. Try EdgeProtocol →