Automate SSL Certificate Expiry Checks With Python (Before Your Site Breaks)
An expired SSL certificate is one of the most embarrassing outages in tech — and it happens to huge companies regularly. Browsers flash scary warnings, visitors bounce, and the fix is usually a five-minute renewal that someone forgot. The real fix is not remembering harder. It is a script that remembers for you.
How Certificate Expiry Checking Works
When your browser connects over HTTPS, the server presents a certificate containing an expiry date. Our script will do the same thing programmatically: open a TLS connection to a domain, read the certificate, and compare its expiry date to today. No requests to shady third-party APIs needed — just Python’s standard library.
The Code
import sslimport socketfrom datetime import datetime, timezonedef check_cert(domain, port=443, warn_days=30): """Return (days_left, expiry_date) for a domain's TLS certificate.""" context = ssl.create_default_context() with socket.create_connection((domain, port), timeout=10) as sock: with context.wrap_socket(sock, server_hostname=domain) as tls: cert = tls.getpeercert() # expiry is like 'Jan 15 12:00:00 2027 GMT' expiry = datetime.strptime( cert["notAfter"], "%b %d %H:%M:%S %Y %Z" ).replace(tzinfo=timezone.utc) days_left = (expiry - datetime.now(timezone.utc)).days status = "OK" if days_left < 0: status = "EXPIRED!" elif days_left <= warn_days: status = "WARNING" return days_left, expiry.date(), statusif __name__ == "__main__": domains = ["example.com", "your-site.com", "blog.example.com"] for domain in domains: try: days, expiry, status = check_cert(domain) print(f"{domain}: {status} — expires {expiry} ({days} days left)") except Exception as e: print(f"{domain}: CHECK FAILED — {e}")
How It Works
- ssl.create_default_context() builds a secure TLS configuration with normal certificate verification.
- The socket handshake connects to port 443 and performs the TLS handshake, exactly like a browser would.
- getpeercert() returns the certificate fields, including notAfter — the expiry date.
- The math is simple date subtraction: days remaining until expiry, compared against your warning threshold.
Running It on a Schedule
Save the script as sslcheck.py and add your real domains to the list. Then automate it with cron (we covered cron jobs in today’s Linux post):
0 8 * * 1 /usr/bin/python3 /home/user/sslcheck.py >> /home/user/sslcheck.log 2>&1
That runs every Monday at 8 AM. Check the log weekly, or extend the script to email you when a certificate drops below 14 days — the smtplib module makes that a short addition.
Why This Is a Security Tool, Not Just an Uptime Tool
Expired certificates do more than break your site: they train your users to click through browser warnings, which is exactly the habit phishing attacks rely on. And an attacker watching for lapses can time a lookalike-domain attack for the window when your real site shows warnings. Keeping certificates fresh is a small habit that protects trust, not just uptime.
Level Up
- Check the whole certificate chain, not just the leaf certificate.
- Alert on weak signature algorithms or certificates valid for unusually long periods.
- Monitor certificates for domains you do not own but depend on — your payment provider, your CDN, your API suppliers.
Five minutes of scripting today saves you from the outage that always seems to happen on a holiday weekend.



Comments
Post a Comment