#coding=utf-8 import requests # 导入 requests 库,用于向网站发送请求 import yagmail # 导入 yagmail 库,用于发送邮件 import time # 导入 time 库,用于设置监控间隔 # Email configuration SMTP_SERVER = 'smtp.qq.com' # 邮箱 SMTP 服务器地址 SMTP_PORT = 465 # 邮箱 SMTP 服务器端口 SMTP_USERNAME = 'your_email@gmail.com' # 邮箱用户名 SMTP_PASSWORD = 'your_email_password' # 邮箱密码或授权码 SMTP_FROM = 'your_email@gmail.com' # 发件人邮箱地址 SMTP_TO = 'recipient_email@gmail.com' # 收件人邮箱地址 # 设置要监控的网站 URL WEBSITE_URLS = ["https://www.example.com"] # 邮箱告警设置 def send_email(subject, message): yag = yagmail.SMTP(SMTP_USERNAME, SMTP_PASSWORD, SMTP_SERVER, SMTP_PORT, smtp_ssl=True) # 初始化 yagmail.SMTP 对象 yag.send(to=SMTP_TO, subject=subject, contents=message) # 发送邮件 # Function to check website status def check_website(url): try: response = requests.get(url) # 向网站发送 GET 请求 return response.status_code # 返回响应状态码 except requests.exceptions.RequestException as e: print(e) return None # Main loop to monitor website status website_statuses = {} # 创建一个字典来保存网站的状态 while True: # 进入无限循环 for url in WEBSITE_URLS: # 遍历要监控的网站 URL status = check_website(url) # 获取网站的状态码 if url not in website_statuses: # 如果网站 URL 不在字典中,添加到字典中 website_statuses[url] = None if status == website_statuses[url]: # 如果状态码未发生变化,打印日志信息 print('Website {} status unchanged: {}'.format(url, status)) else: # 如果状态码发生变化 if status == 200: # 如果状态码为 200,表示网站正常 website_statuses[url] = status print('Website {} status changed to: {}'.format(url, status)) else: # 如果状态码不为 200,表示网站出现问题,发送邮件告警 print('Website {} status changed to: {}'.format(url, status)) message = 'Website {} status changed to {}'.format(url, status) send_email('Website status change notification', message) time.sleep(60) # 设置监控间隔为 60 秒,每隔 60 秒执行一次```