Introduction
An expired domain or SSL certificate can take a client’s website offline for days. Automated expiry tracking alerts you before it happens — giving you time to renew and prevent downtime.
This post builds a complete domain/SSL monitoring system.
Step 1: Check domain expiry
import whois
from datetime import datetime
def check_domain_expiry(domain):
"""Check domain expiry date using WHOIS."""
try:
w = whois.whois(domain)
expiry = w.expiration_date
# Handle list (some registrars return multiple dates)
if isinstance(expiry, list):
expiry = expiry[0]
if isinstance(expiry, str):
expiry = datetime.strptime(expiry, "%Y-%m-%d")
days_left = (expiry - datetime.now()).days
return {
"domain": domain,
"expiry_date": expiry.strftime("%Y-%m-%d"),
"days_left": days_left,
"status": "OK" if days_left > 30 else "WARNING" if days_left > 7 else "CRITICAL",
}
except Exception as e:
return {"domain": domain, "error": str(e)}
# Usage
result = check_domain_expiry("techwithgalvan.in")
print(result)
# {'domain': 'techwithgalvan.in', 'expiry_date': '2027-03-15', 'days_left': 250, 'status': 'OK'}
Step 2: Check SSL certificate expiry
import ssl, socket
from datetime import datetime
def check_ssl_expiry(domain):
"""Check SSL certificate expiry date."""
try:
context = ssl.create_default_context()
with socket.create_connection((domain, 443), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=domain) as ssock:
cert = ssock.getpeercert()
expiry = datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
days_left = (expiry - datetime.now()).days
return {
"domain": domain,
"expiry_date": expiry.strftime("%Y-%m-%d"),
"days_left": days_left,
"status": "OK" if days_left > 30 else "WARNING" if days_left > 7 else "CRITICAL",
}
except Exception as e:
return {"domain": domain, "error": str(e)}
# Usage
result = check_ssl_expiry("techwithgalvan.in")
print(result)
Step 3: Monitor multiple domains
import json
def monitor_domains(domains):
"""Check expiry for multiple domains."""
results = []
for domain in domains:
domain_info = check_domain_expiry(domain)
ssl_info = check_ssl_expiry(domain)
results.append({
"domain": domain,
"domain_expiry": domain_info.get("expiry_date"),
"domain_days": domain_info.get("days_left"),
"domain_status": domain_info.get("status"),
"ssl_expiry": ssl_info.get("expiry_date"),
"ssl_days": ssl_info.get("days_left"),
"ssl_status": ssl_info.get("status"),
})
return results
domains = [
"techwithgalvan.in",
"example.com",
"client1.com",
"client2.com",
]
results = monitor_domains(domains)
for r in results:
print(f"{r['domain']}: Domain={r['domain_status']} ({r['domain_days']}d), SSL={r['ssl_status']} ({r['ssl_days']}d)")
Step 4: Send alerts
import resend, os
resend.api_key = os.environ["RESEND_API_KEY"]
def send_expiry_alert(domain, alert_type, days_left, expiry_date):
"""Send alert for expiring domain or SSL."""
subject = f"⚠️ {alert_type} expiring soon: {domain}"
body = f"""
<h3>{alert_type} Expiry Alert</h3>
<p><strong>Domain:</strong> {domain}</p>
<p><strong>{alert_type} expiry:</strong> {expiry_date}</p>
<p><strong>Days remaining:</strong> {days_left}</p>
<p>Please renew before expiry to avoid downtime.</p>
"""
resend.Emails.send({
"from": "Alerts <[email protected]>",
"to": ["[email protected]"],
"subject": subject,
"html": body,
})
def check_and_alert(domains):
"""Check all domains and send alerts for expiring ones."""
results = monitor_domains(domains)
for r in results:
# Alert at 30, 14, 7, and 1 days
for alert_type, days_key, expiry_key in [("Domain", "domain_days", "domain_expiry"), ("SSL", "ssl_days", "ssl_expiry")]:
days = r[days_key]
if days in (30, 14, 7, 1) or days < 0:
send_expiry_alert(r["domain"], alert_type, days, r[expiry_key])
print(f"ALERT sent: {r['domain']} {alert_type} expires in {days} days")
Step 5: Store tracking data
import sqlite3
def init_db():
conn = sqlite3.connect("domain_tracker.db")
conn.execute("""
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT UNIQUE,
domain_expiry TEXT,
ssl_expiry TEXT,
last_checked TEXT,
auto_renew BOOLEAN DEFAULT 0,
notes TEXT
)
""")
conn.commit()
conn.close()
def save_results(results):
conn = sqlite3.connect("domain_tracker.db")
for r in results:
conn.execute("""
INSERT OR REPLACE INTO domains (domain, domain_expiry, ssl_expiry, last_checked)
VALUES (?, ?, ?, ?)
""", (r["domain"], r["domain_expiry"], r["ssl_expiry"], datetime.now().isoformat()))
conn.commit()
conn.close()
Step 6: Automate with cron
# Check daily at 9 AM
0 9 * * * cd /path/to/project && python domain_tracker.py
Or GitHub Actions:
name: Domain & SSL Check
on:
schedule:
- cron: '0 9 * * *'
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install python-whois
- run: python domain_tracker.py
Step 7: Dashboard (Streamlit)
import streamlit as st
import pandas as pd
import sqlite3
st.title("🔍 Domain & SSL Monitor")
conn = sqlite3.connect("domain_tracker.db")
df = pd.read_sql("SELECT * FROM domains", conn)
# Status indicators
for _, row in df.iterrows():
domain_days = (pd.to_datetime(row["domain_expiry"]) - pd.Timestamp.now()).days
ssl_days = (pd.to_datetime(row["ssl_expiry"]) - pd.Timestamp.now()).days
col1, col2, col3 = st.columns(3)
col1.write(f"**{row['domain']}**")
col2.metric("Domain", f"{domain_days} days", delta="OK" if domain_days > 30 else "WARNING")
col3.metric("SSL", f"{ssl_days} days", delta="OK" if ssl_days > 30 else "WARNING")
st.dataframe(df, use_container_width=True)
Common mistakes
- Not enabling auto-renew — the most common cause of expired domains
- Expired payment method — auto-renew fails silently if the card is expired
- Not checking SSL — SSL certificates expire too (usually annually)
- Ignoring alerts — alerts are useless if you don’t act on them
- No backup DNS — if your DNS provider goes down, your site is offline even if the domain is active
- Not tracking client domains — you’re responsible for client domains too
Key Concepts
- WHOIS = protocol for querying domain registration info
- SSL certificate = security certificate for HTTPS
- Auto-renew = automatic renewal (prevents expiry)
- Cron job = scheduled task that runs automatically
- Alert threshold = days before expiry to trigger alert (30, 14, 7, 1)
What to Try Next
- Track domains and hosting for all clients
- Organise client projects with a system
- Write SOPs for domain management
- Build a monitoring dashboard in Streamlit
FAQ
How often should I check domain/SSL expiry?
Daily (automated). Manual checks weekly. The automated script runs daily and alerts you at 30, 14, 7, and 1 days before expiry.
What if a domain has already expired?
Act fast — you have a 30-day grace period to renew at normal price. After that, it enters redemption (higher price). After 60 days, anyone can buy it. Contact your registrar immediately.
Can I monitor competitor domains?
Yes — the script works for any domain. But don’t use it for malicious purposes. Monitoring competitor domains for research is fine; buying their expired domains to redirect traffic is unethical.
What’s the difference between domain expiry and hosting expiry?
Domain expiry = your domain name registration expires (you lose the URL). Hosting expiry = your web hosting plan expires (your site goes offline but you keep the domain). Both need monitoring. See Track Domains and Hosting.