Python enables automatic monitoring of websites and sending email alerts

Source: Internet
Author: User
Tags explode python script

Original works, allow reprint, please be sure to use hyperlinks in the form of the original source of the article , author information and this Statement. otherwise, the legal liability will be investigated. http://mapengfei.blog.51cto.com/1552412/1841731

By timed execution of Python script, you can implement regular batch access to the site, if you find that the site is not open, the first time to send mail to the administrator mailbox for early warning

python3.5 is used Here.

Plugins that need to be installed:

Smtplib: e-mail needs to be used

Pycurl: when visiting the website, you will need to use

Linecache: when reading the TXT Web site list, you 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 '] =  ' [email protected] '          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 (' Mail 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:35.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")      &nbSp;  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, the Xx[email protected] into your own mailbox,

2. Change the file path to your true path

#!/usr/bin/python#-*- coding:utf-8 -*-import pycurlimport osimport sysimport  linecacheimport time   #引入事件类 to get the current time of the system #from ceshi import studentfrom email  import email_sendfrom curl import curl#bart = student (' Mafei ', 59) # Bart.print_score () def script (urls,type):    msgto =  ' [email protected] '     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 =  Monitoring notifications----%s  url:%s " %  (url_1[0], url)  +  " + time.strftime" ("%y-%m-%d %h:%m:%s", time.localtime (time.time ()))  +  "restored"         down_title =  "monitoring notification----%s url :%s " %  (url_1[0], url)  + " in " + time.strftime ("%y-%m-%d %h:%m:%s ", Time.localtime (time.time ()))  +  "unable to 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))   &nbsP;         print (code+ ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ')          except Exception as e:             print ('--------error message:--------', 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== '  or& 'nbsp;code== '  or code== ' 404 ':             resolveTime = 0             Connection_time = 0            transfer_ Total_time = 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.sendemail ()              print (resole)              print (data3 +  ' Mail has been sent ')          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)  *&Nbsp;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 (' Website can open normally ')     &Nbsp;        #f  = open (filename,  ' a ', encoding= ' utf-8 ')              file_exit=os.path.exists (filename)               #print (file_exit)               #判断这个日志文件存不存在              if (file_exit):                  #读取文件最后一行, in order to read out the last state value                  file = open (filename,  ' r ', encoding= ' Utf-8 ')                  linecount = len ( File.readlines ())                  data = linecaChe.getline (filename, linecount)                  file.close                 if data ==  ':                     print (' This is ' +data+ ' for empty data ')                  else:                     print (' Other information%s ' % (data)                      explode = data.split ('----')                       #判断如果读取出来的值, The last time the exception is in the case of alarms                      if explode[3]== ' 0\n '   or explode[3]== ' 400\n '  or explode[3]== '  or explode[3]== ' 404 ':                          data3 =  ' website:%s has resumed%s '  %  (url_1[0], now_time,url) at%s                           stat3 = email_send (msgto, data3, recovery_title)                           resole = stat3.sendemail ()                          print (resole)                           print (data3 +  ' Mail has been sent ')                      else:                         print (' Last recorded as a different value:%s '% (explode[3]) + '-----')              Else:                print (' File does not exist ')         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 ',  encoding= ' 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:    &nbSp;       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)

This article is from the "Ma Pengfei--" blog, source http://mapengfei.blog.51cto.com/1552412/1841731

Python enables automatic monitoring of websites and sending email alerts

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.