Keeping your website online is non‑negotiable in today’s digital landscape, and an automated uptime monitor built with Python can give you peace of mind without breaking the bank. In this guide we’ll walk through why uptime monitoring matters, how to craft a reliable Python script, and how to extend it with notifications and scheduling. By the end, you’ll have a production‑ready solution that checks your site every minute, logs results, and alerts you the instant something goes wrong.
Why You Need a Python‑Based Uptime Monitor
Even the most robust hosting providers can experience brief outages, DNS hiccups, or application‑level errors. An automated website uptime monitor helps you:
- Detect downtime instantly – so you can respond before users notice.
- Gather historical availability data for SLA reporting.
- Identify patterns, such as spikes during traffic surges.
- Reduce reliance on expensive third‑party services.
Python is an ideal language for this task because of its readability, extensive libraries, and ease of deployment on any server or cloud instance.
Setting Up the Development Environment
Prerequisites
Before you start coding, make sure you have the following installed:
- Python 3.9+ (
python --version) pipfor package management- Access to a terminal or SSH session on the host where the monitor will run
Installing Required Packages
We’ll use requests for HTTP checks and schedule for simple timing. Install them with:
pip install requests schedule
Building the Core Monitoring Script
Design Goals
- Lightweight – minimal CPU and memory footprint.
- Configurable – URL, timeout, and retry count should be easy to change.
- Extensible – plug‑in support for email, Slack, or SMS alerts.
Full Python Example
Save the following as uptime_monitor.py. It checks a URL, logs the result, and optionally sends an alert.
import requests
import logging
import datetime
import smtplib
from email.mime.text import MIMEText
import schedule
import time
# -------------------- Configuration --------------------
URL = "https://example.com"
TIMEOUT = 10 # seconds
RETRY_COUNT = 3
LOG_FILE = "uptime.log"
ALERT_EMAIL = "admin@example.com"
SMTP_SERVER = "smtp.example.com"
SMTP_PORT = 587
SMTP_USER = "smtp_user"
SMTP_PASS = "smtp_password"
# -----------------------------------------------------
# Set up logging
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
def send_email(subject, body):
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = SMTP_USER
msg["To"] = ALERT_EMAIL
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(SMTP_USER, SMTP_PASS)
server.send_message(msg)
def check_site():
for attempt in range(1, RETRY_COUNT + 1):
try:
response = requests.get(URL, timeout=TIMEOUT)
if response.status_code == 200:
logging.info("✅ Site is up (status 200).")
return
else:
logging.warning(f"⚠️ Unexpected status {response.status_code}.")
except requests.RequestException as e:
logging.error(f"❌ Attempt {attempt}: {e}")
if attempt < RETRY_COUNT:
time.sleep(2) # brief pause before retry
# If we reach this point, all attempts failed
message = f"🚨 {URL} is down as of {datetime.datetime.utcnow()} UTC."
logging.critical(message)
try:
send_email("Website Down Alert", message)
except Exception as email_err:
logging.error(f"Failed to send alert email: {email_err}")
# Schedule the check every minute
schedule.every(1).minutes.do(check_site)
if __name__ == "__main__":
logging.info("🔧 Uptime monitor started.")
while True:
schedule.run_pending()
time.sleep(1)
How the Script Works
- Configuration block – adjust URL, timeout, and alert settings without touching the logic.
- Logging – all events are written to
uptime.logfor later analysis. - Retry logic – attempts the request up to
RETRY_COUNTtimes before flagging a failure. - Email alerts – uses SMTP to notify you immediately when the site is unreachable.
- Scheduling – the
schedulelibrary runscheck_site()every minute.
Adding Real‑Time Notifications
Email vs. Chat Apps
While email works everywhere, many teams prefer instant messaging platforms like Slack or Microsoft Teams. Below is a quick snippet for Slack integration using a webhook URL.
import json
import urllib.request
SLACK_WEBHOOK = "https://hooks.slack.com/services/XXX/YYY/ZZZ"
def send_slack(message):
payload = {"text": message}
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
SLACK_WEBHOOK,
data=data,
headers={"Content-Type": "application/json"}
)
urllib.request.urlopen(req)
Replace the call to send_email() in check_site() with send_slack(message) if you prefer Slack alerts.
Deploying the Monitor on a Server
Running as a Background Service
On Linux, the most reliable way to keep the script alive is to create a systemd service.
[Unit]
Description=Python Website Uptime Monitor
After=network.target
[Service]
User=your_user
WorkingDirectory=/home/your_user/monitor
ExecStart=/usr/bin/python3 /home/your_user/monitor/uptime_monitor.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Save this as /etc/systemd/system/uptime-monitor.service, then enable and start it:
sudo systemctl daemon-reload
sudo systemctl enable uptime-monitor
sudo systemctl start uptime-monitor
Using Cron as an Alternative
If you prefer not to use systemd, you can run the script via cron every minute. Add this line to crontab -e:
* * * * * /usr/bin/python3 /path/to/uptime_monitor.py >> /path/to/cron.log 2>&1
Extending the Monitor for Production Use
Key Enhancements
- Multiple URLs – store a list of endpoints in a JSON or YAML file and loop through them.
- Database storage – insert each check into SQLite or PostgreSQL for advanced reporting.
- Response time tracking – log the latency of each request and trigger alerts on slow responses.
- Dashboard integration – expose a simple Flask API that returns the latest status for Grafana or custom UI.
- Docker containerization – package the script with its dependencies for easy deployment across environments.
Sample JSON Configuration for Multiple Sites
[
{"url": "https://example.com", "name": "Main Site"},
{"url": "https://api.example.com/health", "name": "API Endpoint"},
{"url": "https://blog.example.com", "name": "Blog"}
]
Load this file at runtime, iterate over each entry, and generate a per‑site log entry. This approach scales from a single personal site to a fleet of corporate services.
SEO Tips Embedded in This Article
To help this post rank for keywords like Python automated website uptime monitor, we’ve naturally incorporated related terms such as “website monitoring script”, “Python uptime monitor”, “automated uptime check”, and “Python monitoring tutorial”. Using descriptive subheadings, bullet lists, and code examples improves readability and dwell time—both important signals for search engines.
Conclusion
Building a Python automated website uptime monitor is a straightforward yet powerful way to safeguard your online presence. By leveraging the requests library, a simple logging strategy, and optional email or Slack notifications, you gain real‑time visibility into site health without costly third‑party services. Deploy the script as a systemd service or cron job, expand it with multi‑site support, and you’ll have a scalable monitoring solution that grows with your business. Start today, stay ahead of downtime, and keep your visitors happy.
Leave a Reply