Building a Robust Website Monitoring System with Python: Real-Time Uptime and SSL Expiry Alerts

Building a Robust Website Monitoring System with Python: Real-Time Uptime and SSL Expiry Alerts

Ensuring your website remains online and secure is crucial for business operations and user experience. In this post, we’ll walk through building a Python-based website monitoring system that continuously checks site availability, handles API authentication, and sends real-time notifications via webhooks.

This system will help you:
● Monitor website uptime
● Check SSL certificate expiration
● Send instant alerts via webhook
● Log errors for debugging
Let’s dive into building this monitoring system step by step.

1. Setting Up the Monitoring System
We’ll use Python’s built-in libraries like requests, socket, and ssl along with yaml for
configuration.

Installing Dependencies
Ensure you have the required dependencies installed:

pip install requests pyyaml

Configuring the Monitor

Create a YAML configuration file (config.yml) to store the website URLs and webhook
settings.

websites:
– url: “https://example.com”
retries: 3

timeout: 5
– url: “https://api.example.com”
retries: 2
timeout: 5
webhook:
url: “https://your-webhook-url.com”
ssl_check:
enabled: true
alert_days: 7

This allows easy modification of monitoring parameters.

2. Writing the Website Monitoring Script

The script will:
✅ Ping the websites at regular intervals
✅ Retry failed requests
✅ Log errors
and send alerts via webhook

Checking Website Uptime
We use requests to check website availability.

import requests

import yaml
import time
def load_config():
with open("config.yml", "r") as file:
return yaml.safe_load(file)
def check_website(url, retries, timeout):
for _ in range(retries):
try:
response = requests.get(url, timeout=timeout)
if response.status_code == 200:
print(f"✅ {url} is UP")
return True
else:
print(f"⚠️ {url} returned status {response.status_code}")
except requests.exceptions.RequestException as e:

print(f"❌ Error connecting to {url}: {e}")
time.sleep(1)
return False
def monitor_websites(config):
for site in config["websites"]:
check_website(site["url"], site["retries"], site["timeout"])
config = load_config()
monitor_websites(config)

This script loads the configuration and checks each website’s status, logging any failures.

3. Checking SSL Certificate Expiry

SSL certificates expire and need renewal. Let’s add a check to notify us before expiration.
import ssl
import socket
from datetime import datetime

def get_ssl_expiry_date(hostname):
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
expiry_date = datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y GMT")
return expiry_date
def check_ssl_certificates(config):
if not config.get("ssl_check", {}).get("enabled", False):
return
alert_days = config["ssl_check"].get("alert_days", 7)
for site in config["websites"]:
hostname = site["url"].replace("https://", "").replace("http://", "").split("/")[0]
try:
expiry_date = get_ssl_expiry_date(hostname)
days_left = (expiry_date - datetime.utcnow()).days
print(f" {hostname} SSL expires in {days_left} days")
if days_left <= alert_days:
send_webhook_alert(f"⚠️ SSL for {hostname} expires in {days_left} days!")
except Exception as e:
print(f"❌ Failed to check SSL for {hostname}: {e}")

This function extracts the SSL certificate expiration date and checks if it’s close to expiring.

4. Sending Alerts via Webhook

If a website is down or an SSL certificate is expiring soon, we send a webhook alert.

def send_webhook_alert(message):
webhook_url = config["webhook"]["url"]
payload = {"text": message}
try:
requests.post(webhook_url, json=payload)
print("✅ Webhook alert sent")
except requests.exceptions.RequestException as e:
print(f"❌ Failed to send webhook alert: {e}")

5. Automating the Monitoring Process
We wrap everything in a continuous monitoring loop.

def run_monitoring():
config = load_config()
while True:
print(" Running website and SSL checks...")
monitor_websites(config)
check_ssl_certificates(config)
time.sleep(60) # Run every 60 seconds
if __name__ == "__main__":
run_monitoring()

This script will run indefinitely, checking websites and SSL certificates every 60 seconds.

Conclusion
With this Python-based monitoring system, you can:
✅ Track website uptime and performance
✅ Get notified if SSL certificates are expiring
✅ Send real-time webhook alerts for downtime

This solution is easy to extend—consider adding database logging or integrating with services
like Slack or Telegram for alerts.

Leave a Reply