Preface
Because some websites need to check whether there are problems every day, an alarm monitoring mechanism is needed. This requires you to specify the email address you send and the email you receive. With your email address, you can automatically monitor the website.
The python3.5 used here
Plug-ins that need to be installed:
1. smtplib: Needed to send emails Go to
2. pycurl: You will need to use
when accessing the website 3. linecache: You will need to use it when reading the txt website list
Specific idea:
The python program reads website information in batches from txt, and uses Curl.py to simulate a browser to access the website , and write the results of the visit into a file in the format of your website name-date.txt; there are several situations:
1. If you find that it cannot be opened, send an email directly. Prompt that the website cannot be opened
2. It is found that it can be opened and the last accessed situation in the file is read (read the last line of the txt file),
1) If it is found that it cannot be opened last time, send an email to remind that the website has been restored
2) If it is found that it can be opened last time (200 return code), only the log of website access is recorded That’s it
A total of 4 files
Email.py is an email class, which is mainly used to call when sending emails. Here you need to follow In your case, change it to your email (msg['From']), email server address (SMTP address), and your email password (SMTP.login)
Email.py
#!/usr/bin/python #-*- coding:utf-8 -*- import sys import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart class Email_send(object): def __init__(self,msgTo,data2,Subject): self.msgTo=msgTo self.data2=data2 self.Subject=Subject def sendEmail(self): # (attachment,html) = content msg = MIMEMultipart() msg['Subject'] = self.Subject msg['From'] = 'xxxx@xxxx.com.cn' msg['To'] = self.msgTo html_att = MIMEText(self.data2, 'html', 'utf-8') #att = MIMEText(attachment, 'plain', 'utf-8') msg.attach(html_att) #msg.attach(att) try: smtp = smtplib.SMTP() smtp.connect('smtp.xxxx.com', 25) smtp.login(msg['From'], 'xxxx') #改成自己的邮箱密码 smtp.sendmail(msg['From'], msg['To'].split(','), msg.as_string()) return('邮件发送成功') except Exception as e: print('--------------sss------',e) def curl(self): import pycurl c=pycurl.Curl() #url="www.luoan.com.cn" #indexfile=open(os.path.dirname(os.path.realpath(__file__))+"/content.txt","wb") c.setopt(c.URL,url) c.setopt(c.VERBOSE,1) c.setopt(c.ENCODING,"gzip") #模拟火狐浏览器 c.setopt(c.USERAGENT,"Mozilla/5.0 (Windows NT 6.1; rv:35.0) Gecko/20100101 Firefox/35.0") return c
Curl.py is a file mainly used to simulate browser access to the website and return the results
#!/usr/bin/python #-*- coding:utf-8 -*- import sys import pycurl class Curl(object): def __init__(self,url): self.url=url def Curl_site(self): c=pycurl.Curl() #url="www.luoan.com.cn" #indexfile=open(os.path.dirname(os.path.realpath(__file__))+"/content.txt","wb") c.setopt(c.URL,self.url) c.setopt(c.VERBOSE,1) c.setopt(c.ENCODING,"gzip") #模拟火狐浏览器 c.setopt(c.USERAGENT,"Mozilla/5.0 (Windows NT 6.1; rv:35.0) Gecko/20100101 Firefox/35.0") return c
site_moniter.py This file is the main program, which mainly executes and calls the above functions, reads the website list in the txt file, and sends an email to alert if the website cannot be opened
Note:
1. Change xxxx@xxxx.com to your own email,
2. Change the file path Become your own real path
#!/usr/bin/python #-*- coding:utf-8 -*- import pycurl import os import sys import linecache import time #引入事件类,用来获取系统当前时间 #from ceshi import Student from Email import Email_send from Curl import Curl #bart = Student('mafei',59) #bart.print_score() def script(urls,type): msgTo = 'xxxx@xxxx.com' now_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) j=1 # data2=[{'aa':'aa'}] for url_split in urls: #print(url_split) url_1=url_split.split('---') url=url_1[1] recovery_title = "监控通知----%s url:%s" % (url_1[0], url) + "在" + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) + "已经恢复" down_title = "监控通知----%s url:%s" % (url_1[0], url) + "在" + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) + "无法打开" #print('~~~~~~~~~~~~~~~~~~~') #print(url) #引用爬去网站的类,调用结果 url_result = Curl(url) c = url_result.Curl_site() try: c.perform() code = str(c.getinfo(c.HTTP_CODE)) print(code+'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') except Exception as e: print('--------错误信息:--------',e) #indexfile.close() #c.close() code = str(c.getinfo(c.HTTP_CODE)) # print(code+'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') filename = '%s-%s.txt' % (url_1[0], time.strftime("%Y-%m-%d", time.localtime(time.time()))) #判断如果在网站无法打开的情况下 if code == '0' or code=='400' or code=='500' or code=='404': resolveTime = 0 Connection_Time = 0 Transfer_Total_Time = 0 Total_Time = 0 # print('为000000000000000000000000000000000000000000') data3 = '网站:%s无法打开%s' % (url_1[0], url) # indexfile.close() # c.close() #判断网站如果挂了就发邮件 stat3 = Email_send(msgTo, data3, down_title) resole=stat3.sendEmail() print(resole) print(data3 + '邮件已经发送') else: #resolveTime = str(c.getinfo(c.NAMELOOKUP_TIME) * 1000) + " ms" # Connection_Time=str(float(c.getinfo(c.CONNECT_TIME)*1000-c.getinfo(c.NAMELOOKUP_TIME)*1000))+" ms" #Connection_Time = str(c.getinfo(c.CONNECT_TIME) * 1000 - c.getinfo(c.NAMELOOKUP_TIME) * 1000) + " ms" # Connection_Time=round(float(Connection_Time)) #Transfer_Total_Time = str(c.getinfo(c.TOTAL_TIME) * 1000 - c.getinfo(c.PRETRANSFER_TIME) * 1000) + " ms" #Total_Time = str(c.getinfo(c.TOTAL_TIME) * 1000) + " ms" # data2=data # data={'url':url,'HTTP CODE':code,'resolveTime':resolveTime,'Connection_Time':Connection_Time,'Transfer_Total_Time':Transfer_Total_Time,'Total_Time':Total_Time} print('网站可以正常打开') #f = open(filename, 'a',encoding='utf-8') file_exit=os.path.exists(filename) #print(file_exit) #判断这个日志文件存不存在 if(file_exit): #读取文件最后一行,为了读取出来最后一次的状态值 file = open(filename, 'r',encoding='utf-8') linecount = len(file.readlines()) data = linecache.getline(filename, linecount) file.close if data == '': print('这是'+data+'为空的数据') else: print('其他信息%s'%(data)) explode = data.split('----') #判断如果读取出来的值,最后一次是异常的情况就告警 if explode[3]=='0\n' or explode[3]=='400\n' or explode[3]=='500' or explode[3]=='404': data3 = '网站:%s在%s已经恢复%s' % (url_1[0], now_time,url) stat3 = Email_send(msgTo, data3, recovery_title) resole = stat3.sendEmail() print(resole) print(data3 + '邮件已经发送') else: print('最后一次记录为其他值:%s'%(explode[3])+'-----') else: print('文件不存在') data2 = '\n' + url_1[0] + '----' + url + '-----' + time.strftime("%H:%M:%S", time.localtime(time.time())) + '-------' + code print('data2数据写入成功:' + data2) file = open(filename, 'a', encoding='utf-8') file.write(data2) file.close # bart = Student(data2,59) # bart.print_score() if __name__ == "__main__": type = "监控通知-测试" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) data1=['公司门户---www.luoan.com.cn','公司平台---yun.luoan.com.cn'] #script(data1,type) #中心层面的网站清单 file=open('D:\python\site_moniter\zhongxin.txt') data2=[] while 1: line2 =file.readline() print(line2) if not line2: break data2.append(line2[0:-1]) #data2=['www.luoan.com.cn','yun.luoan.com.cn','www.qq.com'] print(data2) title="监控通知-中心"+ time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) script(data2,title)
Summary
Use Python to automatically monitor the website and send This basically ends the email alert method. I hope it will be helpful to everyone’s learning work.
For more articles related to Python automatically monitoring websites and sending email alerts, please pay attention to the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools