网站可用性监控脚本
定时监控多个网站的可用性和响应时间,异常时发送邮件告警,支持状态记录。
详细内容
#!/usr/bin/env python3
# 网站可用性监控脚本
# 依赖: pip install requests
# 使用方法: python3 website_monitor.py
import requests
import time
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
# ========== 配置区 ==========
WEBSITES = [
"https://www.baidu.com",
"https://www.zhihu.com",
"https://ozhan.com.cn", # 改成你的网站
]
CHECK_INTERVAL = 60 # 检查间隔(秒)
TIMEOUT = 10 # 超时时间(秒)
ALERT_EMAIL = "your@email.com" # 告警邮箱
SMTP_SERVER = "smtp.qq.com"
SMTP_PORT = 465
SMTP_USER = "your@qq.com"
SMTP_PASS = "your_smtp_code"
# ============================
def send_alert(url, status, response_time, error=None):
"""发送告警邮件"""
subject = f"【网站告警】{url} 异常"
body = f"""
网站监控告警通知
====================
网站: {url}
状态: {status}
响应时间: {response_time}ms
时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
错误信息: {error or '无'}
"""
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = SMTP_USER
msg['To'] = ALERT_EMAIL
try:
server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
server.login(SMTP_USER, SMTP_PASS)
server.sendmail(SMTP_USER, ALERT_EMAIL, msg.as_string())
server.quit()
print(f" ✅ 告警邮件已发送")
except Exception as e:
print(f" ❌ 告警邮件发送失败: {e}")
def check_website(url):
"""检查单个网站"""
try:
start = time.time()
response = requests.get(url, timeout=TIMEOUT, allow_redirects=True)
response_time = round((time.time() - start) * 1000)
if response.status_code == 200:
print(f" ✅ {url} - {response.status_code} - {response_time}ms")
return True, response_time
else:
print(f" ⚠️ {url} - 状态码: {response.status_code} - {response_time}ms")
send_alert(url, f"HTTP {response.status_code}", response_time)
return False, response_time
except requests.exceptions.Timeout:
print(f" ❌ {url} - 超时 ({TIMEOUT}s)")
send_alert(url, "超时", TIMEOUT * 1000, "请求超时")
return False, TIMEOUT * 1000
except Exception as e:
print(f" ❌ {url} - 错误: {str(e)}")
send_alert(url, "连接失败", 0, str(e))
return False, 0
def main():
print("=" * 50)
print(" 网站可用性监控启动")
print(f" 监控网站数: {len(WEBSITES)}")
print(f" 检查间隔: {CHECK_INTERVAL}秒")
print("=" * 50)
while True:
print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始检查...")
for url in WEBSITES:
check_website(url)
print(f"\n等待 {CHECK_INTERVAL} 秒后再次检查...")
time.sleep(CHECK_INTERVAL)
if __name__ == '__main__':
main()