利用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中使用wxPython开发的一个简易笔记本程序实例
Feb 08 Python
Python程序中使用SQLAlchemy时出现乱码的解决方案
Apr 24 Python
Python获取邮件地址的方法
Jul 10 Python
python获取当前运行函数名称的方法实例代码
Apr 06 Python
Request的中断和ErrorHandler实例解析
Feb 12 Python
浅谈Python中的bs4基础
Oct 21 Python
Python3.6中Twisted模块安装的问题与解决
Apr 15 Python
Python中的四种交换数值的方法解析
Nov 18 Python
Python实现投影法分割图像示例(一)
Jan 17 Python
django执行数据库查询之后实现返回的结果集转json
Mar 31 Python
Python自定义聚合函数merge与transform区别详解
May 26 Python
python批量检查两个对应的txt文件的行数是否一致的实例代码
Oct 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
PHP中的正规表达式(二)
2006/10/09 PHP
CodeIgniter图像处理类的深入解析
2013/06/17 PHP
PHP结合JQueryJcrop实现图片裁切实例详解
2014/07/24 PHP
php查询whois信息的方法
2015/06/08 PHP
WAF的正确bypass
2017/01/05 PHP
PHP-FPM 的管理和配置详解
2019/02/17 PHP
TP5多入口设置实例讲解
2020/12/15 PHP
Aster vs Newbee BO3 第三场2.18
2021/03/10 DOTA
JavaScript高级程序设计(第3版)学习笔记8 js函数(中)
2012/10/11 Javascript
JavaScript(js)设置默认输入焦点(focus)
2012/12/28 Javascript
js实现文件上传表单域美化特效
2015/11/02 Javascript
JavaScript-html标题滚动效果的简单实现
2016/09/08 Javascript
JavaScript中三个等号和两个等号的区别(== 和 ===)浅析
2016/09/22 Javascript
JavaScript中数组常见操作技巧
2017/09/01 Javascript
使用vue-cli创建项目的图文教程(新手入门篇)
2018/05/02 Javascript
Array数组对象中的forEach、map、filter及reduce详析
2018/08/02 Javascript
微信小程序中的店铺评分组件及vue中用svg实现的评分显示组件
2018/11/16 Javascript
vue中实现高德定位功能
2019/12/03 Javascript
vue中可编辑树状表格的实现代码
2020/10/31 Javascript
[01:38]女王驾到——至宝魔廷新尊技能&特效展示
2020/06/16 DOTA
深入理解Python 代码优化详解
2014/10/27 Python
Python中生成器和yield语句的用法详解
2015/04/17 Python
使用python检测主机存活端口及检查存活主机
2015/10/12 Python
Python实现简单的四则运算计算器
2016/11/02 Python
python itchat给指定联系人发消息的方法
2019/06/11 Python
Django模型序列化返回自然主键值示例代码
2019/06/12 Python
PyCharm第一次安装及使用教程
2020/01/08 Python
Python关于拓扑排序知识点讲解
2021/01/04 Python
瀑布模型都有哪些优缺点
2014/06/23 面试题
电气专业应届生求职信
2013/11/01 职场文书
毕业自我鉴定
2013/11/05 职场文书
高中自我鉴定
2013/12/20 职场文书
2015年项目经理工作总结
2015/04/30 职场文书
MySQL索引知识的一些小妙招总结
2021/05/10 MySQL
浅谈Redis 中的过期删除策略和内存淘汰机制
2022/04/03 Redis
GTX1660显卡搭配显示器推荐
2022/04/19 数码科技