监控Web服务器的HTTP响应状态码并发送警报
脚本如下
import requests
import smtplib
from email.mime.text import MIMEText
# 设置要监控的URL列表
URLS = [
'http://www.example.com',
'http://www.example.org',
# 添加更多需要监控的URL
]
# 设置允许的HTTP状态码
ALLOWED_STATUS_CODES = [200, 301, 302]
# 设置发送邮件的参数
SENDER = 'your_email@example.com'
RECIPIENT = 'recipient@example.com'
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USERNAME = 'your_username'
SMTP_PASSWORD = 'your_password'
def send_alert_email(url, status_code):
"""发送HTTP状态码警报邮件"""
subject = 'Web服务器HTTP状态码警报'
body = f'URL: {url}\n'
body += f'HTTP状态码: {status_code}\n'
body += '请立即检查并处理!'
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = SENDER
msg['To'] = RECIPIENT
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.send_message(msg)
def monitor_urls():
"""监控Web服务器的HTTP响应状态码"""
for url in URLS:
try:
response = requests.get(url)
status_code = response.status_code
if status_code not in ALLOWED_STATUS_CODES:
send_alert_email(url, status_code)
except requests.RequestException as e:
print(f'无法访问 {url}: {e}')
if __name__ == '__main__':
monitor_urls()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
上次更新: 2024/06/11, 23:05:26