The user is looking for a Python script to check website uptime and response times. I need to provide a concise answer with code. I don't think I need to ask clarifying questions; I can provide a general script using libraries like requests and time, and maybe argparse for command-line arguments.
The script should accept multiple URLs, send HTTP GET requests, time the responses, and print the status. I’ll make sure it’s clear and straightforward, focusing on the essential components.Drafting a minimal uptime monitoring script
I’m creating a minimal working Python script called monitor.py. First, I'll import argparse, requests, time, and datetime.
The check_url function will attempt to get the response from a given URL within a specified timeout, capturing the elapsed time and status.
In the main function, I’ll parse the command-line arguments for URLs and intervals. For each URL, I’ll run the check in a loop, printing the timestamp, URL, status, and response time. I could mention using aiohttp for asynchronous operations as an option. Finally, I’ll suggest running this script as a cron job for consistent uptime monitoring. Below is a simple, self-contained Python script that:
Checks whether a website is up (HTTP status).
Measures response time.
Repeats checks at a configurable interval.
Works for one or multiple URLs.
Requirements
bash
pip install requests
Script: uptime_monitor.py
python
#!/usr/bin/env python3
import argparse
import time
from datetime import datetime
import requests
def check_url(url: str, timeout: float = 5.0):
"""
Send a GET request to the given URL and measure response time.
Returns a dict with: url, ok, status_code, elapsed_ms, error
"""
start = time.monotonic()
try:
resp = requests.get(url, timeout=timeout)
elapsed_ms = (time.monotonic() - start) * 1000.0
return {
"url": url,
"ok": resp.ok,
"status_code": resp.status_code,
"elapsed_ms": round(elapsed_ms, 2),
"error": None,
}
except requests.RequestException as e:
elapsed_ms = (time.monotonic() - start) * 1000.0
return {
"url": url,
"ok": False,
"status_code": None,
"elapsed_ms": round(elapsed_ms, 2),
"error": str(e),
}
def monitor(urls, interval: float, count: int | None, timeout: float):
"""
Monitor the given URLs.
- interval: seconds between checks
- count: number of iterations (None or 0 for infinite)
"""
iteration = 0
while True:
iteration += 1
timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
print(f"\n[{timestamp} UTC] Check #{iteration}")
print("-" * 80)
print(f"{'URL':50} {'UP':3} {'STATUS':6} {'TIME_MS':8} ERROR")
print("-" * 80)
for url in urls:
result = check_url(url, timeout=timeout)
up_str = "YES" if result["ok"] else "NO"
status = result["status_code"] if result["status_code"] is not None else "-"
err = result["error"] or ""
print(f"{url:50} {up_str:3} {status!s:6} {result['elapsed_ms']:8.2f} {err}")
if count and iteration >= count:
break
time.sleep(interval)
def parse_args():
parser = argparse.ArgumentParser(
description="Check website uptime and response times."
)
parser.add_argument(
"urls",
nargs="+",
help="One or more URLs to monitor (e.g. https://example.com)",
)
parser.add_argument(
"-i",
"--interval",
type=float,
default=60.0,
help="Interval between checks in seconds (default: 60)",
)
parser.add_argument(
"-n",
"--count",
type=int,
default=0,
help="Number of checks to run (0 means run forever)",
)
parser.add_argument(
"-t",
"--timeout",
type=float,
default=5.0,
help="Request timeout in seconds (default: 5)",
)
return parser.parse_args()
def main():
args = parse_args()
monitor(
urls=args.urls,
interval=args.interval,
count=args.count if args.count > 0 else None,
timeout=args.timeout,
)
if __name__ == "__main__":
main()