Check TLS Certificate Expiry Across Your Domains in One Script

You run a homelab. You've got OPNsense on the router, Graylog eating logs off three servers, a Pi pushing GPS data from your car, and probably four or five self-signed certificates you generated back in March and forgot about. The problem isn't generating them. The problem is knowing which one expires next Tuesday so your monitoring dashboard doesn't go dark at 2 AM while you're asleep.

This script checks the TLS certificate on a list of domains and prints how many days are left before each one lapses. It talks to the actual port, does a real TLS handshake, reads the notAfter field, and gives you a number. No API calls to some third-party service that might rate-limit you or go offline, no browser plugin, no "certificate transparency log" nonsense. Just a socket connection and a date comparison. If the machine is down, you find out. If the cert is expired, you find out. That's the whole job.

Verified terminal output of check_tls.py — real test runs in a clean, network-isolated container.

How it works

The core logic lives in a single function called check. It takes a domain, an optional port (defaults to 443), and an optional CA bundle file. Here's the sequence:

  1. It builds an ssl.SSLContext using create_default_context. Verification stays ON by design. You need the handshake to succeed so the certificate is actually parsed and getpeercert() returns the fields you need. If you pass a --ca-file, that PEM gets added as a trust anchor, which is how you handle your own self-signed CAs without disabling verification entirely. The chain still has to validate against something.

  2. check_hostname is set to False. This is deliberate. In a homelab, your cert's Common Name might be nas.internal but you're checking it via 192.168.1.10 or a different alias on the DNS rebinder. The hostname check would fail before you ever get to read the expiry. You're not skipping verification of the chain; you're just not enforcing that the name in the cert matches what you typed on the command line.

  3. It opens a TCP socket with a 5-second timeout, wraps it in the SSL context using server_hostname=domain (which still triggers SNI so virtual-hosted certs resolve correctly), and calls getpeercert(). The 5-second timeout matters if you're checking a domain that points to a machine behind NAT that isn't forwarding that port — you don't want the script to hang for two minutes on a dead endpoint.

  4. The notAfter string comes back in the format %b %d %H:%M:%S %Y %Z — e.g., Sep 15 08:30:00 2025 GMT. It parses that, stamps both dates with UTC, and subtracts. The result is an integer day count. Python's timedelta.days truncates toward zero, so a cert that expires in 7 days and 23 hours still reports as 7d, which is what you want for a threshold check.

  5. Thresholds: more than 30 days is OK, 7 to 30 is WARN, anything under 7 (or negative) is ERROR. The output line is fixed-width so you can pipe it into column -t or grep for a status without regex gymnastics.

The main function handles argument parsing. You pass domains as positional args, or point -f at a text file with one domain per line, or both. If the file has spaces in its name (like /tmp/testdata/my list (v2).txt), that works fine — Python's open() doesn't care about whitespace in paths. Blank lines in the file are skipped silently.

The script

#!/usr/bin/env python3
import sys, ssl, socket, argparse, datetime

def check(domain, port=443, cafile=None):
    try:
        # Verification stays ON (so the cert is actually parsed and the
        # expiry is readable); --ca-file adds a trust anchor for your own
        # self-signed CAs. Hostname match is skipped because homelab certs
        # often carry a CN that differs from the name you check with.
        ctx = ssl.create_default_context(cafile=cafile)
        ctx.check_hostname = False
        with socket.create_connection((domain, port), timeout=5) as s:
            with ctx.wrap_socket(s, server_hostname=domain) as w:
                cert = w.getpeercert()
                exp = datetime.datetime.strptime(
                    cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
        now = datetime.datetime.now(datetime.timezone.utc)
        days = (exp.replace(tzinfo=datetime.timezone.utc) - now).days
    except Exception as e:
        return f"ERROR  {domain:<30} {e}"
    status = "OK" if days > 30 else ("WARN" if days >= 7 else "ERROR")
    return f"{status:<6} {domain:<30} {days:>4}d remaining"

def main():
    p = argparse.ArgumentParser(description="Check TLS cert expiry for domains")
    p.add_argument("domains", nargs="*", help="Domains to check")
    p.add_argument("-f", "--file", help="File with one domain per line")
    p.add_argument("-p", "--port", type=int, default=443)
    p.add_argument("--ca-file", dest="cafile",
                   help="PEM file of extra trusted CAs (self-signed homelab certs)")
    a = p.parse_args()
    domains = list(a.domains)
    if a.file:
        try:
            domains += [l.strip() for l in open(a.file) if l.strip()]
        except OSError as e:
            sys.exit(f"ERROR: cannot read {a.file}: {e}")
    if not domains:
        sys.exit("ERROR: no domains specified (use args or -f FILE)")
    for d in domains:
        print(check(d, a.port, a.cafile))

main()

Verification

I ran this in a clean Ubuntu container with self-signed certs generated at specific expiry intervals. All seven test cases passed on the first run. Here's what each one confirmed:

A cert with 89 days remaining returns the expected status:

OK     localhost                        89d remaining

A cert 13 days out correctly escalates to a warning:

WARN   localhost                        13d remaining

An already-expired certificate gets caught by the SSL layer before we ever reach the date math. The script surfaces the raw error rather than trying to parse a negative day count from a cert that the OS already rejected:

ERROR  localhost                      [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1081)

A port with nothing listening produces a connection-refused error, which is caught by the same broad except and printed cleanly instead of dumping a traceback:

ERROR  localhost                      [Errno 111] Connection refused

Passing an empty file or no arguments at all exits with a clear message instead of silently doing nothing:

ERROR: no domains specified (use args or -f FILE)

Finally, a file whose path contains spaces and parentheses (/tmp/testdata/my list (v2).txt) was read without issue, and both lines in it resolved to the correct status.

How to use it

Save the script as check_tls.py, make it executable, and run it against whatever domains you need to track:

# Single domain on default port 443
python3 check_tls.py nas.internal

# Multiple domains, custom port, with your self-signed CA bundle
python3 check_tls.py graylog.local pi-auto.local --ca-file /etc/ssl/homelab-ca.pem -p 8443

# Batch check from a file (one domain per line)
python3 check_tls.py -f /home/luk/.config/tls-check/domains.txt --ca-file /etc/ssl/homelab-ca.pem

Drop it in a cron job or a systemd timer if you want a daily email. Pipe the output through grep WARN and you only hear about the certs that are actually getting close. No dashboard required.


Luke Keam
Spot a bug or want a custom utility built? I'd love to hear from you. Get in touch
Luke Keam | techgeek.biz