الملفات
ghaymah-exam-abdelaziz-sre/q5-mithal-monitor/monitor.py
2026-07-29 13:28:26 -04:00

142 أسطر
2.7 KiB
Python

import requests
import socket
import ssl
import json
import time
import os
from datetime import datetime, timezone
from urllib.parse import urlparse
URL = "https://mithal.space"
SEARCH_URL = "https://mithal.space/?q=test"
OUTPUT_FILE = "monitor_data.json"
def get_latency():
start = time.time()
response = requests.get(URL, timeout=10)
latency = round((time.time() - start) * 1000, 2)
return latency, response.status_code
def get_dns_time():
host = urlparse(URL).hostname
start = time.time()
socket.gethostbyname(host)
dns_time = round((time.time() - start) * 1000, 2)
return dns_time
def get_ssl_info():
host = urlparse(URL).hostname
context = ssl.create_default_context()
with socket.create_connection((host, 443), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
cert = ssock.getpeercert()
expiry = cert["notAfter"]
expiry_date = datetime.strptime(
expiry,
"%b %d %H:%M:%S %Y %Z"
).replace(tzinfo=timezone.utc)
remaining = (expiry_date - datetime.now(timezone.utc)).days
return remaining, expiry
def get_search_latency():
start = time.time()
requests.get(SEARCH_URL, timeout=10)
return round((time.time() - start) * 1000, 2)
while True:
try:
latency, status = get_latency()
uptime = "UP" if status == 200 else "DOWN"
dns_time = get_dns_time()
ssl_days, ssl_expiry = get_ssl_info()
search_latency = get_search_latency()
result = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"uptime": uptime,
"status_code": status,
"latency_ms": latency,
"dns_ms": dns_time,
"ssl_days_remaining": ssl_days,
"ssl_expiry": ssl_expiry,
"search_latency_ms": search_latency
}
except Exception as e:
result = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"uptime": "DOWN",
"status_code": 0,
"latency_ms": 0,
"dns_ms": 0,
"ssl_days_remaining": 0,
"ssl_expiry": "Unavailable",
"search_latency_ms": 0,
"error": str(e)
}
# Load previous history
if os.path.exists(OUTPUT_FILE):
try:
with open(OUTPUT_FILE, "r") as f:
history = json.load(f)
except:
history = []
else:
history = []
# Add new result
history.append(result)
# Keep only last 24 hours (1440 checks)
history = history[-1440:]
# Save JSON
with open(OUTPUT_FILE, "w") as f:
json.dump(history, f, indent=4)
print(result)
time.sleep(60)