#!/usr/bin/env python3
"""
Website Uptime and Response Time Monitor
This script checks the uptime and response times of one or more websites.
It periodically pings each site via HTTP GET and reports status and response time.
Usage:
python3 uptime_monitor.py https://example.com
python3 uptime_monitor.py https://example.com https://google.com -i 30
python3 uptime_monitor.py -f sites.txt -i 60
Options:
-h, --help Show this help
-i INTERVAL, --interval INTERVAL
Check interval in seconds (default: 60)
-f FILE, --file FILE Read URLs from a file (one per line)
Requirements:
pip install requests
"""
import argparse
import requests
import sys
import time
from datetime import datetime
import signal
import os
# Global flag for graceful shutdown
running = True
def signal_handler(sig, frame):
global running
print("\n[!] Interrupt received. Shutting down gracefully...")
running = False
def check_site(url, timeout=10):
"""
Check if a site is up and measure response time.
Returns (is_up: bool, response_time_ms: float)
"""
try:
start_time = time.time()
response = requests.get(url, timeout=timeout, allow_redirects=True)
end_time = time.time()
response_time_ms = (end_time - start_time) * 1000
is_up = response.status_code < 400 # Consider 2xx and 3xx as up
return is_up, response_time_ms
except requests.exceptions.RequestException:
return False, 0.0
def load_urls_from_file(filename):
"""Load URLs from a file, one per line."""
try:
with open(filename, 'r') as f:
urls = [line.strip() for line in f if line.strip() and not line.startswith('#')]
return urls
except FileNotFoundError:
print(f"[!] File '{filename}' not found.", file=sys.stderr)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description="Monitor website uptime and response times.")
parser.add_argument('urls', nargs='*', help="URLs to monitor")
parser.add_argument('-i', '--interval', type=int, default=60, help="Check interval in seconds (default: 60)")
parser.add_argument('-f', '--file', help="Read URLs from file")
args = parser.parse_args()
# Load URLs
urls = args.urls
if args.file:
file_urls = load_urls_from_file(args.file)
urls.extend(file_urls)
if not urls:
print("[!] No URLs provided. Use --help for usage.", file=sys.stderr)
sys.exit(1)
print(f"[+] Monitoring {len(urls)} sites every {args.interval} seconds.")
print("[+] Press Ctrl+C to stop.\n")
# Set up signal handler for graceful shutdown
signal.signal(signal.SIGINT, signal_handler)
while running:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] Checking sites...")
for url in urls:
is_up, resp_time = check_site(url)
status = "UP" if is_up else "DOWN"
time_str = f"{resp_time:.0f} ms" if is_up else "N/A"
print(f" {url:<50} | {status:<4} | {time_str}")
if running:
print() # Empty line for readability
time.sleep(args.interval)
print("[+] Monitor stopped.")
if __name__ == "__main__":
main()
How to Use:
-
Install dependencies:
pip install requests
-
Run examples:
-
Features:
- Uptime check: HTTP status < 400 (2xx/3xx = UP).
- Response time: Total time for request (including redirects), in ms.
- Timeout: 10 seconds per request.
- Graceful shutdown: Ctrl+C stops cleanly.
- Logging: Timestamped output to console.
This script is production-ready for basic monitoring. For advanced use (e.g., alerting, database logging), extend it further!