⏰
blog.cat.ssl

A script to monitor SSL expiry automatically: Bash and Python examples

21.11.2026
← All articles

Let's Encrypt certificates renew automatically, but automatic does not mean unbreakable. Renewal can stop after a DNS change, a new firewall rule, a full disk, or a web server that never reloaded the new certificate. Commercial certificates renew by hand and are easy to forget after a year. A small daily script that checks every domain prevents the "your site is unsafe" message from reaching customers first.

What the script should check

Check the certificate the server actually serves, not the file on disk; a new file means nothing if the web server still presents the old one. The script connects on port 443, reads the expiry date and counts the days left. Since Let's Encrypt usually renews about 30 days before expiry, 14 days left signals a broken renewal; for yearly commercial certificates use 30 days.

Bash version

Imagine a small Tashkent web studio watching dozens of client sites: a cafe, a private clinic, an online shop. timeout keeps a hung server from blocking the run, and date -d is GNU-specific, so it works on Linux but not on stock macOS.

#!/usr/bin/env bash
# /usr/local/bin/ssl-check.sh
DOMAINS="example.uz www.example.uz shop.misol.uz"
WARN_DAYS=14
ALERTS=""

for d in $DOMAINS; do
  end=$(echo | timeout 15 openssl s_client -connect "$d:443" -servername "$d" 2>/dev/null \
        | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)
  if [ -z "$end" ]; then
    ALERTS+="$d: ERROR (no certificate)"$'\n'
    continue
  fi
  days=$(( ( $(date -d "$end" +%s) - $(date +%s) ) / 86400 ))
  if [ "$days" -lt "$WARN_DAYS" ]; then
    ALERTS+="$d: $days days left"$'\n'
  fi
done

if [ -n "$ALERTS" ]; then
  printf '%s' "$ALERTS"
  exit 1
fi
echo "All certificates OK"

The script exits with 1 when it finds a problem and 0 otherwise, which makes it easy to plug into other monitoring tools.

sudo chmod +x /usr/local/bin/ssl-check.sh
/usr/local/bin/ssl-check.sh; echo "exit code: $?"

Telegram alerts

Nobody reads logs daily, so send a message. Create a bot with BotFather, get the token and your chat ID, and keep them in a root-only file rather than in the script. Alert only on problems; daily "all good" messages quickly get ignored.

# /etc/ssl-check.env  (chmod 600)
TG_TOKEN="your-bot-token"
TG_CHAT="chat-id"

# at the end of ssl-check.sh, before exit 1:
source /etc/ssl-check.env
curl -s -X POST "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \
  -d chat_id="${TG_CHAT}" \
  --data-urlencode text="SSL monitoring:
$ALERTS" > /dev/null

Run it daily with cron

Once a day is plenty, since expiry is measured in days.

crontab -e

# every day at 09:00
0 9 * * * /usr/local/bin/ssl-check.sh >> /var/log/ssl-check.log 2>&1

Python version

The standard library is enough. ssl.create_default_context() fully validates the chain, hostname and dates, so an expired or broken certificate raises an error that the script reports as ERROR. That is a feature: visitors would fail in exactly the same way.

#!/usr/bin/env python3
import socket, ssl, time

DOMAINS = ["example.uz", "www.example.uz", "shop.misol.uz"]
WARN_DAYS = 14

def days_left(host):
    ctx = ssl.create_default_context()
    with socket.create_connection((host, 443), timeout=10) as sock:
        with ctx.wrap_socket(sock, server_hostname=host) as tls:
            cert = tls.getpeercert()
    expires = ssl.cert_time_to_seconds(cert["notAfter"])
    return int((expires - time.time()) // 86400)

for host in DOMAINS:
    try:
        d = days_left(host)
        status = "WARN" if d < WARN_DAYS else "OK"
        print(f"{status} {host}: {d} days")
    except Exception as e:
        print(f"ERROR {host}: {e}")

Details that matter

If a site has several IPs or sits behind a CDN, different locations may serve different certificates, so check each real address or watch the CDN's status page. Include www, mail and API subdomains; they often have separate certificates and get forgotten first. Test the alert path monthly by temporarily raising WARN_DAYS.

Hosting vs VPS

On sayt.uz hosting the panel renews Let's Encrypt certificates automatically, so the script is an extra safety net. On a VPS you manage certificates yourself and monitoring is close to mandatory. Run the script from a different machine than the one being checked, so you still hear about it if the main server goes down completely.

Related articles

📧 SSL for mail.domain.uz: Fixing the Outlook Certificate Warning ⏳ Let's Encrypt Rate Limits: Fixing "too many certificates" 📜 Certificate Transparency: How Public Logs of SSL Certificates Work 🏢 SSL for internal (intranet) sites: how to secure office systems
🌐 Language
🇺🇿 O⁠'zbek 🇺🇿 Özbek (yangi) 🇺🇿 Ўзбек 🇷🇺 Русский 🇬🇧 English ✓