Create a Python Script for System Monitoring
Learning how to create a Python script for system monitoring gives Linux administrators a repeatable way to spot resource pressure early. This example uses Python 3 and its standard library on RHEL, CentOS Stream, Fedora and similar hosts, with no package installation required.
It suits Australian teams supporting offices in Sydney, Melbourne and Brisbane, where local file servers and routers often sit beside cloud workloads. Small businesses and managed service providers can use the same readings as a practical baseline.
Each sample records CPU use, memory use, root-filesystem consumption and load average. Local timestamps make the log easy to compare with business hours, maintenance windows and incidents handled by on-call support staff.
The script collects measurements rather than documents, customer names or credentials. That restraint supports obligations under the Privacy Act 1988 and alignment with the Australian Signals Directorate’s Essential Eight, while producing evidence for configuration and access reviews.
Plan the monitoring scope
Begin with CPU, memory, disk space and load average. Together they expose saturated processors, memory pressure, full filesystems and runnable-task queues before a service becomes unavailable. Keep the first version small so each reading has a clear purpose.
Use absolute paths for the script and log file because cron, systemd and SSH sessions can have different working directories. Root access is needed for the protected log path, while standard /proc counters are normally readable. The wider Linux administration guides provide useful context for these choices.
Build the script
Save the following as system-monitor.py. It reads Linux counters, samples them every 60 seconds and appends a timestamped line to /var/log/system-monitor.log.
#!/usr/bin/env python3
import os
import shutil
import time
from datetime import datetime
from pathlib import Path
INTERVAL = 60
LOG_FILE = Path("/var/log/system-monitor.log")
LIMITS = {"cpu": 80.0, "memory": 85.0, "disk": 85.0}
def read_cpu():
with open("/proc/stat", encoding="utf-8") as stats:
values = list(map(int, stats.readline().split()[1:]))
return sum(values), values[3] + values[4]
previous = read_cpu()
while True:
time.sleep(INTERVAL)
current = read_cpu()
total = current[0] - previous[0]
idle = current[1] - previous[1]
cpu = 100 * max(0.0, min(1.0, 1 - idle / total))
previous = current
with open("/proc/meminfo", encoding="utf-8") as meminfo:
memory = {}
for row in meminfo:
key, value = row.split(":", 1)
if key in ("MemTotal", "MemAvailable"):
memory[key] = int(value.split()[0])
memory_use = 100 * (1 - memory["MemAvailable"] / memory["MemTotal"])
disk = shutil.disk_usage("/")
disk_use = 100 * disk.used / disk.total
load = os.getloadavg()[0]
readings = {"cpu": cpu, "memory": memory_use, "disk": disk_use}
alerts = [name for name, value in readings.items() if value > LIMITS[name]]
status = "OK" if not alerts else "WARNING=" + ",".join(alerts)
stamp = datetime.now().astimezone().isoformat(timespec="seconds")
line = f"{stamp} {status} cpu={cpu:.1f}% mem={memory_use:.1f}% disk={disk_use:.1f}% load={load:.2f}"
print(line, flush=True)
with LOG_FILE.open("a", encoding="utf-8") as log:
log.write(line + "\n")
The first CPU sample establishes a baseline; the next calculates usage across the interval. MemAvailable provides a better memory-pressure estimate than free memory alone, while shutil.disk_usage() measures the root filesystem. The script also records a warning status when any default limit is crossed.
Install and test it
Validate the file before installing it, then run one sample as root. The first result appears after one minute; press Ctrl+C after checking the output.
python3 -m py_compile system-monitor.py
sudo install -m 0755 system-monitor.py /usr/local/bin/system-monitor.py
sudo touch /var/log/system-monitor.log
sudo chmod 0640 /var/log/system-monitor.log
sudo /usr/local/bin/system-monitor.py
During setup, confirm that the account can read /proc and write the log. The network reference resource can complement this local view when connectivity also needs checking.
Run it with systemd
Create a systemd unit so the monitor starts at boot and restarts after a failure. A service is safer here than a cron entry because the script already runs continuously.
[Unit]
Description=Python system monitoring service
After=local-fs.target
[Service]
Type=simple
ExecStart=/usr/local/bin/system-monitor.py
Restart=always
RestartSec=5
User=root
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/log/system-monitor.log
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
Reload systemd, enable the unit and follow its journal. The dedicated log remains available even when journal rotation changes the system stream.
sudo systemctl daemon-reload
sudo systemctl enable --now system-monitor
sudo systemctl status system-monitor
sudo journalctl -u system-monitor -f
Tune thresholds for real workloads
The defaults of 80 per cent CPU, 85 per cent memory and 85 per cent disk are deliberately conservative starting points. Change them to match a host’s role, then restart the service; a short spike should not use the same limit as sustained pressure.
For Nginx hosts, the web server tutorials show where access and error logs sit. If those paths use a separate mount, add that filesystem to the disk check because watching only / can hide a full log partition.
Account for Australian conditions
Australian conditions add useful operational detail. datetime.astimezone() records the machine’s UTC offset, including daylight saving for Sydney and Melbourne, while Perth remains on UTC+8. Do not convert that timestamp to UTC later and lose the local context.
Temperatures are conventionally reported in Celsius rather than Fahrenheit. The current script omits sensors because hardware interfaces vary, but any later temperature check should normalise units before comparison.
The Privacy Act 1988 and the Notifiable Data Breaches scheme affect many Australian organisations. Because this monitor stores operational metrics rather than personal information, it supports compliance work without replacing incident assessment, access controls or the Essential Eight.
Make the output routine
During the first week, compare the log with top, free -h and df -h. Tune thresholds from observed workloads, give the file a log-rotation policy, restrict access and keep the script and unit under configuration control so updates remain traceable.
The practical takeaway is a dependable one-minute baseline: fewer blind spots, quicker diagnosis and clear evidence before an Australian Linux host becomes unavailable.