Python Monitoring Toolkit for Linux: CPU, Disk, Services

Most servers don’t fall over without warning. The disk crept up for a week. A service died at 2 am and nobody noticed. Some process slowly ate all the RAM. The signs were there, just not in front of anyone.

You don’t need a full Prometheus stack to catch the basics. Four small Python scripts and a systemd timer will cover a surprising amount of ground. This post builds that toolkit: a server health checker, a disk space monitor with threshold alerts, a “what’s eating my CPU and memory” process finder, and a systemd service monitor that alerts once per failure instead of spamming you every five minutes.

Everything here was run on Ubuntu 26.04.1 LTS (Python 3.14.4, psutil 7.1.0) and RHEL 10.2 (Python 3.12.13, psutil 5.9.8). Same scripts, no edits between the two. If you want the theory behind metrics, logs and alerts first, Linux Monitoring: Metrics, Logs, Traces and Alerts is the companion read.

What the Toolkit Does

Four scripts, each with one job, all living in /opt/healthmon:

  • health_check.py gives a one-screen snapshot of CPU, RAM, swap, root disk, uptime and load average.
  • disk_monitor.py checks space and inodes on every real filesystem, with warning and critical thresholds.
  • top_processes.py lists the processes using the most CPU or memory.
  • service_monitor.py finds failed systemd services and alerts once, then tells you when they recover.

They all follow the Nagios exit code convention: 0 for OK, 1 for warning, 2 for critical. That small detail means you can plug them into cron, a systemd timer, Nagios, Zabbix or a CI job later without rewriting anything.

Install psutil on Ubuntu and RHEL

psutil is the library that does the heavy lifting. It reads CPU, memory, disk and process data from /proc and gives it back as clean Python objects. Install it from your distro’s packages, not pip. These scripts run as system tools, so the system package is the right fit.

Ubuntu:

sudo apt install python3-psutil

RHEL 10 (it’s in AppStream, no EPEL needed):

sudo dnf install python3-psutil

Check it:

python3 -c "import psutil; print('psutil', psutil.__version__)"
psutil 7.1.0

RHEL prints psutil 5.9.8. Older, but everything in this post works on both versions. If you’d rather pin a specific version in a virtual environment, this venv and pip guide walks through it. Then create the folder:

sudo mkdir -p /opt/healthmon

Save each script below into that folder and make it executable with sudo chmod 755 /opt/healthmon/*.py.

Build a Linux Server Health Checker in Python

First up, the “is this box OK?” script. It checks CPU, memory, swap, the root disk, uptime and load average, labels each one OK, WARN or CRIT, and exits with the worst result.

#!/usr/bin/env python3
"""Server health snapshot: CPU, RAM, swap, root disk, uptime and load."""
import os
import sys
import time

import psutil

WARN, CRIT = 80, 90  # percent


def level(pct):
    return "CRIT" if pct >= CRIT else "WARN" if pct >= WARN else "OK"


cores = psutil.cpu_count()
cpu = psutil.cpu_percent(interval=1)  # sample for 1 second
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
disk = psutil.disk_usage("/")
uptime = int(time.time() - psutil.boot_time())
load1, load5, load15 = os.getloadavg()
load_pct = load1 / cores * 100  # load relative to core count

checks = {
    "CPU": (cpu, f"{cpu:.1f}% across {cores} cores"),
    "Memory": (mem.percent, f"{mem.percent:.1f}% ({mem.used / 1024**3:.1f} of {mem.total / 1024**3:.1f} GiB)"),
    "Swap": (swap.percent, f"{swap.percent:.1f}% of {swap.total / 1024**3:.1f} GiB"),
    "Disk /": (disk.percent, f"{disk.percent:.1f}% ({disk.free / 1024**3:.1f} GiB free)"),
    "Load": (load_pct, f"{load1:.2f} {load5:.2f} {load15:.2f} (1m = {load_pct:.0f}% of cores)"),
}

print(f"Host   : {os.uname().nodename}")
print(f"Uptime : {uptime // 86400}d {uptime % 86400 // 3600}h {uptime % 3600 // 60}m")
worst = "OK"
for name, (pct, text) in checks.items():
    state = level(pct)
    print(f"{state:<4}  {name:<7} {text}")
    if state == "CRIT" or (state == "WARN" and worst == "OK"):
        worst = state

print(f"Overall: {worst}")
sys.exit({"OK": 0, "WARN": 1, "CRIT": 2}[worst])

A few things worth pointing out.

cpu_percent(interval=1) samples for one second. Without an interval, the first call returns a meaningless 0.0, which catches a lot of people out. Load average comes from os.getloadavg(), and the script divides it by the core count so it gets a percentage. Raw load means nothing without that. A load of 3 is idle on 22 cores and a crisis on 2. If load average still feels fuzzy, this load average explainer breaks it down.

Here it is on Ubuntu with three CPU-burning loops and a 600 MB memory hog running in the background:

./health_check.py
Host   : DESKTOP-3NICIT8
Uptime : 0d 0h 17m
OK    CPU     13.7% across 22 cores
OK    Memory  12.1% (1.9 of 15.3 GiB)
OK    Swap    0.0% of 4.0 GiB
OK    Disk /  0.5% (950.6 GiB free)
OK    Load    0.36 0.09 0.02 (1m = 2% of cores)
Overall: OK
echo $?
0

Three busy loops on a 22-core machine is only 13.7% CPU, so everything stays green. That’s the point of normalizing. On a 2-core VM the same load would light up red. Want to tweak sensitivity? Change WARN and CRIT at the top.

Python Disk Space Monitoring Script with Threshold Alerts

Disk space is the classic one. But most disk scripts you’ll find online only check /, and they only check bytes. Real servers have /var, /home and data volumes on separate filesystems. And a disk can be “full” with plenty of space left if it runs out of inodes. This script handles both.

#!/usr/bin/env python3
"""Check space and inodes on every real filesystem, alert past thresholds."""
import argparse
import os
import sys
import syslog

import psutil

parser = argparse.ArgumentParser()
parser.add_argument("--warn", type=float, default=80)
parser.add_argument("--crit", type=float, default=90)
args = parser.parse_args()

problems = []
seen = set()
for part in psutil.disk_partitions(all=False):
    if part.device in seen or part.fstype in ("squashfs", "iso9660"):
        continue  # skip bind mounts and read-only snap images
    seen.add(part.device)
    try:
        usage = psutil.disk_usage(part.mountpoint)
        st = os.statvfs(part.mountpoint)
    except PermissionError:
        continue
    inode_pct = (1 - st.f_ffree / st.f_files) * 100 if st.f_files else 0.0

    worst = max(usage.percent, inode_pct)
    state = "CRIT" if worst >= args.crit else "WARN" if worst >= args.warn else "OK"
    print(f"{state:<4}  {part.mountpoint:<12} space {usage.percent:5.1f}%  "
          f"inodes {inode_pct:5.1f}%  free {usage.free / 1024**3:.2f} GiB")
    if state != "OK":
        problems.append((state, f"{part.mountpoint} space {usage.percent:.0f}% inodes {inode_pct:.0f}%"))

syslog.openlog("healthmon")
for state, msg in problems:
    syslog.syslog(syslog.LOG_CRIT if state == "CRIT" else syslog.LOG_WARNING, f"disk {state}: {msg}")

if any(s == "CRIT" for s, _ in problems):
    sys.exit(2)
sys.exit(1 if problems else 0)

How it works:

  • psutil.disk_partitions(all=False) returns only real devices, so tmpfs, proc and friends are skipped automatically.
  • Snap’s read-only squashfs images are always 100% full on Ubuntu, so they’re filtered out. Otherwise you’d get a permanent false alarm.
  • os.statvfs() gives the inode counts that psutil doesn’t.
  • Alerts go to syslog with the tag healthmon, at critical or warning priority. That means they land in journalctl, /var/log/syslog or /var/log/messages, wherever your log shipping already looks.

To test it, I mounted a small 200 MB filesystem on /srv/data and filled it with a fake backup file:

./disk_monitor.py
OK    /            space   0.5%  inodes   0.1%  free 950.61 GiB
CRIT  /srv/data    space  97.6%  inodes   0.6%  free 0.00 GiB
echo $?
2

Now the sneaky one. I deleted the backup and created about 1,960 tiny session files instead. Look at what df -h says:

df -h /srv/data
Filesystem      Size  Used Avail Use% Mounted on
/dev/loop1      194M   65K  180M   1% /srv/data

df -i /srv/data
Filesystem     Inodes IUsed IFree IUse% Mounted on
/dev/loop1       2000  1972    28   99% /srv/data

1% used. Looks totally fine. But inodes are at 99%, and the next file write will fail with “No space left on device”. The script catches it:

./disk_monitor.py
OK    /            space   0.2%  inodes   0.1%  free 953.80 GiB
CRIT  /srv/data    space   0.0%  inodes  98.6%  free 0.18 GiB

This happens in real life with PHP session folders, mail queues and cache directories full of tiny files. A bytes-only check would stay green right up until the app breaks.

Thresholds are command-line flags, so different servers can use different limits without editing code:

./disk_monitor.py --warn 70 --crit 99
OK    /            space   0.2%  inodes   0.1%  free 953.80 GiB
WARN  /srv/data    space   0.0%  inodes  98.6%  free 0.18 GiB
echo $?
1

Find High CPU and Memory Processes on Linux with psutil

When the health check goes yellow, the next question is always “what’s doing it?”. This script answers that.

#!/usr/bin/env python3
"""Show the processes using the most CPU or memory."""
import argparse
import time

import psutil

parser = argparse.ArgumentParser()
parser.add_argument("--sort", choices=["cpu", "mem"], default="cpu")
parser.add_argument("-n", type=int, default=5)
args = parser.parse_args()

procs = list(psutil.process_iter(["pid", "name", "username"]))
for p in procs:
    try:
        p.cpu_percent(None)  # first call only primes the counter
    except psutil.Error:
        pass
time.sleep(1)

rows = []
for p in procs:
    try:
        rows.append((p.cpu_percent(None), p.memory_info().rss, p.info))
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        continue  # process exited or belongs to another user

key = 0 if args.sort == "cpu" else 1
rows.sort(key=lambda r: r[key], reverse=True)

print(f"{'PID':>7}  {'USER':<10} {'CPU%':>6} {'RSS MB':>8}  NAME")
for cpu, rss, info in rows[: args.n]:
    print(f"{info['pid']:>7}  {(info['username'] or '?')[:10]:<10} "
          f"{cpu:6.1f} {rss / 1024**2:8.1f}  {info['name']}")

The interesting bit is the CPU measurement. A process’s CPU percentage only makes sense over a time window. So the script calls cpu_percent(None) once on every process to start the clock, sleeps for a second, then calls it again to get the real number. Skip that first pass and every process shows 0.0.

The try/except isn’t optional either. Processes start and exit constantly. Between listing them and reading them, some will be gone. That’s NoSuchProcess, and without catching it the script crashes randomly, maybe one run in twenty. Fun to debug.

Top CPU users, with the same three busy loops running:

./top_processes.py
    PID  USER         CPU%   RSS MB  NAME
   2267  asif        102.7      1.7  sh
   2268  asif        101.7      1.7  sh
   2269  asif        101.7      1.7  sh
     87  root          1.0     11.7  systemd-udevd
   2273  asif          1.0     16.8  python3

Yes, over 100%. psutil reports per-process CPU like top does, where 100% means one full core. A multi-threaded process can show 400% or more. The small wobble above 100 is just timing jitter from a one-second sample.

Now sorted by memory:

./top_processes.py --sort mem -n 5
    PID  USER         CPU%   RSS MB  NAME
   2270  asif          0.0    609.3  python3
    501  mysql         1.0    511.5  mysqld
    236  root          0.0     34.8  php-fpm8.5
    404  root          0.0     31.3  unattended-upgr
    223  root          0.0     27.2  networkd-dispat

There’s the 600 MB hog at the top, followed by MySQL. RSS is the physical memory the process is actually holding, which is what matters when the box starts swapping. Run it without sudo and you’ll still see every process, though a few details of other users’ processes may be hidden.

Monitor systemd Services with Python and Alert on Failures

This is the one I’d set up first on any server. It does two things:

  1. Catches every service systemd has marked as failed, even ones you forgot existed.
  2. Checks a list of services you name that must be running. A service someone stopped by hand isn’t “failed”, it’s just inactive, so systemctl --failed alone would miss it.

It also remembers what it already alerted on. Without that, a timer running every five minutes sends 288 identical alerts a day for one dead service, and everyone mutes the channel by lunchtime.

#!/usr/bin/env python3
"""Find failed systemd services and alert once per failure, not every run."""
import json
import subprocess
import sys
import syslog
from pathlib import Path

WATCH = sys.argv[1:]  # services that must be running, e.g. nginx sshd
STATE = Path("/var/tmp/healthmon-services.json")


def systemctl(*args):
    return subprocess.run(["systemctl", *args], capture_output=True, text=True).stdout


failed = {line.split()[0] for line in systemctl(
    "list-units", "--type=service", "--state=failed", "--plain", "--no-legend").splitlines()
    if line.strip()}

for svc in WATCH:
    unit = svc if svc.endswith(".service") else f"{svc}.service"
    state = systemctl("is-active", unit).strip()
    if state != "active":
        failed.add(unit)

already = set(json.loads(STATE.read_text())) if STATE.exists() else set()
new = failed - already
recovered = already - failed

syslog.openlog("healthmon")
for unit in sorted(new):
    syslog.syslog(syslog.LOG_ERR, f"service DOWN: {unit}")
    print(f"ALERT      {unit} is down")
for unit in sorted(failed & already):
    print(f"STILL DOWN {unit} (already alerted)")
for unit in sorted(recovered):
    syslog.syslog(syslog.LOG_INFO, f"service RECOVERED: {unit}")
    print(f"RECOVERED  {unit}")

STATE.write_text(json.dumps(sorted(failed)))
if not failed:
    print("OK         no failed services")
sys.exit(2 if failed else 0)

To have something to catch, I created a deliberately broken unit called report-sync.service whose ExecStart is /usr/bin/false, and started it. systemd sees it fail:

systemctl --failed --no-pager
  UNIT                LOAD   ACTIVE SUB    DESCRIPTION
● report-sync.service loaded failed failed Nightly report sync (demo)

1 loaded units listed.

Now the monitor, on RHEL, watching sshd and crond (on Ubuntu those are ssh and cron). First run:

sudo ./service_monitor.py sshd crond
ALERT      report-sync.service is down

Second run, a few seconds later. No repeat alert:

sudo ./service_monitor.py sshd crond
STILL DOWN report-sync.service (already alerted)

Then I stopped crond by hand. It’s not “failed”, just inactive, but it’s on the watch list so it gets flagged:

sudo systemctl stop crond
sudo ./service_monitor.py sshd crond
ALERT      crond.service is down
STILL DOWN report-sync.service (already alerted)

Fix both, run again, and you get recovery messages plus a clean exit code:

sudo systemctl start crond
sudo systemctl reset-failed report-sync.service
sudo ./service_monitor.py sshd crond
RECOVERED  crond.service
RECOVERED  report-sync.service
OK         no failed services
echo $?
0

Every ALERT and RECOVERED line also went to syslog:

sudo journalctl -t healthmon -g service --no-pager -o short | tail -4
Nov 01 15:05:49 DESKTOP-3NICIT8 healthmon[1536]: service DOWN: report-sync.service
Nov 01 15:05:50 DESKTOP-3NICIT8 healthmon[1559]: service DOWN: crond.service
Nov 01 15:05:50 DESKTOP-3NICIT8 healthmon[1579]: service RECOVERED: crond.service
Nov 01 15:05:50 DESKTOP-3NICIT8 healthmon[1579]: service RECOVERED: report-sync.service

Want Slack or email instead? Swap the syslog.syslog() calls for a function that posts to a webhook with urllib.request or sends mail with smtplib. The once-per-failure logic stays exactly the same.

Schedule the Checks with a systemd Timer

Scripts you run by hand aren’t monitoring. Let systemd run them every five minutes. A timer beats cron here because the output lands in the journal automatically, and Persistent=true catches up on runs missed while the box was off.

Create /etc/systemd/system/healthmon.service:

[Unit]
Description=Python health monitor checks

[Service]
Type=oneshot
ExecStart=-/opt/healthmon/disk_monitor.py
ExecStart=-/opt/healthmon/service_monitor.py sshd crond

Note the - in front of each path. In a oneshot service with several ExecStart lines, a non-zero exit stops the rest from running. Our scripts exit 2 on purpose when something’s wrong, so without the dash, a full disk would stop the service check from ever happening. The dash tells systemd to keep going. On Ubuntu, change the watch list to ssh cron.

Then /etc/systemd/system/healthmon.timer:

[Unit]
Description=Run healthmon every 5 minutes

[Timer]
OnBootSec=2min
OnUnitActiveSec=5min
Persistent=true

[Install]
WantedBy=timers.target

Load and enable it:

sudo systemctl daemon-reload
sudo systemctl enable --now healthmon.timer
Created symlink '/etc/systemd/system/timers.target.wants/healthmon.timer' → '/etc/systemd/system/healthmon.timer'.

Setup Confirmation

Time to prove it all works end to end. I broke report-sync.service again, then checked the timer, the last run and the alerts. This is from RHEL 10.2. Ubuntu gave the same results.

The timer is scheduled and has already fired once:

systemctl list-timers healthmon.timer --no-pager
NEXT                            LEFT LAST                        PASSED UNIT            ACTIVATES
Sun 2026-11-01 15:11:06 PKT 4min 59s Sun 2026-11-01 15:06:04 PKT 1s ago healthmon.timer healthmon.service

1 timers listed.

Both scripts ran. The service check exited with 2 because of the broken unit, but thanks to the dash prefix the run still finished cleanly:

systemctl status healthmon.service --no-pager
○ healthmon.service - Python health monitor checks
     Loaded: loaded (/etc/systemd/system/healthmon.service; static)
     Active: inactive (dead) since Sun 2026-11-01 15:06:06 PKT; 17ms ago
TriggeredBy: ● healthmon.timer
    Process: 1765 ExecStart=/opt/healthmon/disk_monitor.py (code=exited, status=0/SUCCESS)
    Process: 1767 ExecStart=/opt/healthmon/service_monitor.py sshd crond (code=exited, status=2)
   Main PID: 1767 (code=exited, status=2)
   Mem peak: 7.7M
        CPU: 93ms

Nov 01 15:06:06 DESKTOP-3NICIT8 systemd[1]: Starting healthmon.service - Python health monitor checks...
Nov 01 15:06:06 DESKTOP-3NICIT8 disk_monitor.py[1765]: OK    /            space   0.2%  inodes   0.1%  free 953.80 GiB
Nov 01 15:06:06 DESKTOP-3NICIT8 disk_monitor.py[1765]: OK    /srv/data    space   0.0%  inodes   0.5%  free 0.18 GiB
Nov 01 15:06:06 DESKTOP-3NICIT8 service_monitor.py[1767]: STILL DOWN report-sync.service (already alerted)
Nov 01 15:06:06 DESKTOP-3NICIT8 systemd[1]: healthmon.service: Deactivated successfully.
Nov 01 15:06:06 DESKTOP-3NICIT8 systemd[1]: Finished healthmon.service - Python health monitor checks.

“STILL DOWN (already alerted)” is right. Enabling the timer kicked off an immediate run, which raised the alert. Here it is in the journal:

sudo journalctl -t healthmon --since "-2min" --no-pager -o short | tail -1
Nov 01 15:06:05 DESKTOP-3NICIT8 healthmon[1753]: service DOWN: report-sync.service

One alert, no repeats. If you see the same three things on your server (timer listed with a NEXT time, both ExecStart processes in the status output, and healthmon lines in the journal), the toolkit is live.

Frequently Asked Questions

Do I need psutil, or can I use only the standard library?

You can read /proc/meminfo, /proc/loadavg and friends yourself, and for one or two metrics that’s fine. psutil earns its place once you need per-process CPU, disk partitions or anything cross-platform. It’s packaged by both Ubuntu and RHEL, so it’s not a heavy dependency.

Why does a process show more than 100% CPU?

Because 100% means one full core. A process using four cores shows about 400%. That matches what top and htop show. For a whole-system number, use psutil.cpu_percent() instead, which is scaled to 100% across all cores.

Should I use cron or a systemd timer?

Either works. A timer gives you output in the journal for free, runs missed jobs after a reboot with Persistent=true, and is easy to inspect with systemctl list-timers. Cron is simpler if you already manage everything there.

How do I send alerts to Slack, Teams or email?

Replace the syslog.syslog() calls with a small function. For Slack or Teams, POST JSON to an incoming webhook with urllib.request. For email, use smtplib with your SMTP relay. Keep the webhook URL in an environment file, not in the script.

Is this a replacement for Prometheus, Zabbix or Nagios?

No. It’s for small fleets, a handful of VPSes, or as a safety net on boxes that aren’t in your main monitoring yet. Because the scripts use Nagios-style exit codes, they’re also easy to plug into Nagios or Zabbix later as custom checks.

Why does the disk script ignore some mounts?

It skips pseudo filesystems like tmpfs and proc, Snap’s always-full squashfs images, and duplicate entries for the same device, which show up with bind mounts and containers. Those would only create noise.

Where to Go Next

You now have a small but honest monitoring setup: health snapshots, disk and inode alerts, a process finder for when things get slow, and service alerts that don’t cry wolf. From here, a good next step is packaging these four scripts into one installable tool with a single CLI entry point. Python Modules and Packages for DevOps Automation shows exactly how. And if you’re still getting comfortable with Python itself, start at Python for DevOps Engineers.