#!/usr/bin/env python import subprocess import re import argparse import sys class cert: def __init__(self, name, expiration, certType): self.name = name self.exp = exp self.certType = certType def GetOptions(): p = argparse.ArgumentParser() p.add_argument( '--warning', dest='warning', required=True, type=int, help='Warning' ) p.add_argument( '--critical', dest='critical', required=True, type=int, help='Critical' ) return p.parse_args() opt = GetOptions() # cmd contains shell command cmd="/bin/sudo /usr/bin/kubeadm certs check-expiration | /usr/bin/awk '{ print $1, $7 }'" process = subprocess.Popen(cmd,shell=True,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE) # The output from your shell command result=process.stdout.readlines() certType = "" certListWarning = [] certListCritical = [] matched = False for line in result: if "CERTIFICATE EXTERNALLY" in line.decode("utf-8"): certType = "Externally" if "CERTIFICATE MANAGED" in line.decode("utf-8"): certType = "Managed" regex = re.search("^(.*)\s([0-9]+)([d|y])$", line.decode("utf-8")) if regex: exp = None name = regex.group(1) unit = regex.group(3) try: exp = int(regex.group(2)) except ValueError: print("Error parsing expiration column") sys.exit(3) matched = True if unit == "y": continue if unit == "d": if exp <= opt.critical: certListCritical.append(cert(name, exp, certType)) elif exp <= opt.warning: certListWarning.append(cert(name, exp, certType)) else: continue if not matched: print("Error parsing command") sys.exit(3) code = 0 if certListWarning: code = 1 print("Warning certificates:") for cert in certListWarning: print(cert.certType+": "+cert.name+" "+str(cert.exp)+" days") if certListCritical: code = 2 print("Critical certificates:") for cert in certListCritical: print(cert.certType+": "+cert.name+" "+str(cert.exp)+" days") if code == 0: print("Kubernetes Certificates are up to date") sys.exit(0) sys.exit(code)