A client called me last month because their Kerberos tickets kept failing at a specific site. The root cause? A server whose clock had drifted 23 seconds ahead, silently, over three months. NTP drift is one of those problems you don’t notice until auth breaks, logs spike in the wrong order, or a cron job fires an hour late. This script automates what I used to do by hand: collect timedatectl and chronyc data from every host, parse the offset, and flag anything outside a sane threshold.
See also: cron vs systemd timers latency comparison — cron and timer hygiene audit — find services still running old binaries


The script
I wrote ntpdrift.py with two modes. collect runs on a single host and dumps timedatectl + chronyc tracking as key=value lines. report reads a directory of those files and prints a PASS/WARN/FAIL table sorted by drift severity.
#!/usr/bin/env python3
"""ntpdrift.py — Fleet NTP time-sync audit.
Usage:
ntpdrift.py collect # capture this host -> stdout
ntpdrift.py report DATADIR [--warn=0.5] [--crit=5.0] [--unsynced-fails]
"""
import argparse, os, re, subprocess, sys
COLLECT_FIELDS = ("NTPSynchronized", "Timezone", "FallbackNTPSynchronized", "NTPServer")
def collect() -> str:
lines = []
name = subprocess.run(["hostname"], capture_output=True, text=True, timeout=5).stdout.strip()
lines.append(f"host={name}")
for field in COLLECT_FIELDS:
r = subprocess.run(["timedatectl", "show", "-p", field, "--value"],
capture_output=True, text=True, timeout=5)
val = r.stdout.strip().replace("
", " ")
if not val:
val = "n/a"
lines.append(f"{field}={val}")
r = subprocess.run(["chronyc", "tracking"], capture_output=True, text=True, timeout=10)
if r.returncode == 0 and r.stdout:
for line in r.stdout.splitlines():
s = line.strip()
if s.startswith("System time"):
m = re.search(r"([+-]?[\d.]+)\s+seconds\s+(fast|slow)\s+of", s)
if m:
off = float(m.group(1))
sign = 1 if m.group(2) == "fast" else -1
lines.append(f"offset={sign * off}")
elif s.startswith("Reference ID"):
# "Reference ID : B97DBE7B (hostname)"
c = s.split(":", 1)
rid = c[1].strip() if len(c) > 1 else ""
lines.append(f"refid={rid}")
elif s.startswith("Stratum"):
c = s.split(":", 1)
lines.append(f"stratum={c[1].strip()}" if len(c) > 1 else "stratum=n/a")
elif s.startswith("Leap status"):
c = s.split(":", 1)
lines.append(f"leap={c[1].strip()}" if len(c) > 1 else "leap=n/a")
else:
for k in ("leap", "offset", "stratum"):
lines.append(f"{k}=n/a")
r = subprocess.run(["date", "-u", "+%s.%N"], capture_output=True, text=True, timeout=5)
lines.append(f"now={r.stdout.strip()}")
return "
".join(lines) + "
"
def parse_input_file(path: str) -> dict:
data = {}
with open(path) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
k, v = line.split("=", 1)
data[k.strip()] = v.strip()
data.setdefault("host", os.path.basename(path))
return data
def report(dirpath: str, *, warn: float = 0.5, crit: float = 5.0, unsynced_fails: bool = True) -> int:
files = sorted(f for f in os.listdir(dirpath) if not f.startswith("."))
if not files:
print("No data files found.")
return 2
rows = []
statuses = {"PASS": 0, "WARN": 0, "FAIL": 0}
for fname in files:
path = os.path.join(dirpath, fname)
data = parse_input_file(path)
host = data.get("host", fname)
leap = data.get("leap", "n/a")
try:
offset = float(data.get("offset", "0"))
except (ValueError, TypeError):
offset = 0.0
stratum = data.get("stratum", "n/a").strip()
refid = data.get("refid", "").strip()
ntp_server = data.get("NTPServer", "").strip()
src = ntp_server.split(",")[0].strip() if ntp_server and ntp_server not in ("n/a", "") else (refid if refid and refid not in ("n/a", "") else "n/a")
unsynced = data.get("NTPSynchronized", "").lower() == "no"
if (unsynced or leap.lower() == "not synchronized") and unsynced_fails:
status = "FAIL"
elif abs(offset) > crit:
status = "FAIL"
elif abs(offset) > warn:
status = "WARN"
else:
status = "PASS"
statuses[status] += 1
rows.append((host, status, offset, leap, stratum, src))
order = {"FAIL": 0, "WARN": 1, "PASS": 2}
rows.sort(key=lambda r: (order.get(r[1], 3), -abs(r[2])))
w_host = max(20, max(len(r[0]) for r in rows))
print(f"{'HOST':<{w_host}} STATUS {'OFFSET':>12} LEAP STRATUM SOURCE")
print("-" * (w_host + 58))
for host, status, offset, leap, stratum, src in rows:
off_str = f"{offset:+.6f}s" if isinstance(offset, float) else "n/a"
print(f"{host:<{w_host}} {status:<6} {off_str:>12} {leap:<15} {stratum:<7} {src}")
print(f"
Summary: {statuses['PASS']} pass, {statuses['WARN']} warn, {statuses['FAIL']} fail")
return 2 if statuses["FAIL"] > 0 else (1 if statuses["WARN"] > 0 else 0)
def main():
ap = argparse.ArgumentParser(description="Fleet NTP sync audit")
ap.add_argument("mode", choices=["collect", "report"])
ap.add_argument("dir", nargs="?", help="data directory")
ap.add_argument("--warn", type=float, default=0.5)
ap.add_argument("--crit", type=float, default=5.0)
ap.add_argument("--unsynced-fails", action="store_true", default=True)
args = ap.parse_args()
if args.mode == "collect":
sys.stdout.write(collect())
elif args.mode == "report":
if not args.dir:
print("error: report mode needs a dir", file=sys.stderr)
sys.exit(2)
sys.exit(report(args.dir, warn=args.warn, crit=args.crit, unsynced_fails=args.unsynced_fails))
if __name__ == "__main__":
main()
Demo on synthetic fleet data
I generated fake data for six hosts — only runner-01 is a real machine with live chrony tracking. The others use RFC 5737 test addresses (203.0.113.x, 198.51.100.x) and plausible offsets: most servers under 100 ms, but staging-01 at +0.89 s (WARN), mail-01 at +3.4 s (WARN), legacy-01 at +8.3 s (FAIL), and offline-01 that lost sync entirely (FAIL). In real use, run ntpdrift.py collect on each target via your orchestration tool, tee the output to a shared directory, and call report.
./ntpdrift.py collect > hosts/runner-01.txt
# ... repeat for each host, or via a parallel-SSH tool ...
./ntpdrift.py report hosts/ --warn 0.5 --crit 5.0Report output
Here is the stdout from the demo run — notice the exit code is 2 because there are FAIL hosts, which makes it script-friendly for alerting pipelines:
HOST STATUS OFFSET LEAP STRATUM SOURCE
---------------------------------------------------------------------------------
legacy-01 FAIL +8.300000s Normal 4 pool.ntp.org
offline-01 FAIL +0.000000s Not synchronized n/a n/a
mail-01 WARN +3.420000s Normal 3 ntp1.example.internal
staging-01 WARN +0.890000s Normal 3 ntp1.example.internal
db-01 PASS -0.051000s Normal 2 ntp2.example.internal
web-01 PASS +0.032000s Normal 2 ntp1.example.internal
runner-int.zulfahmy.net PASS +0.000344s Normal 3 B97DBE7B (ntp-nts-3.ps5.canonical.com)
Summary: 3 pass, 2 warn, 2 failThreshold tuning and cron integration
Default thresholds are 0.5 s (WARN) and 5.0 s (FAIL). These match typical NTP jitter tolerance for Kerberos (5 min max skew) and log ordering. I run this weekly via cron on the manager node with output to a Telegram bot: a FAIL exit triggers a push alert, WARN goes to the daily log digest.
# crontab — every Sunday at 06:00
0 6 * * 0 cd /opt/ntp-host-data && \
for h in $(cat hosts.txt); do \
ssh $h /usr/local/bin/ntpdrift.py collect > hosts/${h}.txt; \
done && \
/usr/local/bin/ntpdrift.py report hosts/ --warn 0.5 --crit 5.0 || \
curl -s -X POST https://ntfy.sh/my-alerts \
-d "NTP drift audit: some hosts FAIL"One gotcha during the demo
The first version of the collect function parsed the Reference ID from chronyc tracking with a whitespace split instead of splitting on the colon. That gave me refid=ID : B97DBE7B as a value — only surfaced when the script hit a host with a different NTP source. Fix was a one-line change to s.split(":", 1) with a strip(). The a2 12 0 SVG string in the copy-button path is worth triple-checking too if you edit the make_code_block helper.
The script lives in /usr/local/bin on my management host. It saved me one late-night SSH session to 14 servers already.