利用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自定义函数的创建、调用和函数的参数详解
Mar 11 Python
python django事务transaction源码分析详解
Mar 17 Python
python编写朴素贝叶斯用于文本分类
Dec 21 Python
tensorflow学习笔记之mnist的卷积神经网络实例
Apr 15 Python
tensorflow 恢复指定层与不同层指定不同学习率的方法
Jul 26 Python
Python读取YUV文件,并显示的方法
Dec 04 Python
详解python项目实战:模拟登陆CSDN
Apr 04 Python
如何在Django项目中引入静态文件
Jul 26 Python
使用pandas实现连续数据的离散化处理方式(分箱操作)
Nov 22 Python
在tensorflow中实现去除不足一个batch的数据
Jan 20 Python
Python基础之字符串操作常用函数集合
Feb 09 Python
Python Selenium自动化获取页面信息的方法
Aug 31 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
高分R级DC动画剧《哈莉·奎茵》第二季正式预告首发
2020/04/09 欧美动漫
html静态页面调用php文件的方法
2014/11/13 PHP
thinkphp3.2.2实现生成多张缩略图的方法
2014/12/19 PHP
php保存任意网络图片到服务器的方法
2015/04/14 PHP
PHP的Socket通信之UDP通信实例
2015/07/02 PHP
PHP date()格式MySQL中插入datetime方法
2019/01/29 PHP
游戏人文件夹程序 ver 4.03
2006/07/14 Javascript
jQuery toggleClass应用实例(附效果图)
2014/04/06 Javascript
Js实现网页键盘控制翻页的方法
2014/10/30 Javascript
jQuery选择id属性带有点符号元素的方法
2015/03/17 Javascript
jquery拖拽效果完整实例(附demo源码下载)
2016/01/14 Javascript
基于iscroll.js实现下拉刷新和上拉加载效果
2016/11/28 Javascript
遍历json 对象的属性并且动态添加属性的实现
2016/12/02 Javascript
nginx部署访问vue-cli搭建的项目的方法
2018/02/12 Javascript
ES6使用 Array.includes 处理多重条件用法实例分析
2020/03/02 Javascript
vue离开当前页面触发的函数代码
2020/09/01 Javascript
[03:04]2018年度DOTA2玩家最喜爱的主播-完美盛典
2018/12/16 DOTA
python中cPickle用法例子分享
2014/01/03 Python
Python实现windows下模拟按键和鼠标点击的方法
2015/03/13 Python
python抓取百度首页的方法
2015/05/19 Python
python设计模式大全
2016/06/27 Python
python subprocess 杀掉全部派生的子进程方法
2017/01/16 Python
Python入门之三角函数sin()函数实例详解
2017/11/08 Python
python实现壁纸批量下载代码实例
2018/01/25 Python
Django1.9 加载通过ImageField上传的图片方法
2018/05/25 Python
pandas 对每一列数据进行标准化的方法
2018/06/09 Python
python中将\\uxxxx转换为Unicode字符串的方法
2018/09/06 Python
Python安装与基本数据类型教程详解
2019/05/29 Python
简述 Python 的类和对象
2020/08/21 Python
详解HTML5中表单验证的8种方法介绍
2016/12/19 HTML / CSS
英国在线购买轮胎、预订汽车、汽车维修和装配网站:Protyre
2020/04/12 全球购物
业务员岗位职责
2013/11/16 职场文书
如何撰写岗位职责
2014/02/01 职场文书
销售岗位职责范本
2014/06/12 职场文书
优秀员工自荐书
2015/03/06 职场文书
护士自荐信范文(2016推荐篇)
2016/01/28 职场文书