Skip to content

Instantly share code, notes, and snippets.

@sephii
Last active February 3, 2020 07:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sephii/0d9f01e5149d6bc06bcf92617cfbec50 to your computer and use it in GitHub Desktop.
Save sephii/0d9f01e5149d6bc06bcf92617cfbec50 to your computer and use it in GitHub Desktop.
Check for letsencrypt/certbot certificates expiry date. Can be run in a cron
#!/usr/bin/env python3
"""
Usage: certcheck.py host1 host2 hostN. Will exit with status code 1 if any of the hosts is about to expire (see
WARNING_DAYS below).
"""
from datetime import datetime
import socket
import ssl
import sys
WARNING_DAYS = 7
def certificate_about_to_expire(host, port=443):
conn = ssl.create_default_context().wrap_socket(socket.socket(socket.AF_INET), server_hostname=host)
conn.connect((host, port))
expiry_date = datetime.utcfromtimestamp(ssl.cert_time_to_seconds(conn.getpeercert()['notAfter']))
return (expiry_date - datetime.now()).days <= WARNING_DAYS
def main(hosts):
hosts_about_to_expire = list(filter(certificate_about_to_expire, hosts))
if hosts_about_to_expire:
print("The following hosts are about to expire:")
print('\n'.join(hosts_about_to_expire))
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment