OpenVPN Server / ca certificate expiration check for Nagios

#!/usr/bin/python3

import argparse, os, sys, subprocess, time, math, datetime

def timeify(seconds):
    from collections import OrderedDict
    from math import floor

    units = dict()
    units["s"] = 1
    units["m"] = 60
    units["h"] = 60 * units["m"]
    units["d"] = 24 * units["h"]
    units["w"] = 7 * units["d"]
    units["y"] = 52 * units["w"]

    result = []
    for unit in reversed(units):
        if (s:=floor(seconds / units[unit])) != 0:
                result.append(str(s)+unit)
                seconds = seconds - s * units[unit];

    return (" ".join(result))

ap = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter)
ap.add_argument('certificate', help='Run cron-helper')
ap.add_argument('-c','--critical', help='Critical threshold', action='store', default=10)
ap.add_argument('-w','--warning', help='Warning threshold', action='store', default=30)
ap.add_argument('-d','--description', help='Add description to output', action='store')

args = ap.parse_args();

if not os.path.isfile(args.certificate):
    print ("ERROR: File `"+args.certificate+"` not found!");
    sys.exit(-1);

if not os.access(args.certificate, os.R_OK):
    print ("ERROR: File `"+args.certificate+"` not readable!");
    sys.exit(-1);

result = subprocess.run("openssl x509 -enddate -noout -in "+args.certificate+" | cut -c10- | date +%s -f -", shell=True, capture_output=True);

if result.returncode != 0:
    print ("ERROR: Could not run / failed to parse openssl output");
    sys.exit(-1);

try:
    expires = int(result.stdout)
except:
    print ("ERROR: Failed to parse openssl output");
    sys.exit(-1);

now = int(time.time())

if args.description:
    desc = " ("+args.description+")"
else:
    desc = "";

if expires < now:    # Expired
    print ("CRITICAL: Certificate "+args.certificate+desc+" expired "+timeify(now - expires)+" ago");
    sys.exit(2);

days_left = math.floor((expires-now) / 60 / 60 / 24)
valid_until = datetime.datetime.fromtimestamp(expires).strftime("%c");

if days_left <= int(args.critical):
    print ("CRITICAL: Certificate "+args.certificate+desc+" expires "+valid_until+" ("+str(days_left)+" days left)");
    sys.exit(2);

if days_left <= int(args.warning):
    print ("WARNING: Certificate "+args.certificate+desc+" expires "+valid_until+" ("+str(days_left)+" days left)");
    sys.exit(1);

print ("OK: Certificate "+args.certificate+desc+" valid until "+valid_until+" ("+str(days_left)+" days left)");
sys.exit(0);
Dette indlæg blev udgivet i Python. Bogmærk permalinket.