Python enables automatic monitoring of websites and sending email alerts

Source: Internet
Author: User
Tags curl explode python script


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 

#!/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

Note: 1, change [email protected] 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   #引入事件类 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)  * 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, please be sure to keep this source http://mapengfei.blog.51cto.com/1552412/1841731

Python enables automatic monitoring of websites and sending email alerts

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.