How to check TLS certificate expiry for all your domains with a 50-line Python script (and catch the ones auto-renew missed)
Uptime monitoring from outside your own infrastructure that alerts you the minute your site goes down — upordown.online "We use Let's Encrypt with auto-renew, so certificates aren't a problem anymore." Mostly true. Au
Uptime monitoring from outside your own infrastructure that alerts you the minute your site goes down — upordown.online
"We use Let's Encrypt with auto-renew, so certificates aren't a problem anymore."
Mostly true. Auto-renewal removed the classic "someone forgot to buy the certificate" outage. It replaced it with a quieter set of failures:
- The renewal job fails because a DNS or firewall change broke the HTTP-01 challenge, and the failure email goes to an address nobody reads.
- The certificate is renewed on disk, but the web server is never reloaded, so it keeps serving the old one until it expires.
- One server behind the load balancer has its own copy and was missed.
- A forgotten subdomain (
status.,old-api.,mail.) had a certificate issued manually two years ago.
The fix for all of these is the same: don't check the certificate files, check the certificate each hostname is actually serving. That's what this script does.
The script
It uses only the Python standard library. Put your hostnames in a text file, one per line, optionally with a port:
www.example.com
api.example.com
status.example.com
mail.example.com:465
Then:
#!/usr/bin/env python3
"""Warn about TLS certificates that are close to expiry or already broken."""
import socket, ssl, sys
from datetime import datetime, timezone
WARN_DAYS = 21
TIMEOUT = 10
def check(host, port=443):
ctx = ssl.create_default_context()
with socket.create_connection((host, port), timeout=TIMEOUT) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as tls:
cert = tls.getpeercert()
expires = datetime.fromtimestamp(
ssl.cert_time_to_seconds(cert["notAfter"]), tz=timezone.utc)
issuer = dict(x[0] for x in cert["issuer"]).get("organizationName", "?")
days = (expires - datetime.now(timezone.utc)).days
return days, expires, issuer
def main(path):
problems = 0
for line in open(path):
line = line.strip()
if not line or line.startswith("#"):
continue
host, _, port = line.partition(":")
port = int(port or 443)
try:
days, expires, issuer = check(host, port)
except ssl.SSLCertVerificationError as e:
print(f"FAIL {host}:{port} verification failed: {e.verify_message}")
problems += 1
continue
except (OSError, ssl.SSLError) as e:
print(f"FAIL {host}:{port} could not connect: {e}")
problems += 1
continue
status = "WARN" if days < WARN_DAYS else "ok "
if days < WARN_DAYS:
problems += 1
print(f"{status} {host}:{port} {days:>4} days "
f"{expires:%Y-%m-%d} {issuer}")
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "hosts.txt"))
Run it:
python3 certcheck.py hosts.txt
ok www.example.com:443 62 days 2027-01-17 Let's Encrypt
WARN status.example.com:443 9 days 2026-11-25 Let's Encrypt
FAIL old-api.example.com:443 verification failed: certificate has expired
ok mail.example.com:465 48 days 2027-01-03 Let's Encrypt
The exit code is 1 if anything needs attention, so it drops straight into cron or CI.
Why each part is there
create_default_context() verifies the certificate. That means an expired certificate, a hostname mismatch or a missing intermediate shows up as FAIL, not as a number of days. Those are all real outages for visitors, so they should be loud.
server_hostname=host sends SNI. Without it, a server hosting many sites returns its default certificate, and you'd be checking the wrong one.
The 21-day threshold. Let's Encrypt certificates last 90 days and most clients renew at 30 days left. If a certificate is under 21 days, renewal has already failed at least once, and that's the moment you want to hear about it, not at 2 days.
Issuer in the output. It's a cheap way to spot certificates that were issued outside your normal process.
Checking every server, not just the hostname
DNS for www.example.com returns one address (or a rotating set), so the script checks whichever server it happens to reach. To check every backend, connect to each IP while sending the right SNI:
def check_ip(host, ip, port=443):
ctx = ssl.create_default_context()
with socket.create_connection((ip, port), timeout=TIMEOUT) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as tls:
return tls.getpeercert()["notAfter"]
Loop over your backend IPs and compare the notAfter values. If one server reports an older date than the others, that's the box that missed the reload. This is the single most common certificate outage I've seen with auto-renewal: the cert renewed fine, and one node kept serving the old one.
A script on a cron job only helps if the cron job runs and someone reads the output. upordown.online checks your sites from outside, and alerts you the moment visitors start seeing a certificate error, even if the warning email went nowhere.
Finding the hostnames you forgot
The list of hostnames is the weak point. A few ways to build it:
- Export all A, AAAA and CNAME records from your DNS provider and check every one that answers on 443.
- Search Certificate Transparency logs (crt.sh is the usual front end) for your domain. Every publicly trusted certificate ever issued for it shows up there, including the ones somebody issued by hand for a demo in 2023.
- Grep your reverse proxy and load balancer configs for
server_nameand host rules.
The certificate transparency search is usually the eye-opener. It tends to find two or three subdomains nobody remembered existed, some of them still serving traffic.
Running it
Put it in a daily cron job on a machine that isn't one of the web servers, and send the output somewhere a human sees it when the exit code is 1. Keep the hosts file in version control, and add "update hosts.txt" to the checklist for creating a new subdomain.
Then keep an outside check on the main URLs too. The script tells you a certificate is going to expire; an uptime check from upordown.online tells you when visitors are actually getting the browser warning.
Related reading
- Case study (hypothetical): the payment provider's status page said 'operational' while our checkout timed out for 40 minutes
- Six TLS certificate myths that cause outages (and one that just wastes money)
- How to fix 'Your connection is not private' in Chrome (NET::ERR_CERT_DATE_INVALID and friends), as a visitor and as the site owner
- Your uptime alerts have never been tested. A 12-point checklist to prove they'll actually wake you
- A free uptime check with GitHub Actions that opens (and closes) an issue for you
How do you keep track of certificates across subdomains? And has auto-renew ever "worked" for you while one server kept serving the old certificate?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.