Python automatically monitors websites and sends email alerts

Source: Internet
Author: User
This article describes how to regularly execute python scripts to access websites in batches. if you find that the website cannot be opened, you can send an email to the administrator's mailbox for warning immediately. For more information, see. Preface

Because some websites need to check whether there is a problem on a daily basis, an alarm monitoring mechanism is required. you need to specify the email address you sent and the email address you received, you can automatically monitor your website.

Here, python3.5 is used.

Plug-ins to be installed:

1,Smtplib: Used for sending emails

2,Pycurl: Used to access a website

3,Linecache: Used to read the txt website list

Specific ideas:

Records are recorded in the prepare format. There are several situations:

1. if you find that the website cannot be opened, send an email directly prompting you that the website cannot be opened.

2. you can open the file and read the last access to the file (read the last row of the txt file ),

1) If you find that the last attempt was rejected, send an email to remind you that the website has recovered.

2) If you find that the last attack was opened (200 return code), you only need to record the website access logs.

4 files in total

Email. py is an email class, mainly used for calling when sending an email. here, you need to change it to your mailbox (msg ['from']), email 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 ['subobject'] = 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'], 'XXX') # Change it to your mailbox password smtp. sendmail (msg ['from'], msg ['to']. split (','), msg. as_string () return ('mail sent successfully ') failed t 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") # simulate Firefox browser 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 used to simulate a browser to access a website and return 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") # simulate Firefox browser c. setopt (c. USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv: 35.0) Gecko/20100101 Firefox/35.0") return c

The site_moniter.py file is the main program. it mainly calls the above function to read the list of websites in the txt file. if the website cannot be opened, an alarm is sent.

Note:

1. change the xxxx@xxxx.com into your own mailbox,

2. change the file path to your own real path.

#! /Usr/bin/python #-*-coding: UTF-8-*-import pycurlimport osimport sysimport linecacheimport time # introduce the event class, used to obtain the current system time # from ceshi import Studentfrom Email import Email_sendfrom 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 = [{'a': 'A'}] for url_split in urls: # Print (url_split) url_1 = url_split.split ('---') url = url_1 [1] recovery_title = "monitoring notification ---- % s url: % s" % (url_1 [0], url) + "in" + time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime (time. time () + "recovered" down_title = "monitoring notification ---- % s url: % s" % (url_1 [0], url) + "in" + time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime (time. time () + "cannot open" # print ('~~~~~~~~~~~~~~~~~~~ ') # Print (url) # reference the crawling website class. the calling result url_result = Curl (url) c = url_result.Curl_site () try: c. perform () code = str (c. getinfo (c. HTTP_CODE) print (code + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') failed t Exception as e: print ('-------- error message: -------- ', e) # indexfile. close () # c. close () code = str (c. getinfo (c. HTTP_CODE) # print (code + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') filename = 'audio s-%s.txt '% (url_1 [0], time. strftime ("% Y-% m-% d", time. localtime (time. time ()))) # determine if the website cannot be opened, if code = '0' or code = '000000' or code = '000000' or code = '000000 ': resolveTime = 0 Connection_Time = 0 Transfer_Total_Time = 0 Total_Time = 0 # print ('2017 ') data3 = 'website: % s cannot open % s' % (url_1 [0], url) # indexfile. close () # c. close () # determine if the website is down and send an email "stat = Email_send (msgTo, data3, down_title) resole = stat3.sendEmail () print (resole) print (data3 + 'email 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 ('The website can be opened normally') # f = open (filename, 'A', encoding = 'utf-8') file_exit = OS. path. exists (filename) # print (file_exit) # determine whether the log file does not exist if (file_exit): # read the last row of the file, to read 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 +' empty data') else: print ('other information % s' % (data )) explode = data. split ('----') # judge if the value is read, if explode [3] = '0 \ n' or explode [3] = '2014 \ n' or explode [3] =' 500 'or explode [3] = '000000 ': data3 = 'website: % s has recovered % s' % (url_1 [0], now_time, url) stat3 = Email_send (msgTo, data3, recovery_title) in % s) resole = stat3.sendEmail () print (resole) print (data3 + 'email sent ') else: print ('last record is another 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 written successfully: '+ 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) # central website list 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)

Summary

The method of using Python to automatically monitor the website and send email alerts has basically ended. I hope this will be helpful for everyone's learning work.

For more articles related to Python's automatic monitoring of websites and sending email alerts, refer to PHP's Chinese website!

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.