9ddfc06
#!/usr/bin/python
9ddfc06
from __future__ import print_function
9ddfc06
from sys import stderr
9ddfc06
9ddfc06
import subprocess, time, calendar, os, getopt
9ddfc06
9ddfc06
def usage():
9ddfc06
  print("""Usage: cert-check [options] files ...
9ddfc06
	-h,--help	this message
9ddfc06
	-q,--quiet	do not print cert files needing (re)newing
9ddfc06
	-d n,--days=n	days before expiration to renew (default 7)
9ddfc06
Succeeds only if all certs exist and are more than <days> from expiration.""",
9ddfc06
        file=stderr)
9ddfc06
  return 2
9ddfc06
9ddfc06
def main(argv):
9ddfc06
  days = 7	# days ahead to 
9ddfc06
  quiet = False
9ddfc06
9ddfc06
  try:
9ddfc06
    opts,args = getopt.getopt(argv,'hqd:',['days=','quiet','help'])
9ddfc06
  except getopt.GetoptError as err:
9ddfc06
    # print help information and exit:
9ddfc06
    print(err,file=stderr) # prints something like "option -a not recognized"
9ddfc06
    return usage()
9ddfc06
9ddfc06
  for opt,val in opts:
9ddfc06
    if opt in ('-h','--help'):
9ddfc06
      return usage()
9ddfc06
    if opt in ('-q','--quiet'):
9ddfc06
      quiet = True
9ddfc06
    if opt in ('-d','--days'):
9ddfc06
      try:
9ddfc06
        days = int(val)
9ddfc06
      except:
9ddfc06
        return usage()
9ddfc06
      
9ddfc06
  now = time.time()
9ddfc06
  soon = now + days * 24 * 60 * 60
9ddfc06
  rc = 0
9ddfc06
9ddfc06
  for fn in args:
9ddfc06
      try:
9ddfc06
          size = os.path.getsize(fn)
9ddfc06
      except:
9ddfc06
          size = 0
9ddfc06
      if size == 0:
9ddfc06
          if not quiet: print(fn)
9ddfc06
          rc += 1
9ddfc06
          continue
9ddfc06
      proc = subprocess.Popen(
9ddfc06
          ["openssl", "x509", "-in", fn, "-noout", "-enddate"],
9ddfc06
          stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
9ddfc06
      out, err = proc.communicate()
9ddfc06
      if proc.returncode != 0:
9ddfc06
          raise IOError("{1}: OpenSSL Error: {0}".format(err,fn))
9ddfc06
      t = time.strptime(out.decode(),'notAfter=%b %d %H:%M:%S %Y GMT\n')
9ddfc06
      t = calendar.timegm(t)
9ddfc06
      if soon > t: 
9ddfc06
          if not quiet: print(fn)
9ddfc06
          rc += 1
9ddfc06
  return rc > 0
9ddfc06
9ddfc06
if __name__ == '__main__':
9ddfc06
  import sys
9ddfc06
  sys.exit(main(sys.argv[1:]))