Geavanceerd
Zoeken inLabs
Zo zoek je
  • Zoek een taak of een tool (lvm, selinux, @podman); filter op niveau en op boek of cursus.
  • Met een leeg zoekvak toont een filter alleen al de labs — bijvoorbeeld alle moeilijke labs van één cursus.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Lab 10.1Python, Hoofdstuk 10

Build and schedule a daily server health report

Niveau
Gemiddeld
60 min
Machines
a Linux server or VM with Python 3.10+ and systemd
Status
Nog niet begonnen

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 ~/healthreport and plan the checks on paper first: what is WARN and what is CRIT for each one?

Taken

  1. Write health.py with argparse options: --disk-warn (default 80), --disk-crit (90), --out (folder for the reports), --host (repeatable, for the TLS check).
  2. Check every real file system (/, /home, /var …) with shutil.disk_usage; skip pseudo file systems.
  3. Read memory from /proc/meminfo (MemAvailable vs MemTotal) and the load from os.getloadavg() compared to the number of CPUs.
  4. List failed systemd units with subprocess.run(["systemctl", "--failed", ...]) (no shell=True).
  5. For every --host, read the TLS certificate end date with ssl and socket; WARN under 21 days, CRIT under 7.
  6. Write report-YYYY-MM-DD.md (a table) and latest.json. Exit 0 (all OK), 1 (a WARN) or 2 (a CRIT). Log to stderr with logging.
  7. 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.json has "overall" and a list of checks; the exit code matches the worst status.
  • With --disk-warn 1 you get exit=1 (WARN).
  • The timer shows the next run at 06:30.

Hints

Toon de hints
  • Real file systems: read /proc/mounts and keep types like ext4, xfs, btrfs, vfat.
  • ssl.create_default_context().wrap_socket(sock, server_hostname=host).getpeercert()["notAfter"], then ssl.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/, then systemctl --user daemon-reload and loginctl enable-linger $USER so it runs when you are logged out.

Oplossing

Toon de oplossing
  1. 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())
  2. Run it.
    python3 health.py --out ./out --host s0sta.com; echo "exit=$?"
    INFO overall OK, 6 checks
    exit=0
    python3 health.py --out ./out --disk-warn 1; echo "exit=$?"
  3. 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.target
    systemctl --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.

Lessen voor dit lab

Commando's in dit lab