Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
Doel
Write the tool many admins wish they had: one Python script, only the standard library, that checks disk, memory, load, failed services and certificate expiry, gives each check a status (OK / WARN / CRIT), writes a Markdown report and a JSON file for monitoring, and exits with a Nagios-style code. A systemd timer runs it every morning.
Voordat je begint
- A Linux machine with Python 3.10+ and systemd. Work as a normal user; only task 6 needs
sudo. - Make the folder
~/healthreportand plan the checks on paper first: what is WARN and what is CRIT for each one?
Taken
Vink een taak aan als hij klaar is. Alleen je browser onthoudt dit.
- Write
health.pywithargparseoptions:--disk-warn(default 80),--disk-crit(90),--out(folder for the reports),--host(repeatable, for the TLS check). - Check every real file system (
/,/home,/var…) withshutil.disk_usage; skip pseudo file systems. - Read memory from
/proc/meminfo(MemAvailablevsMemTotal) and the load fromos.getloadavg()compared to the number of CPUs. - List failed systemd units with
subprocess.run(["systemctl", "--failed", ...])(noshell=True). - For every
--host, read the TLS certificate end date withsslandsocket; WARN under 21 days, CRIT under 7. - Write
report-YYYY-MM-DD.md(a table) andlatest.json. Exit0(all OK),1(a WARN) or2(a CRIT). Log to stderr withlogging. - Install a systemd service + timer that runs the script every day at 06:30 and keeps the last 14 reports.
Controleer je werk
python3 health.py --out ./out --host s0sta.com --host github.com; echo "exit=$?"
cat out/report-$(date +%F).md
python3 -m json.tool out/latest.json | head -20
systemctl --user list-timers health-report.timer- The Markdown table has one row per check with a status and the value (for example
/ 41% used). latest.jsonhas"overall"and a list of checks; the exit code matches the worst status.- With
--disk-warn 1you getexit=1(WARN). - The timer shows the next run at 06:30.
Hints
Toon de hints
- Real file systems: read
/proc/mountsand keep types likeext4,xfs,btrfs,vfat. ssl.create_default_context().wrap_socket(sock, server_hostname=host).getpeercert()["notAfter"], thenssl.cert_time_to_seconds().max()over the status numbers gives the overall status (0 = OK, 1 = WARN, 2 = CRIT).- A user timer needs no root: files in
~/.config/systemd/user/, thensystemctl --user daemon-reloadandloginctl enable-linger $USERso it runs when you are logged out.
Oplossing
Toon de oplossing
- The script.health.py
#!/usr/bin/env python3 """Daily health report: disk, memory, load, failed units, TLS expiry. Exit 0 OK, 1 WARN, 2 CRIT.""" import argparse, datetime as dt, json, logging, os, pathlib, shutil, socket, ssl, subprocess, time NAMES = {0: "OK", 1: "WARN", 2: "CRIT"} REAL_FS = {"ext4", "xfs", "btrfs", "vfat", "zfs"} log = logging.getLogger("health") def level(value, warn, crit): return 2 if value >= crit else 1 if value >= warn else 0 def disks(a): seen = set() for line in open("/proc/mounts"): dev, mnt, fstype = line.split()[:3] if fstype in REAL_FS and dev not in seen: seen.add(dev) u = shutil.disk_usage(mnt) pct = round(u.used * 100 / u.total) yield {"check": f"disk {mnt}", "value": f"{pct}% used", "status": level(pct, a.disk_warn, a.disk_crit)} def memory(): info = {l.split(":")[0]: int(l.split()[1]) for l in open("/proc/meminfo")} used = round(100 - info["MemAvailable"] * 100 / info["MemTotal"]) return {"check": "memory", "value": f"{used}% used", "status": level(used, 85, 95)} def load(): l1, cpus = os.getloadavg()[0], os.cpu_count() or 1 return {"check": "load", "value": f"{l1:.2f} on {cpus} CPUs", "status": level(l1 / cpus, 1.0, 2.0)} def failed_units(): r = subprocess.run(["systemctl", "--failed", "--no-legend", "--plain"], capture_output=True, text=True, timeout=20) units = [l.split()[0] for l in r.stdout.splitlines() if l.strip()] return {"check": "failed units", "value": ", ".join(units) or "none", "status": 2 if units else 0} def tls(host): try: ctx = ssl.create_default_context() with socket.create_connection((host, 443), timeout=10) as s, ctx.wrap_socket(s, server_hostname=host) as t: days = int((ssl.cert_time_to_seconds(t.getpeercert()["notAfter"]) - time.time()) // 86400) return {"check": f"tls {host}", "value": f"{days} days left", "status": 2 if days < 7 else 1 if days < 21 else 0} except OSError as err: return {"check": f"tls {host}", "value": str(err), "status": 2} def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--disk-warn", type=int, default=80) p.add_argument("--disk-crit", type=int, default=90) p.add_argument("--out", default="out") p.add_argument("--host", action="append", default=[]) a = p.parse_args() logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") checks = [*disks(a), memory(), load(), failed_units(), *(tls(h) for h in a.host)] overall = max(c["status"] for c in checks) out = pathlib.Path(a.out) out.mkdir(parents=True, exist_ok=True) today = dt.date.today().isoformat() rows = "\n".join(f"| {c['check']} | {NAMES[c['status']]} | {c['value']} |" for c in checks) (out / f"report-{today}.md").write_text(f"# Health report {socket.gethostname()} {today}\n\nOverall: **{NAMES[overall]}**\n\n| Check | Status | Value |\n|---|---|---|\n{rows}\n") (out / "latest.json").write_text(json.dumps({"host": socket.gethostname(), "date": today, "overall": NAMES[overall], "checks": checks}, indent=2)) for old in sorted(out.glob("report-*.md"))[:-14]: old.unlink() log.info("overall %s, %d checks", NAMES[overall], len(checks)) return overall if __name__ == "__main__": raise SystemExit(main()) - Run it.
- The user service and timer.~/.config/systemd/user/health-report.service
[Unit] Description=Daily health report [Service] Type=oneshot ExecStart=/usr/bin/python3 %h/healthreport/health.py --out %h/healthreport/out --host s0sta.com~/.config/systemd/user/health-report.timer[Unit] Description=Run the health report every morning [Timer] OnCalendar=*-*-* 06:30 Persistent=true [Install] WantedBy=timers.targetsystemctl --user daemon-reload systemctl --user enable --now health-report.timer loginctl enable-linger $USER systemctl --user start health-report.service && journalctl --user -u health-report -n 5
Mijn notities
Nog geen notities.