Use python to check website availability in batches and python availability

Source: Internet
Author: User

Use python to check website availability in batches and python availability

Preface

As the number of sites increases, the management complexity has also increased. As the saying goes: when there are too many people, it is difficult for me to handle too many 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 url in prev_results and 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,compare_site_status()The function returns an internally defined function.

3,map() Two parameters are required. One is a function, and the other is a sequence. The function is to apply Function Methods to each element in the sequence.

Summary

The above is all the content of this article. If you need it, you can refer to it for reference.

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.