python實現批量監控網站,python實現監控

來源:互聯網
上載者:User

python實現批量監控網站,python實現監控

最近又新上了一部分網站,隨著網站的增多,管理複雜性也上來了,俗話說:人多了不好帶,我發現網站多了也不好管,因為這些網站裡有重要的也有不重要的,重要核心的網站當然就管理的多一些,像一些萬年都不出一次問題的,慢慢就被自己都淡忘了,冷不丁那天出個問題,還的手忙腳亂的去緊急處理,所以規範的去管理這些網站是很有必要的,今天我們就做第一步,不管大站小站,先統一把監控做起來,先不說業務情況,最起碼那個網站不能訪問了,要第一時間報出來,別等著業務方給你反饋,就顯得我們不夠專業了,那接下來我們看看如果用python實現多網站的可用性監控,指令碼如下:

#!/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:])

指令碼核心點解釋:

1、getattr()是python的內建函數,接收一個對象,可以根據對象屬性返回對象的值。

2、compare_site_status()函數是返回的是一個內部定義的函數。

3、map(),需要2個參數,一個是函數,一個是序列,功能就是將序列中的每個元素應用函數方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.