SSL certificate expiry watch in Python
Minimal script that checks an SSL certificate and alerts 14 days before expiry.
Recipe
import ssl, socket, datetime
def days_left(host: str, port: int = 443) -> int:
ctx = ssl.create_default_context()
with socket.create_connection((host, port), timeout=10) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as ss:
not_after = ss.getpeercert()["notAfter"]
exp = datetime.datetime.strptime(not_after, "%b %d %H:%M:%S %Y %Z")
return (exp - datetime.datetime.utcnow()).days
if days_left("example.com") < 14:
raise SystemExit("SSL expiring soon")
Same thing in Enterno.io
Enterno SSL check + monitor: automatic email + Telegram at T-14 and T-3 days before expiry, full chain validation (intermediate, OCSP, cipher).
Related recipes
Your cron silently stopped running. Need an alert when the script misses its window.
Site is on the HSTS preload list, but after an nginx refactor the header is gone. In 3 months the domain will be removed from the preload list. Need a daily check.
Caddy usually renews on its own, but once a Let's Encrypt rate-limit broke the cycle and we found out 2 days before expiry. Want a belt-and-braces daily check.