github 仓库: gubaiovo/check_web_is_online: 使用 get 方法检查 web 在线,并通过邮箱提醒
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 import smtplibimport requestsfrom time import sleepimport refrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom datetime import datetimedef send_email (receiver, url, current_time, status_code ): sender_email = "aaa@aaa.com" password = "xxxxxx" message = MIMEMultipart() message["From" ] = sender_email message["To" ] = receiver message["Subject" ] = "网站上线" body = f"网站 {url} 状态为 {status_code} ,当前时间: {current_time} " message.attach(MIMEText(body, "plain" )) try : server = smtplib.SMTP("smtp.qq.com" , 587 ) server.starttls() server.login(sender_email, password) server.sendmail(sender_email, receiver, message.as_string()) print ("邮件发送成功" ) except Exception as e: print (f"邮件发送失败: {e} " ) finally : server.quit() def checkweb (receiver, url ): current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S" ) try : response = requests.get(url) if response.status_code == 200 : print (f"网站正常 {url} ,当前时间: {current_time} " ) send_email(receiver, url, current_time, response.status_code) else : print (f"网站异常{response.status_code} , 但是网站在线 {url} ,当前时间: {current_time} " ) send_email(receiver, url, current_time, response.status_code) except Exception as e: print (f"网站连接失败 {e} ,当前时间: {current_time} " ) def is_valid_email (email ): pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' return re.match (pattern, email) is not None def is_valid_url (url ): pattern = r'^(http|https)://[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+' return re.match (pattern, url) is not None print (r""" ________ __________ .__ / _____/ __ __ \______ \_____ |__| / \ ___| | \ | | _/\__ \ | | \ \_\ \ | / | | \ / __ \| | \______ /____/ |______ /(____ /__| \/ \/ \/ """ )print ("ctrl + c 退出程序" )time = int (input ("请输入检测间隔时间(秒): " )) receiver = input ("请输入收件人邮箱: " ) while not is_valid_email(receiver): print ("邮箱格式不正确,请重新输入。" ) receiver = input ("请输入收件人邮箱: " ) url = input ("请输入网站地址(http/https不可省略): [ https(http)://www.example.com ]: " ) while not is_valid_url(url): print ("网站地址格式不正确,请重新输入。" ) url = input ("请输入网站地址(http/https不可省略): [ https(http)://www.example.com ]: " ) while True : checkweb(receiver, url) sleep(time)