Python implements batch monitoring of website details and instances

Source: Internet
Author: User
This article will share with you a very practical script for implementing multi-site availability monitoring using python, with the core points to be explained, if you have the same requirements, you can refer to this article to share with you a very practical script for implementing multi-site availability monitoring using python, with the explanation of the core points attached, if you have the same requirements, refer

">

Recently, some new sites have been launched. as the number of sites increases, the management complexity has also increased. as the saying goes: it is difficult to bring more people, and I find it difficult to manage the sites when there are more sites, because there are important and unimportant sites in these sites, of course, there are more important core sites managed, such as those that have never encountered any problems for many years, I was forgotten by myself, and there was a problem that day, and I was still in a hurry to handle it urgently. Therefore, it is necessary to manage these sites in a standardized manner, today, we will do our first step. no matter how big or small the station is, we need to make unified monitoring and not talk about the business situation. at least that site cannot be accessed. we need to report it as soon as possible, don't wait for the feedback from the business side, it seems that we are not professional enough. let's take a look at the following script if you use python to monitor the availability of multiple websites:

#!/usr/bin/env python  import pickle, os, sys, loggingfrom httplib import HTTPConnection, socketfrom smtplib import SMTP def email_alert(message, status):  fromaddr = 'xxx@163.com'  toaddrs = 'xxxx@qq.com'    server = SMTP('smtp.163.com:25')  server.starttls()  server.login('xxxxx', 'xxxx')  server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))  server.quit() def get_site_status(url):  response = get_response(url)  try:    if getattr(response, 'status') == 200:      return 'up'  except AttributeError:    pass  return 'down'    def get_response(url):  try:    conn = HTTPConnection(url)    conn.request('HEAD', '/')    return conn.getresponse()  except socket.error:    return None  except:    logging.error('Bad URL:', url)    exit(1)    def get_headers(url):  response = get_response(url)  try:    return getattr(response, 'getheaders')()  except AttributeError:    return 'Headers unavailable' def compare_site_status(prev_results):    def is_status_changed(url):    status = get_site_status(url)    friendly_status = '%s is %s' % (url, status)    print friendly_status    if urlin prev_resultsand prev_results[url] != status:      logging.warning(status)      email_alert(str(get_headers(url)), friendly_status)    prev_results[url] = status   return is_status_changed def is_internet_reachable():  if get_site_status('www.baidu.com') == 'down' and get_site_status('www.sohu.com') == 'down':    return False  return True  def load_old_results(file_path):  pickledata = {}  if os.path.isfile(file_path):    picklefile = open(file_path, 'rb')    pickledata = pickle.load(picklefile)    picklefile.close()  return pickledata  def store_results(file_path, data):  output = open(file_path, 'wb')  pickle.dump(data, output)  output.close()  def main(urls):  logging.basicConfig(level=logging.WARNING, filename='checksites.log',       format='%(asctime)s %(levelname)s: %(message)s',       datefmt='%Y-%m-%d %H:%M:%S')    pickle_file = 'data.pkl'  pickledata = load_old_results(pickle_file)  print pickledata      if is_internet_reachable():    status_checker = compare_site_status(pickledata)    map(status_checker, urls)  else:    logging.error('Either the world ended or we are not connected to the net.')      store_results(pickle_file, pickledata) if __name__ == '__main__':  main(sys.argv[1:])

Script core points:

1. getattr () is a python built-in function that receives an object and can return the object value based on the object property.

2. the compare_site_status () function returns an internally defined function.

3. map () requires two parameters. one is a function and the other is a sequence. the function is to apply function methods to each element in the sequence.

The above is the details about how to implement batch monitoring on python websites and instances. For more information, see other related articles in the first PHP community!

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.