A reliable ssl certificate expiry monitor script is the simplest insurance policy against sudden HTTPS outages when automated ACME renewals silently fail. Even when Let’s Encrypt or ZeroSSL cron jobs are configured, DNS propagation hiccups, Nginx reload errors, Cloudflare proxy mismatches, or full disk partitions can leave production endpoints serving an expiring TLS certificate. Worse, if you manage dozens of subdomains, API gateways, or internal staging hosts, checking dates manually in a browser does not scale. Built for Linux, macOS, and CI runners using Python 3.10+, the script below opens direct TLS handshakes via Python’s standard library, inspects X.509 notAfter timestamps concurrently, supports custom ports and SNI hostnames, includes a safe --dry-run and --json output mode, and dispatches tiered warning and critical alerts to Slack or Discord webhooks. You can copy, configure, and schedule it in minutes.
Key Takeaways & Script Specs
- Runtime & Dependencies: Python 3.10+ (standard library
ssl,socket,concurrent.futures) plus optionalrequestsfor webhook alerts. - Target Environments: Public HTTPS domains, custom TLS ports (443, 8443, 465), and private VPC endpoints.
- Execution Time: Checks 50+ domains in under 1.5 seconds using parallel worker threads.
- Safety Controls: Configurable
--warn-days(default 21) and--crit-days(default 7) thresholds, strict socket timeouts,--dry-runmode, and non-zero CI exit codes on critical findings.
Table of Contents
Why Automated TLS Renewals Still Fail Silently in 2027
Most teams assume that installing Certbot, Caddy, or a Kubernetes cert-manager controller eliminates expired-certificate outages forever. In practice, renewal pipelines break in subtle ways that never trigger a process crash. A firewall rule update blocks port 80 HTTP-01 challenges, an expired API token breaks DNS-01 TXT record updates, or a reverse proxy fails to reload its worker processes after writing the new fullchain.pem to disk. Because the old certificate remains valid for weeks after the first failed renewal attempt, nobody notices until the exact minute it expires.
Monitoring the certificate directly over a live TCP/TLS handshake—rather than checking local PEM files on disk—verifies what real clients actually receive at the edge. By using Python’s built-in ssl TLS/SSL socket wrapper documentation, your monitor validates both the active certificate chain and the exact expiration timestamp presented by your load balancer or CDN.
Architecture and Parallel Execution Flow
Checking endpoints sequentially works for three domains, but a single hung firewall or blackholed IP with a 5-second timeout stalls the entire run when you monitor 40 or 100 hosts. To keep daily sweeps fast and predictable, our script dispatches TLS handshakes across a bounded pool using Python’s concurrent.futures ThreadPoolExecutor.
+-------------------------------------------------------------------+
| 1. Load Targets (CLI args + domains.txt, supporting host:port) |
|---|+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 2. Fan Out Parallel TLS Handshakes (ThreadPoolExecutor) |
| - socket.create_connection(host, port, timeout=5) |
| - ssl.create_default_context().wrap_socket(server_hostname) |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 3. Parse X.509 'notAfter' & Compute UTC Days Remaining |
| - <= crit_days (7d) -> CRITICAL (exit code 2) |
| - <= warn_days (21d) -> WARNING (exit code 1) |
| - Connection/TLS err -> ERROR (exit code 2) |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 4. Output Table or --json + Dispatch Webhook (unless --dry-run) |
+-------------------------------------------------------------------+
Notice that the script returns distinct exit codes: 0 when all certificates are healthy, 1 when warnings exist, and 2 when any certificate is expired, critical, or unreachable. That makes it drop-in compatible with both local systemd timers and automated GitHub Actions CI/CD pipelines, alongside your existing Docker health check script.
Comparing SSL Monitoring Approaches in 2027
Before deploying a custom monitor, compare how the four common SSL tracking methods stack up on cost, private-network visibility, and alerting flexibility.
| Monitoring Method | Private / VPC Endpoints | Parallel Speed | CI/CD Exit Codes | Monthly Cost |
|---|---|---|---|---|
| SaaS Uptime Platforms | No (requires paid agents) | Fast (cloud probes) | API polling needed | $10–$50+ / month |
One-Line openssl s_client Bash | Yes | Sequential (slow) | Manual parsing | Free |
| Certbot Dry-Run Only | Local host only | N/A (renewal check) | Limited | Free |
| Python Concurrent SSL Monitor | Yes (runs anywhere) | Fast (ThreadPool) | Native (0 / 1 / 2) | Free |
A self-hosted Python script gives you full visibility into internal staging subdomains, database TLS listeners, and public edge domains without paying per-monitor SaaS fees. You can pair it with automated Linux server backups and free developer CLI tools for a complete zero-cost observability baseline.
Prerequisites and Environment Setup
Because modern Linux distributions enforce PEP 668 against system-wide pip installs, create a clean virtual environment for the script. If you only need terminal or JSON output without webhook alerts, the script runs with zero third-party packages; installing requests enables Slack and Discord webhook delivery.
sudo mkdir -p /opt/ssl-expiry-monitor
sudo chown "$USER":"$USER" /opt/ssl-expiry-monitor
cd /opt/ssl-expiry-monitor
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install "requests>=2.32.0,<3.0.0"
Next, create a target list at /opt/ssl-expiry-monitor/domains.txt. Each line accepts a bare hostname (defaulting to port 443) or hostname:port, and ignores blank lines and # comments:
# Public production endpoints
myscrpts.com
api.example.com
# Custom TLS port example
mail.example.com:465
Complete Production Python SSL Expiry Monitor Script
Save the following script as /opt/ssl-expiry-monitor/ssl_expiry_monitor.py. It uses Python’s argparse CLI module, validates X.509 chains with ssl.create_default_context(), parses RFC-formatted notAfter dates in UTC, and formats clean terminal tables, machine-readable JSON, and webhook payloads.
#!/usr/bin/env python3
"""
Production SSL Certificate Expiry Monitor (2027)
Performs parallel TLS handshakes, computes UTC days remaining, outputs
human-readable tables or JSON, and dispatches Slack/Discord webhook alerts.
"""
import argparse
import concurrent.futures
import json
import logging
import os
import socket
import ssl
import sys
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional, Tuple
try:
import requests
except ImportError:
requests = None
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("ssl_expiry_monitor")
@dataclass
class CertResult:
target: str
host: str
port: int
status: str # OK, WARNING, CRITICAL, ERROR
days_remaining: Optional[int]
expires_utc: Optional[str]
issuer: Optional[str]
error: Optional[str] = None
def parse_target(raw_target: str) -> Tuple[str, int]:
"""Parse 'example.com' or 'example.com:8443' into (host, port)."""
cleaned = raw_target.strip()
if cleaned.startswith("https://"):
cleaned = cleaned[8:]
elif cleaned.startswith("http://"):
cleaned = cleaned[7:]
cleaned = cleaned.split("/", 1)[0]
if ":" in cleaned:
host, port_str = cleaned.rsplit(":", 1)
return host, int(port_str)
return cleaned, 443
def load_targets(cli_domains: List[str], domains_file: Optional[str]) -> List[str]:
"""Combine CLI domain arguments with lines from --domains-file."""
targets: List[str] = list(cli_domains)
if domains_file:
path = Path(domains_file)
if not path.is_file():
raise FileNotFoundError(f"Domains file not found: {domains_file}")
for line in path.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if stripped and not stripped.startswith("#"):
targets.append(stripped)
# Deduplicate while preserving order
seen = set()
unique_targets = []
for item in targets:
if item not in seen:
seen.add(item)
unique_targets.append(item)
return unique_targets
def inspect_certificate(
raw_target: str,
timeout: float,
warn_days: int,
crit_days: int,
) -> CertResult:
"""Connect to host:port over TLS and inspect the leaf X.509 certificate."""
try:
host, port = parse_target(raw_target)
except ValueError as exc:
return CertResult(
target=raw_target,
host=raw_target,
port=443,
status="ERROR",
days_remaining=None,
expires_utc=None,
issuer=None,
error=f"Invalid target format: {exc}",
)
context = ssl.create_default_context()
try:
with socket.create_connection((host, port), timeout=timeout) as sock:
with context.wrap_socket(sock, server_hostname=host) as tls_sock:
cert = tls_sock.getpeercert()
except (socket.timeout, TimeoutError):
return CertResult(
target=raw_target,
host=host,
port=port,
status="ERROR",
days_remaining=None,
expires_utc=None,
issuer=None,
error=f"Connection timed out after {timeout}s",
)
except (ssl.SSLError, OSError) as exc:
return CertResult(
target=raw_target,
host=host,
port=port,
status="ERROR",
days_remaining=None,
expires_utc=None,
issuer=None,
error=str(exc),
)
not_after_raw = cert.get("notAfter")
if not not_after_raw:
return CertResult(
target=raw_target,
host=host,
port=port,
status="ERROR",
days_remaining=None,
expires_utc=None,
issuer=None,
error="Certificate missing notAfter field",
)
expires_dt = datetime.strptime(not_after_raw, "%b %d %H:%M:%S %Y %Z").replace(
tzinfo=timezone.utc
)
now_utc = datetime.now(timezone.utc)
days_remaining = int((expires_dt - now_utc).total_seconds() // 86400)
issuer_parts = dict(x[0] for x in cert.get("issuer", ()))
issuer_name = issuer_parts.get("organizationName") or issuer_parts.get("commonName")
if days_remaining <= crit_days:
status = "CRITICAL"
elif days_remaining <= warn_days:
status = "WARNING"
else:
status = "OK"
return CertResult(
target=raw_target,
host=host,
port=port,
status=status,
days_remaining=days_remaining,
expires_utc=expires_dt.strftime("%Y-%m-%d %H:%M:%SZ"),
issuer=issuer_name,
)
def send_webhook_alert(webhook_url: str, alerts: List[CertResult], dry_run: bool) -> None:
"""Post a consolidated alert summary to Slack or Discord."""
if not alerts:
return
lines = ["*[SSL Expiry Monitor Alert]*"]
for item in alerts:
if item.status == "ERROR":
lines.append(f"- `{item.host}:{item.port}` | ERROR: {item.error}")
else:
lines.append(
f"- `{item.host}:{item.port}` | {item.status}: "
f"{item.days_remaining}d remaining (expires {item.expires_utc})"
)
message = "\n".join(lines)
if dry_run:
logger.info("[DRY-RUN] Would send webhook alert:\n%s", message)
return
if requests is None:
logger.error("Install 'requests' to enable webhook delivery: pip install requests")
return
payload = {"text": message, "content": message}
try:
resp = requests.post(webhook_url, json=payload, timeout=5)
resp.raise_for_status()
logger.info("Sent webhook alert for %d domain(s).", len(alerts))
except requests.RequestException as exc:
logger.error("Webhook delivery failed: %s", exc)
def print_table(results: List[CertResult]) -> None:
"""Print a clean aligned status table to stdout."""
header = f"{'STATUS':<10} {'DAYS':<6} {'EXPIRES (UTC)':<22} {'TARGET':<32} {'DETAIL'}"
print(header)
print("-" * len(header))
for r in results:
days_str = str(r.days_remaining) if r.days_remaining is not None else "-"
exp_str = r.expires_utc or "-"
detail = r.error if r.error else (r.issuer or "-")
print(f"{r.status:<10} {days_str:<6} {exp_str:<22} {r.host}:{r.port:<25} {detail}")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Monitor TLS/SSL certificate expiry across domains in parallel."
)
parser.add_argument("domains", nargs="*", help="Domain(s) or host:port targets")
parser.add_argument(
"-f", "--domains-file", help="Path to newline-delimited domains file"
)
parser.add_argument(
"--warn-days",
type=int,
default=int(os.getenv("SSL_WARN_DAYS", "21")),
help="Warning threshold in days (default: 21)",
)
parser.add_argument(
"--crit-days",
type=int,
default=int(os.getenv("SSL_CRIT_DAYS", "7")),
help="Critical threshold in days (default: 7)",
)
parser.add_argument(
"--timeout",
type=float,
default=5.0,
help="TCP/TLS socket timeout in seconds (default: 5.0)",
)
parser.add_argument(
"--workers",
type=int,
default=10,
help="Max concurrent TLS check threads (default: 10)",
)
parser.add_argument("--json", action="store_true", help="Emit JSON output")
parser.add_argument(
"--dry-run",
action="store_true",
help="Run checks and log webhook alerts without sending HTTP requests",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
try:
targets = load_targets(args.domains, args.domains_file)
except FileNotFoundError as exc:
logger.error("%s", exc)
return 2
if not targets:
logger.error("No targets provided. Pass domains as arguments or use --domains-file.")
return 2
results: List[CertResult] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = [
executor.submit(
inspect_certificate, target, args.timeout, args.warn_days, args.crit_days
)
for target in targets
]
for future in concurrent.futures.as_completed(futures):
results.append(future.result())
results.sort(key=lambda r: (r.days_remaining is None, r.days_remaining or 9999, r.host))
if args.json:
print(json.dumps([asdict(r) for r in results], indent=2))
else:
print_table(results)
alerts = [r for r in results if r.status in ("WARNING", "CRITICAL", "ERROR")]
webhook_url = os.getenv("WEBHOOK_URL")
if webhook_url and alerts:
send_webhook_alert(webhook_url, alerts, dry_run=args.dry_run)
if any(r.status in ("CRITICAL", "ERROR") for r in results):
return 2
if any(r.status == "WARNING" for r in results):
return 1
return 0
if name == "main":
sys.exit(main())
Test the script immediately with --dry-run so you can verify domain resolution, SNI handshake behavior, and threshold formatting without triggering live alerts:
chmod +x /opt/ssl-expiry-monitor/ssl_expiry_monitor.py
/opt/ssl-expiry-monitor/.venv/bin/python /opt/ssl-expiry-monitor/ssl_expiry_monitor.py \
--domains-file /opt/ssl-expiry-monitor/domains.txt --warn-days 30 --dry-run
Scheduling With GitHub Actions or a Systemd Timer
You can run this monitor either from a cloud runner using GitHub Actions scheduled cron workflows (ideal for public endpoints) or from an internal Linux host via a systemd timer (ideal for private VPC services). For GitHub Actions, create .github/workflows/ssl-monitor.yml and store your webhook in repository secrets as SSL_WEBHOOK_URL:
name: Daily SSL Expiry Check
on:
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
jobs:
check-ssl:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install requests
- name: Run SSL expiry monitor
env:
WEBHOOK_URL: ${{ secrets.SSL_WEBHOOK_URL }}
run: python ssl_expiry_monitor.py --domains-file domains.txt --warn-days 21 --crit-days 7
Notice the offset minute (17 3 * * *) rather than 0 3 * * *—scheduling off the top of the hour avoids GitHub Actions queue congestion. On a Linux VPS, pair a oneshot systemd service with a daily timer and a 0600 environment file so your webhook URL never leaks into shell history or process listings:
cat <<'EOF' > /opt/ssl-expiry-monitor/.env
WEBHOOK_URL=https://hooks.slack.com/services/REPLACE/ME/NOW
SSL_WARN_DAYS=21
SSL_CRIT_DAYS=7
EOF
chmod 600 /opt/ssl-expiry-monitor/.env
Troubleshooting and Security Hardening
When running TLS checks across mixed infrastructure, keep these three operational edge cases in mind:
- SNI Mismatches on Shared IPs: Always pass
server_hostname=hosttocontext.wrap_socket()(already built into the script). Without SNI, reverse proxies like Nginx or Cloudflare return a default fallback certificate instead of your domain’s actual cert. - Self-Signed Internal Certificates:
ssl.create_default_context()rejects untrusted or self-signed CA chains by design, returning anERRORstatus. For internal staging hosts signed by a private corporate CA, pass your internal CA bundle viaSSL_CERT_FILE=/etc/ssl/certs/internal-ca.pemrather than disabling verification. - Webhook Credential Protection: Keep
WEBHOOK_URLinside a0600.envfile or GitHub Actions encrypted secret, and always keeptimeout=5on outbound webhook calls so a slow Slack or Discord API response never stalls your CI job.
Frequently Asked Questions
Does this SSL certificate expiry monitor script require OpenSSL or third-party binaries?
No. It uses Python 3.10+ standard library modules (ssl, socket, datetime, and concurrent.futures) to inspect live X.509 certificates over TLS. The requests library is only needed if you configure a Slack or Discord WEBHOOK_URL.
Can I monitor non-standard TLS ports like 8443 or 465?
Yes. Pass targets using host:port notation either on the command line or inside domains.txt (for example, mail.example.com:465). Any target without a port defaults to 443.
How does the script handle Cloudflare or CDN-proxied domains?
Because the script completes a full TLS handshake with SNI enabled, it inspects the exact edge certificate served to your visitors by Cloudflare, Fastly, or AWS CloudFront—catching edge renewal or Universal SSL failures immediately.
What exit codes does the script return for CI/CD pipelines?
It returns 0 when all endpoints are healthy, 1 when at least one certificate enters the warning window (–warn-days), and 2 when any certificate is critical (–crit-days), expired, or unreachable.
Why use –dry-run before scheduling in cron or systemd?
Running with –dry-run executes every DNS lookup and TLS handshake, prints the full status table or JSON output, and logs the exact webhook payload to stderr without sending HTTP requests to your team channel.
How fast does it check a large list of domains?
Using ThreadPoolExecutor with 10 concurrent workers by default, the script checks 50 public HTTPS endpoints in roughly 1 to 1.5 seconds, and you can raise –workers for larger fleets.