Skip to content

Instantly share code, notes, and snippets.

@h0tw1r3
Last active October 24, 2021 00:36
Show Gist options
  • Save h0tw1r3/166c238c7289735848313f8cf3cf7991 to your computer and use it in GitHub Desktop.
Save h0tw1r3/166c238c7289735848313f8cf3cf7991 to your computer and use it in GitHub Desktop.
nagios style last system update check for yum, dnf and apt
#!/usr/bin/env python
from __future__ import print_function
from datetime import timedelta
from datetime import datetime
import os
import re
import sys
def normalize_cmdline(cmdline):
norm_cmdline = cmdline.split()
for opt in list(norm_cmdline):
if opt.startswith('-') or opt.isnumeric():
norm_cmdline.remove(opt)
return ' '.join(norm_cmdline)
NAG_OK = 0
NAG_WARNING = 1
NAG_CRITICAL = 2
NAG_UNKNOWN = 3
# cli arguments
crit_days = 31 if (len(sys.argv) < 2) else int(sys.argv[1])
if len(sys.argv) < 3:
warn_days = (float(crit_days) / 4.0) * 3
else:
warn_days = int(sys.argv[2])
crit_dt = datetime.now() - timedelta(days=crit_days)
warn_dt = datetime.now() - timedelta(days=warn_days)
last_dt = None
apt_log_path = os.getenv('APT_LOG_PATH', '/var/log/apt')
if os.path.exists(apt_log_path):
# test
import gzip
import glob
os.chdir(apt_log_path)
found = False
for histfile in sorted(glob.glob("history.log*"), key=os.path.getmtime, reverse=True):
file = gzip.open(histfile, 'r') if histfile.endswith('.gz') else open(histfile, 'rb')
for line in file:
if line.startswith('Start-Date: '):
found = False
elif not found and re.match(r'Commandline: apt(-get)?( -y)? (dist-)?upgrade( -y)?$', line):
found = True
elif found and line.startswith('End-Date: '):
last_dt = datetime.strptime(line, 'End-Date: %Y-%m-%d %H:%M:%S\n')
file.close()
if last_dt is not None:
break
elif os.path.exists('/var/lib/dnf'):
import dnf
pm = dnf.Base()
for old in pm.history.old():
if old.cmdline is not None:
cmdline = normalize_cmdline(old.cmdline)
if re.match(r'(system-upgrade )?(upgrade|update)$', cmdline) and len(old.error()) == 0:
if old.end_timestamp is None:
last_dt = datetime.fromtimestamp(old.beg_timestamp)
else:
last_dt = datetime.fromtimestamp(old.end_timestamp)
break
elif os.path.exists('/var/lib/yum'):
import yum
pm = yum.YumBase()
pm.preconf.debuglevel = 0
pm.preconf.errorlevel = 0
for old in pm.history.old():
if old.cmdline is not None:
cmdline = normalize_cmdline(old.cmdline)
if re.match(r'(upgrade|update)$', cmdline) and len(old.errors) == 0:
if old.end_timestamp is None:
last_dt = datetime.fromtimestamp(old.beg_timestamp)
else:
last_dt = datetime.fromtimestamp(old.end_timestamp)
break
else:
print('unsupported os')
raise SystemExit(NAG_UNKNOWN)
if last_dt is not None:
print(last_dt)
if last_dt < crit_dt:
raise SystemExit(NAG_CRITICAL)
elif last_dt < warn_dt:
raise SystemExit(NAG_WARNING)
else:
raise SystemExit(NAG_OK)
print('not found')
raise SystemExit(NAG_UNKNOWN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment