利用python批量检查网站的可用性


Posted in Python onSeptember 09, 2016

前言

随着站点的增多,管理复杂性也上来了,俗话说:人多了不好带,我发现站点多了也不好管,因为这些站点里有重要的也有不重要的,重要核心的站点当然就管理的多一些,像一些万年都不出一次问题的,慢慢就被自己都淡忘了,冷不丁那天出个问题,还的手忙脚乱的去紧急处理,所以规范的去管理这些站点是很有必要的,今天我们就做第一步,不管大站小站,先统一把监控做起来,先不说业务情况,最起码那个站点不能访问了,要第一时间报出来,别等着业务方给你反馈,就显得我们不够专业了,那接下来我们看看如果用python实现多网站的可用性监控,脚本如下:

#!/usr/bin/env python
 
 
import pickle, os, sys, logging
from httplib import HTTPConnection, socket
from 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:])

脚本核心点解释:

1、getattr()是python的内置函数,接收一个对象,可以根据对象属性返回对象的值。

2、compare_site_status()函数是返回的是一个内部定义的函数。

3、map() ,需要2个参数,一个是函数,一个是序列,功能就是将序列中的每个元素应用函数方法。

总结

以上就是这篇文章的全部内容,有需要的朋友们可以参考借鉴。

Python 相关文章推荐
Python利用递归和walk()遍历目录文件的方法示例
Jul 14 Python
Python实现霍夫圆和椭圆变换代码详解
Jan 12 Python
Python实现识别手写数字大纲
Jan 29 Python
python安装模块如何通过setup.py安装(超简单)
May 05 Python
Python实现的序列化和反序列化二叉树算法示例
Mar 02 Python
Python中asyncio模块的深入讲解
Jun 10 Python
Python何时应该使用Lambda函数
Jul 02 Python
django 快速启动数据库客户端程序的方法示例
Aug 16 Python
python文件和文件夹复制函数
Feb 07 Python
Python使用graphviz画流程图过程解析
Mar 31 Python
matlab xlabel位置的设置方式
May 21 Python
virtualenv隔离Python环境的问题解析
Jun 21 Python
Python如何判断数独是否合法
Sep 08 #Python
python框架django基础指南
Sep 08 #Python
python中星号变量的几种特殊用法
Sep 07 #Python
Python 实现 贪吃蛇大作战 代码分享
Sep 07 #Python
python 转换 Javascript %u 字符串为python unicode的代码
Sep 06 #Python
Python 编码处理-str与Unicode的区别
Sep 06 #Python
Python如何获取系统iops示例代码
Sep 06 #Python
You might like
PHP中如何实现常用邮箱的基本判断
2014/01/07 PHP
PHP编程快速实现数组去重的方法详解
2017/07/22 PHP
javascript文件中引用依赖的js文件的方法
2014/03/17 Javascript
setTimeout()递归调用不加引号出错的解决方法
2014/09/05 Javascript
jQuery实现新消息在网页标题闪烁提示
2015/06/23 Javascript
jquery ajax结合thinkphp的getjson实现跨域的方法
2016/06/06 Javascript
jQuery实现区域打印功能代码详解
2016/06/17 Javascript
JS解决iframe之间通信和自适应高度的问题
2016/08/24 Javascript
Javascript中call,apply,bind方法的详解与总结
2016/12/12 Javascript
基于jQuery对象和DOM对象和字符串之间的转化实例
2017/08/08 jQuery
swiper移动端轮播插件(触碰图片之后停止轮播)
2017/12/28 Javascript
Bootstrap-table自定义可编辑每页显示记录数
2018/09/07 Javascript
微信小程序实现跑马灯效果
2020/10/21 Javascript
vue实现简易的双向数据绑定
2020/12/29 Vue.js
对比Python中__getattr__和 __getattribute__获取属性的用法
2016/06/21 Python
Python 实现12306登录功能实例代码
2018/02/09 Python
Django如何配置mysql数据库
2018/05/04 Python
Python中GeoJson和bokeh-1的使用讲解
2019/01/03 Python
关于pandas的离散化,面元划分详解
2019/11/22 Python
python利用google翻译方法实例(翻译字幕文件)
2020/09/21 Python
windows+vscode安装paddleOCR运行环境的步骤
2020/11/11 Python
PyCharm最新激活码PyCharm2020.2.3有效
2020/11/18 Python
PyQt实现计数器的方法示例
2021/01/18 Python
a标签下载链接的简单实现
2016/09/13 HTML / CSS
台湾深度自由行旅游平台:Tripbaa趣吧
2017/10/10 全球购物
澳大利亚音乐商店:Bava’s Music City
2019/05/05 全球购物
英国曼彻斯特宠物用品品牌:Bunty Pet Products
2019/07/27 全球购物
《兰亭集序》教学反思
2014/02/11 职场文书
个人安全承诺书
2014/05/22 职场文书
2014年六一儿童节演讲稿
2014/05/23 职场文书
2014年巴西世界杯口号
2014/06/05 职场文书
依法行政工作汇报
2014/10/28 职场文书
pycharm2021激活码使用教程(永久激活亲测可用)
2021/03/30 Python
聊聊pytorch测试的时候为何要加上model.eval()
2021/05/23 Python
Python Flask请求扩展与中间件相关知识总结
2021/06/11 Python
一篇文章带你掌握SQLite3基本用法
2022/06/14 数据库