Skip to content

Instantly share code, notes, and snippets.

@tasoseng
Created March 26, 2021 20:59
Show Gist options
  • Save tasoseng/0db814046cb267f5460d22ab38324879 to your computer and use it in GitHub Desktop.
Save tasoseng/0db814046cb267f5460d22ab38324879 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import os
from cryptography import x509
from cryptography.hazmat.backends import default_backend
import pem
from datetime import datetime
try:
CERTPATH = sys.argv[1]
except IndexError:
CERTPATH = "/etc/ssl/certs"
checkdays = 30
_, _, certfiles = next(os.walk(CERTPATH))
EXIT = [0,0,0,0]
for certfile in certfiles:
certs = pem.parse_file(CERTPATH+"/"+certfile)
for i, cert in enumerate(certs):
try:
x = x509.load_pem_x509_certificate(data=cert.as_bytes(),backend=default_backend())
subj = x.subject.rfc4514_string() if 'rfc4514_string' in dir(x.subject) else str(x.subject.rdns[-1]).split("'")[1] # centos too old
expiry = x.not_valid_after
now = datetime.now()
diff = expiry - now
if diff.total_seconds() < 0:
print("CRITICAL - cert {} ({}) in file {} expired {} days ago".format(i, subj, certfile, -diff.days))
EXIT[2] += 1
elif diff.total_seconds() < 86400*checkdays:
print("WARNING - cert {} ({}) in file {} will expire in {} days".format(i, subj, certfile, diff.days))
EXIT[1] += 1
except:
print("UNKNOWN - cert {} ({}) in file {}".format(i, subj, certfile))
print(sys.exc_info()[0])
EXIT[3] += 1
pass
i=2
while EXIT[i]==0:
i -= 1
if i==0 and EXIT(3)>0:
exit(3)
else:
exit(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment