Monitor Website Uptime with Python
Periodically check if a website is reachable and its HTTP status is 200, logging the status with timestamps.
pip install requests
Python code
32 linesimport requests
import time
def check_website(url):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.ConnectionError:
return False
except requests.Timeout:
return False
def monitor_uptime(url, interval=60):
while True:
if check_website(url):
print(f"{url} is UP - {time.ctime()}")
else:
print(f"{url} is DOWN - {time.ctime()}")
time.sleep(interval)
if __name__ == "__main__":
website = "https://httpbin.org/status/200"
# Run for 3 checks only for demo
for _ in range(3):
if check_website(website):
print(f"{website} is UP - {time.ctime()}")
else:
print(f"{website} is DOWN - {time.ctime()}")
time.sleep(2)
Output
https://httpbin.org/status/200 is UP - Mon Jan 15 12:00:05 2024
https://httpbin.org/status/200 is UP - Mon Jan 15 12:00:07 2024
https://httpbin.org/status/200 is UP - Mon Jan 15 12:00:09 2024
How it works
The check_website() function wraps a GET request in a try/except to catch connection errors and timeouts, returning True only when a 200 status is received. monitor_uptime() runs an infinite loop calling this checker at a fixed interval (default 60 seconds). The demo loop at the bottom mimics this behavior for three iterations with a 2-second pause. HTTP status codes other than 200 (e.g., 404, 500) are treated as downtime, which is reasonable for basic uptime monitoring.
Common mistakes
- Forgetting to handle `requests.Timeout`, causing the script to hang indefinitely if the server is slow.
- Assuming any successful response (not just 200) means uptime, ignoring 3xx redirects or 4xx client errors.
- Using too short an interval that overwhelms the target server or your own network.
Variations
- Use `requests.head()` instead of `get()` for a lighter check that doesn't download the page body.
- Replace `time.sleep()` with `schedule` library for more flexible cron-like scheduling.
Real-world use cases
- Running a background script on a Raspberry Pi to alert when your personal blog goes offline.
- Integrating with a monitoring dashboard that plots uptime percentages over weeks.
- Triggering automated failover to a backup server when primary endpoint returns non-200 status.
Sponsored
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
Keep learning
Related tutorials and quizzes for this topic.