Production Linux services rarely fail loudly at convenient hours. A crashing nginx worker, stalled postgresql daemon, or failing background queue can silently take an application offline unless an automated systemd service monitor script checks unit health continuously and dispatches actionable alerts.
Instead of parsing human-formatted systemctl status output or installing heavy monitoring agents, this zero-dependency Python 3.10+ script queries machine-readable properties via systemctl show, extracts recent crash context from journalctl, persists unit states in /var/tmp/systemd_monitor_state.json to prevent alert fatigue, and sends Slack or Discord webhook notifications only on state transitions.
Table of Contents
Prerequisites and Environment Setup
Create a dedicated directory at /opt/systemd-monitor and store your monitored unit list and webhook endpoint in a restricted .env file:
sudo mkdir -p /opt/systemd-monitor
sudo tee /opt/systemd-monitor/.env >/dev/null <<'EOF'
MONITOR_UNITS=nginx.service,postgresql.service,redis-server.service
WEBHOOK_URL=https://hooks.slack.com/services/REPLACE/WITH/TOKEN
STATE_FILE=/var/tmp/systemd_monitor_state.json
EOF
sudo chmod 600 /opt/systemd-monitor/.env
Complete Python Systemd Service Monitor Script
Save the following script to /opt/systemd-monitor/systemd_monitor.py. It supports explicit --units monitoring, automatic --scan-failed discovery, --json output for cron or CI pipelines, and a safe --dry-run mode for testing before enabling the timer:
#!/usr/bin/env python3
"""Zero-dependency systemd service monitor with crash log capture and webhook alerts."""
import argparse
import json
import os
import socket
import subprocess
import sys
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
def run_cmd(cmd: list[str]) -> str:
res = subprocess.run(cmd, capture_output=True, text=True, check=False)
return res.stdout.strip()
def query_unit_state(unit: str) -> dict[str, str]:
out = run_cmd([
"systemctl", "show", unit,
"--property=Id,LoadState,ActiveState,SubState,Result",
])
props = {}
for line in out.splitlines():
if "=" in line:
k, v = line.split("=", 1)
props[k] = v.strip()
return {
"unit": props.get("Id", unit),
"load": props.get("LoadState", "unknown"),
"active": props.get("ActiveState", "unknown"),
"sub": props.get("SubState", "unknown"),
"result": props.get("Result", "unknown"),
}
def scan_failed_units() -> list[str]:
out = run_cmd([
"systemctl", "list-units", "--type=service",
"--state=failed", "--no-legend", "--plain",
])
units = []
for line in out.splitlines():
parts = line.split()
if parts:
units.append(parts[0])
return units
def get_recent_logs(unit: str, lines: int = 12) -> str:
out = run_cmd([
"journalctl", "-u", unit, "-n", str(lines),
"--no-pager", "-o", "short-iso",
])
return out or "(no recent journalctl entries available)"
def load_state(path: Path) -> dict[str, str]:
if not path.exists():
return {}
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
def save_state(path: Path, state: dict[str, str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(state, indent=2), encoding="utf-8")
def send_webhook(url: str, message: str, dry_run: bool = False) -> None:
payload = json.dumps({"text": message, "content": message}).encode("utf-8")
if dry_run:
print(f"[DRY-RUN WEBHOOK]\n{message}", file=sys.stderr)
return
req = urllib.request.Request(
url,
data=payload,
headers={"Content-Type": "application/json", "User-Agent": "systemd-monitor/1.0"},
method="POST",
)
with urllib.request.urlopen(req, timeout=5):
pass
def print_table(statuses: list[dict[str, str]]) -> None:
print(f"{'UNIT':<34} {'LOAD':<10} {'ACTIVE':<10} {'SUB':<12} RESULT")
for s in statuses:
print(f"{s['unit']:<34} {s['load']:<10} {s['active']:<10} {s['sub']:<12} {s['result']}")
def main() -> int:
parser = argparse.ArgumentParser(description="Monitor systemd units and alert on crashes.")
parser.add_argument("--units", help="Comma-separated systemd unit names")
parser.add_argument("--scan-failed", action="store_true", help="Include any failed systemd services")
parser.add_argument("--json", action="store_true", help="Output status as JSON")
parser.add_argument("--dry-run", action="store_true", help="Do not send webhooks or save state")
args = parser.parse_args()
env_units = [u.strip() for u in (args.units or os.getenv("MONITOR_UNITS", "")).split(",") if u.strip()]
units = list(dict.fromkeys(env_units + (scan_failed_units() if args.scan_failed else [])))
if not units:
print("No units specified via --units, MONITOR_UNITS, or --scan-failed.", file=sys.stderr)
return 0
host = socket.gethostname()
now_utc = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
state_path = Path(os.getenv("STATE_FILE", "/var/tmp/systemd_monitor_state.json"))
prev_state = load_state(state_path)
curr_state: dict[str, str] = {}
statuses: list[dict[str, str]] = []
alerts: list[str] = []
for unit in units:
st = query_unit_state(unit)
statuses.append(st)
active = st["active"]
curr_state[unit] = active
old_active = prev_state.get(unit, "active")
if active != "active" and old_active == "active":
logs = get_recent_logs(unit)
alerts.append(
f"*[SYSTEMD CRASH]* `{host}` | `{unit}` entered `{active}/{st['sub']}` at {now_utc}\n```\n{logs}\n```"
)
elif active == "active" and old_active != "active":
alerts.append(
f"*[SYSTEMD RECOVERED]* `{host}` | `{unit}` is back to `active` at {now_utc}"
)
if args.json:
print(json.dumps({"host": host, "timestamp_utc": now_utc, "units": statuses}, indent=2))
else:
print_table(statuses)
webhook_url = os.getenv("WEBHOOK_URL")
if webhook_url and alerts:
send_webhook(webhook_url, "\n\n".join(alerts), dry_run=args.dry_run)
if not args.dry_run:
save_state(state_path, curr_state)
return 1 if any(s["active"] != "active" for s in statuses) else 0
if __name__ == "__main__":
sys.exit(main())
Testing With Dry-Run Mode
Run a safe --dry-run pass first to verify unit names, state output, and journalctl access without modifying your state file or sending alerts:
chmod +x /opt/systemd-monitor/systemd_monitor.py
set -a && source /opt/systemd-monitor/.env && set +a
python3 /opt/systemd-monitor/systemd_monitor.py --scan-failed --dry-run
Scheduling With a Systemd Timer Every Two Minutes
Schedule the monitor using a lightweight systemd timer running every two minutes so crashes are caught quickly without spawning heavy daemons. Combine it with your Nginx log analyzer script and automated Linux server backups for end-to-end host reliability:
sudo tee /etc/systemd/system/systemd-monitor.service >/dev/null <<'EOF'
[Unit]
Description=Systemd Service Crash & Recovery Monitor
[Service]
Type=oneshot
EnvironmentFile=/opt/systemd-monitor/.env
ExecStart=/usr/bin/python3 /opt/systemd-monitor/systemd_monitor.py --scan-failed
EOF
sudo tee /etc/systemd/system/systemd-monitor.timer >/dev/null <<'EOF'
[Unit]
Description=Run Systemd Service Monitor Every 2 Minutes
[Timer]
OnBootSec=1min
OnUnitActiveSec=2min
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now systemd-monitor.timer
Troubleshooting and Security Hardening
Watch for these three operational edge cases when rolling out systemd service monitoring across Ubuntu, Debian, or RHEL hosts:
- Unit Name Differences Across Distros: Ubuntu names the SSH daemon
sshwhile RHEL and Fedora name itsshd. Ifsystemctl showreturnsnot-found, verify the exact unit name viasystemctl list-unit-files --type=servicebefore adding it toMONITOR_UNITS. - Journalctl Permission Errors: If non-root users see empty log snippets in webhook alerts, add the service user to the
systemd-journalgroup or run the oneshot monitor timer asrootwith0750permissions on/opt/systemd-monitor/systemd_monitor.py. - Webhook Timeout & Secret Protection: Keep
WEBHOOK_URLinside your0600.envfile and preservetimeout=5inurllib.request.urlopen()so a slow Slack or Discord API never stalls your timer queue.
Frequently Asked Questions
Does this systemd service monitor script require pip packages?
No. It uses Python 3.10+ standard library modules only (subprocess, urllib.request, json, and pathlib), so it runs cleanly on minimal Linux servers without virtual environments.
How does the script avoid spamming Slack or Discord every two minutes?
It persists each unit’s last observed ActiveState in /var/tmp/systemd_monitor_state.json and triggers an alert only when a unit transitions from active to a non-active state—or when it recovers back to active.
What does –scan-failed do compared to –units?
The –units flag checks your explicit list of critical services, while –scan-failed also runs systemctl list-units –state=failed so unexpected failures in any other system service are caught automatically.
Why use systemctl show instead of systemctl status in scripts?
systemctl status formats human-readable text and truncates lines, whereas systemctl show outputs machine-parsable key=value properties like ActiveState and SubState.
What does –dry-run test before enabling the timer?
Passing –dry-run queries live systemd unit states, prints the status table or JSON output, and logs any webhook alert payloads to stderr without sending HTTP requests or overwriting the state file.
Can I monitor user-level systemd services with this script?
Yes. Add the –user flag to the systemctl and journalctl argument lists inside query_unit_state() and get_recent_logs() when running under a non-root user session.