Preface
Because there are some sites need daily check whether there is a problem, so need an alarm monitoring mechanism, this requires you to specify the mailbox you send and the mailbox you receive, you can do to the site automatic monitoring.
python3.5 is used here.
Plugins that need to be installed:
1,smtplib: E-mail needs to use
2,Pycurl: Access to the site will need to use
3,Linecache: When reading the TXT website list need to use
Specific ideas:
The Python program reads the information from the TXT in bulk to the website, accesses the website through the curl.py simulation browser, and writes the results of the visit to a file in its own website name-date. txt format; there are several situations:
1, if found not open, direct e-mail prompted the site has not opened
2, the discovery can open, read the file in the last access situation (read the TXT file the final line),
1) If you find that the last time is not open, e-mail reminder site has been restored
2) If the last time is found to be open (200 of the return code), just record the site access to the log can be
A total of 4 files
email.py is the message class, mainly used to send the message when the call, here need to follow your case to change to your mailbox (msg[' from '), the Mailbox server address (SMTP address), and your mailbox password (smtp.login)
email.py
#!/usr/bin/python#-*-coding:utf-8-*-import sysimport smtplibfrom email.mime.text Import Mimetextfrom Email.mime.multipart Import Mimemultipartclass 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 ', ') smtp.login (msg[' from '), ' xxxx ') #改成自己的邮箱密码 smtp.sendmail (msg[' from '], msg[' To '].split (', '), msg.as_string ()) return (' message sent successfully ') 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:3 5.0) gecko/20100101 firefox/35.0 ") return C
Curl.py is primarily used to perform a file that simulates a browser's access to a Web site and returns results
#!/usr/bin/python#-*-coding:utf-8-*-import sysimport pycurlclass 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 as the main program, mainly execute call the above function, read the TXT file in the Web site list, if the website can not open to send an email alarm
Need to note:
1, change the xxxx@xxxx.com to your own mailbox,
2. Change the file path to your true path
#!/usr/bin/python#-*-coding:utf-8-*-import pycurlimport osimport sysimport linecacheimport time #引入事件类, used to get system current times # From Ceshi import studentfrom Email import email_sendfrom Curl Import Curl#bart = Student (' Mafei ',) #bart. Print_score () d EF 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] Recover Y_title = "Monitoring notification----%s url:%s"% (url_1[0], URL) + "in" + Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Time.time ())) + " "Down_title =" Monitoring notification has been restored----%s url:%s "% (url_1[0], URL) +" in "+ Time.strftime ("%y-%m-%d%h:%m:%s ", Time.localtime (Time.ti Me ()) + "Cannot open" #print (' ~~~~~~~~~~~~~~~~~~~ ') #print (URL) #引用爬去网站的类, call result Url_result = Curl (URL) c = url_result. Curl_site () try:c.perform () code = str (c.getinfo (C.http_code)) print (code+ ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ') exc EPT Exception as E:print ('--------error message:--------', E) #indexfile. Close () #c. Close () code = str (c.getinfo (C.http_code)) # Print (code+ ' aaaaaaaaaaaaaaaaaaaaaaaaa AAAAAAA ') filename = '%s-%s.txt '% (Url_1[0], time.strftime ("%y-%m-%d", Time.localtime (Time.time ()))) #判断如果在网站无法打开的情况下 if code = = ' 0 ' or code== ' or code== ' or code== ' 404 ': resolvetime = 0 connection_time = 0 transfer_total_tim E = 0 total_time = 0 # print (' for 000000000000000000000000000000000000000000 ') data3 = ' website:%s cannot open%s '% (url_1[0], URL) # indexfile.close () # c.close () #判断网站如果挂了就发邮件 STAT3 = Email_send (msgto, data3, Down_title) Resole=stat3.sendemai L () print (resole) print (Data3 + ' mail sent ') Else: #resolveTime = str (c.getinfo (c.namelookup_time) * +) + "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) * +) + "MS" # Connection_time=round (float (Connection_time)) #Transfer_ToTal_time = str (c.getinfo (c.total_time) * 1000-c.getinfo (c.pretransfer_time) * +) + "MS" #Total_Time = STR (c.getinf O (c.total_time) * +) + "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 (' website can open normally ') #f = Open (filename, ' a ', encoding= ' Utf-8 ') file_exit=os.path.exists (filename) #print (file_exit) #判断这个日志文件存不存在 if (file_ex It): #读取文件最后一行, in order to read out the last state value of file = open (filename, ' r ', encoding= ' utf-8 ') LineCount = Len (File.readlines ()) da TA = linecache.getline (filename, linecount) file.close if data = = ': Print (' This is ' +data+ ' is empty data ') Else:prin T (' Other information%s '% (data)) explode = data.split ('----') #判断如果读取出来的值, the last exception is the case of an alarm if explode[3]== ' 0\n ' or explode[3]== ' 400\n ' or explode[3]== ' or explode[3]== ' 404 ': Data3 = ' website:%s has recovered%s ' in%s '% (Url_1[0], now_time,url) STAT3 = E Mail_send (Msgto, data3, RecoveRy_title) Resole = Stat3.sendemail () print (resole) print (Data3 + ' mail sent ') Else:print (' last recorded as a different value :%s '% (explode[3]) + '-----') else:print (' File not present ') Data2 = ' \ n ' + url_1[0] + '----' + URL + '-----' + time.strftime ("%H :%m:%s ", Time.localtime (Time.time ())) + '-------' + code print (' Data2 Data Write success: ' + data2 ') file = open (filename, ' a ', Encodi ng= ' Utf-8 ') file.write (data2) file.close# Bart = Student (data2,59) # Bart.print_score () if __name__ = = "__main__": type = "Monitoring notification-Test" + time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Time.time ())) data1=[' Company Portal---www.luoan.com.cn ', ' Company platform---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= "Monitoring notification-center" + time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ( Time.time ()) script (Data2,title)
Summarize
Using Python to automatically monitor the site and send email alerts to this is basically the end of the hope that everyone's study work can be helpful.