网站性能检测脚本

代码脚本 · 其他

Python编写的网站性能监控脚本,定期检测网站的响应时间、HTTP状态码、SSL证书有效期、页面大小,发现响应超时、状态异常、证书即将过期时自动发送告警,是网站运维的必备工具。

详细内容

import requests, ssl, socket from datetime import datetime sites = ['https://example.com', 'https://ozhan.com.cn'] for url in sites: try: r = requests.get(url, timeout=10) print(f'{url}: 状态{r.status_code}, 响应{r.elapsed.total_seconds():.2f}s') if r.elapsed.total_seconds() > 3: print(f' 警告: 响应超时') except Exception as e: print(f'{url}: 异常 - {e}') # SSL证书检测 if url.startswith('https'): host = url.split('//')[1].split('/')[0] ctx = ssl.create_default_context() with socket.create_connection((host, 443)) as sock: with ctx.wrap_socket(sock, server_hostname=host) as ssock: cert = ssock.getpeercert() expiry = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z') days = (expiry - datetime.now()).days print(f' SSL证书: {days}天后过期') if days < 30: print(f' 警告: 证书即将过期')

适配环境

依赖环境:Python 3.7+,需安装requests

使用说明

1.安装Python 3.7+
2.pip install requests
3.保存为site_monitor.py
4.修改要监控的网址列表
5.配合crontab或任务计划定时运行
可以配置多个网站同时监控
设置响应时间阈值告警
SSL证书到期前30天告警
可以集成企业微信/钉钉推送
建议每5分钟检测一次

常见问题

问:支持HTTPS证书检测吗?
答:支持,可以检测证书有效期和到期时间

问:检测频率多少合适?
答:建议5-10分钟一次,太频繁可能被封

Python网站监控性能SSL告警运维免费

更多其他