cert-checker.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  2. import datetime
  3. import socket
  4. import ssl
  5. import requests
  6. def get_cert(domain):
  7. context = ssl.create_default_context()
  8. conn = context.wrap_socket(
  9. socket.socket(socket.AF_INET),
  10. server_hostname=domain,
  11. )
  12. # 3 second timeout because Lambda has runtime limitations
  13. conn.settimeout(3.0)
  14. conn.connect((domain, 443))
  15. return conn.getpeercert()
  16. def ssl_alt_names(ssl_info):
  17. return [item[1] for item in ssl_info['subjectAltName']]
  18. def ssl_valid_time_remaining(ssl_info):
  19. ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
  20. expires = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
  21. return expires - datetime.datetime.utcnow()
  22. def check_domain(domain):
  23. cert = get_cert(domain)
  24. t_remaining = ssl_valid_time_remaining(cert)
  25. return t_remaining.days + t_remaining.seconds / 86400
  26. def post_data(domain, time):
  27. db = 'scripts_data'
  28. INFLUXDB_HOST = "http://grafana.labs:8086/write?db=%s" % db
  29. data = 'days_remaining,hostname=%s value=%.2f' % (domain, time)
  30. headers = {'Content-Type': 'application/octet-stream'}
  31. r = requests.post(INFLUXDB_HOST, data=data, headers=headers)
  32. if r.status_code < 200 or r.status_code > 300:
  33. print("When posting %s I got status_code %d" % (domain, r.status_code))
  34. hosts = [ 'labs.davidventura.com.ar', 'especificosba.com.ar', 'casa.especificosba.com.ar' ]
  35. data = []
  36. for h in hosts:
  37. try:
  38. t = check_domain(h)
  39. data.append((h,t))
  40. except Exception as e:
  41. print("Exception while contacting %s" % h)
  42. print(e)
  43. for d in data:
  44. post_data(*d)