add check_cert_file_expiry.py
This commit is contained in:
86
check_cert_file_expiry.py
Executable file
86
check_cert_file_expiry.py
Executable file
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/python3
|
||||
# Author: Yannik Enss
|
||||
import subprocess
|
||||
import datetime
|
||||
import argparse
|
||||
import enum
|
||||
import sys
|
||||
|
||||
class Status(enum.Enum):
|
||||
OK = 0
|
||||
WARNING = 1
|
||||
CRITICAL = 2
|
||||
UNKNOWN = 3
|
||||
|
||||
def get_expiry_date(filename):
|
||||
finished_process = subprocess.run(
|
||||
["openssl",
|
||||
"x509",
|
||||
"-in", filename,
|
||||
"-enddate",
|
||||
"-dateopt", "iso_8601",
|
||||
"-noout"],
|
||||
text=True, capture_output=True, check=True)
|
||||
date = finished_process.stdout.strip().split("=")[1]
|
||||
date = date.replace("Z", "") # needed for python < 3.11, because python is stupid
|
||||
date = datetime.datetime.fromisoformat(date)
|
||||
return date
|
||||
|
||||
def is_expired(filename, days_from_now=0):
|
||||
finished_process = subprocess.run(
|
||||
["openssl",
|
||||
"x509",
|
||||
"-in", filename,
|
||||
"-checkend", str(days_from_now*24*60*60),
|
||||
"-noout"],
|
||||
stdout=subprocess.DEVNULL)
|
||||
|
||||
if finished_process.returncode == 0:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("file")
|
||||
parser.add_argument("--warning-threshold", "-w", type=int, default=30)
|
||||
parser.add_argument("--critical-threshold", "-c", type=int, default=7)
|
||||
args = parser.parse_args()
|
||||
|
||||
status = Status.UNKNOWN
|
||||
message = "Plugin failed"
|
||||
perfdata = {}
|
||||
|
||||
try:
|
||||
expiry_date = get_expiry_date(args.file)
|
||||
|
||||
perfdata["expires_in"] = (expiry_date - datetime.datetime.now()).days
|
||||
|
||||
if is_expired(args.file, 0):
|
||||
message = f"Expired on {expiry_date}"
|
||||
status = Status.CRITICAL
|
||||
|
||||
elif is_expired(args.file, args.critical_threshold):
|
||||
message = f"Will expire on {expiry_date}"
|
||||
status = Status.CRITICAL
|
||||
|
||||
elif is_expired(args.file, args.warning_threshold):
|
||||
message = f"Will expire on {expiry_date}"
|
||||
status = Status.WARNING
|
||||
|
||||
else:
|
||||
message = f"Will expire on {expiry_date}"
|
||||
status = Status.OK
|
||||
|
||||
except Exception as e:
|
||||
message = f"Failed: {e}"
|
||||
status = Status.UNKNOWN
|
||||
|
||||
perfdata_str = ""
|
||||
for key,value in perfdata.items():
|
||||
perfdata_str += f"|{key}={value}"
|
||||
|
||||
print(f"{status.name}: {message}{perfdata_str}")
|
||||
sys.exit(status.value)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user