Python实现批量检测HTTP服务的状态


Posted in Python onOctober 27, 2016

用Python实现批量测试一组url的可用性(可以包括HTTP状态、响应时间等)并统计出现不可用情况的次数和频率等。

类似的,这样的脚本可以判断某个服务的可用性,以及在众多的服务提供者中选择最优的。

需求以及脚本实现的功能如下:

  1. 默认情况下,执行脚本会检测一组url的可用性。
  2. 如果可用,返回从脚本所在的机器到HTTP服务器所消耗的时间和内容等信息。
  3. 如果url不可用,则记录并提示用户,并显示不可用发生的时间。
  4. 默认情况下,允许最大的错误次数是200,数目可以自定义,如果达到允许的最大错误次数,则在输出信息的最后,根据每一个url做出错误统计。
  5. 如果用户手动停止脚本,则需要在输出信息的最后,根据每一个url做出错误统计。

脚本中涉及的一些技巧:

  1. 使用gevent并发处理多个HTTP请求,多个请求之间无须等待响应(gevent还有很多使用技巧,可再自行学习);
  2. 使用signal模块捕获信号,如果捕获到则处理并退出,避免主进程接收到KeyboardInterrupt直接退出但无法处理的问题;
  3. 注意留意脚本中关于统计次数方面的小技巧;

脚本运行效果图( 如果图片看不清楚,请选择“在新标签页中打开图片” )如下:

Python实现批量检测HTTP服务的状态

脚本如下:

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:    LinuxBashShellScriptForOps:testNoHttpResponseException,testHttpHostAvailability.py
User:    Guodong
Create Date:  2016/10/26
Create Time:  12:09

Function:
 test Http Host Availability

Some helpful message:
 For CentOS: yum -y install python-devel python-pip; pip install gevent
 For Ubuntu: apt-get -y install python-dev python-pip; pip install gevent
 For Windows: pip install gevent
 """
import signal
import time
import sys
# execute some operations concurrently using python
from gevent import monkey

monkey.patch_all()
import gevent
import urllib2

hosts = ['https://webpush.wx2.qq.com/cgi-bin/mmwebwx-bin/synccheck',
   'https://webpush.wx.qq.com/cgi-bin/mmwebwx-bin/synccheck', ]

errorStopCounts = 200

quit_flag = False
statistics = dict()


def changeQuit_flag(signum, frame):
 del signum, frame
 global quit_flag
 quit_flag = True
 print "Canceled task on their own by the user."


def testNoHttpResponseException(url):
 tryFlag = True
 global quit_flag
 errorCounts = 0
 tryCounts = 0
 global statistics
 globalStartTime = time.time()
 while tryFlag:
  if not quit_flag:
   tryCounts += 1
   print('GET: %s' % url)
   try:
    startTime = time.time()
    resp = urllib2.urlopen(url) # using module 'request' will be better, request will return header info..
    endTime = time.time()
    data = resp.read()
    responseTime = endTime - startTime
    print '%d bytes received from %s. response time is: %s' % (len(data), url, responseTime)
    print "data received from %s at %d try is: %s" % (url, tryCounts, data)
    gevent.sleep(2)
   except urllib2.HTTPError as e:
    errorCounts += 1
    statistics[url] = errorCounts
    currentTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print "HTTPError occurred, %s, and this is %d times(total) occurs on %s at %s." % (
     e, statistics[url], url, currentTime)

    if errorCounts >= errorStopCounts:
     globalEndTime = time.time()
     tryFlag = False
  else:
   globalEndTime = time.time()
   break

 for url in statistics:
  print "Total error counts is %d on %s" % (statistics[url], url)
  hosts.remove(url)
 for url in hosts:
  print "Total error counts is 0 on %s" % url
 globalUsedTime = globalEndTime - globalStartTime
 print "Total time use is %s" % globalUsedTime
 sys.exit(0)


try:
 # Even if the user cancelled the task,
 # it also can statistics the number of errors and the consumption of time for each host.
 signal.signal(signal.SIGINT, changeQuit_flag)

 gevent.joinall([gevent.spawn(testNoHttpResponseException, host) for host in hosts])
except KeyboardInterrupt:
 # Note: this line can NOT be reached, because signal has been captured!
 print "Canceled task on their own by the user."
 sys.exit(0)
Python 相关文章推荐
python远程登录代码
Apr 29 Python
Python设计足球联赛赛程表程序的思路与简单实现示例
Jun 28 Python
python使用pymysql实现操作mysql
Sep 13 Python
Python实现通过继承覆盖方法示例
Jul 02 Python
Python中请不要再用re.compile了
Jun 30 Python
Python封装成可带参数的EXE安装包实例
Aug 24 Python
python hash每次调用结果不同的原因
Nov 21 Python
python中设置超时跳过,超时退出的方式
Dec 13 Python
使用卷积神经网络(CNN)做人脸识别的示例代码
Mar 27 Python
在Python中使用K-Means聚类和PCA主成分分析进行图像压缩
Apr 10 Python
Django+Uwsgi+Nginx如何实现生产环境部署
Jul 31 Python
python爬取网易云音乐热歌榜实例代码
Aug 07 Python
python解决网站的反爬虫策略总结
Oct 26 #Python
Python控制多进程与多线程并发数总结
Oct 26 #Python
Python网络爬虫项目:内容提取器的定义
Oct 25 #Python
Python实现ssh批量登录并执行命令
Oct 25 #Python
详解Python的Lambda函数与排序
Oct 25 #Python
Python脚本实现Web漏洞扫描工具
Oct 25 #Python
python+django快速实现文件上传
Oct 24 #Python
You might like
PHP.MVC的模板标签系统(五)
2006/09/05 PHP
PHP 高手之路(一)
2006/10/09 PHP
PHP 提取图片img标记中的任意属性的简单实例
2013/12/10 PHP
PHP利用APC模块实现文件上传进度条的方法
2015/01/26 PHP
phpstudy默认不支持64位php的解决方法
2017/02/20 PHP
Laravel Intervention/image图片处理扩展包的安装、使用与可能遇到的坑详解
2017/11/14 PHP
php实现生成带二维码图片并强制下载功能
2018/02/24 PHP
JQuery jsonp 使用示例代码
2009/08/12 Javascript
js removeChild 障眼法 可能出现的错误
2009/10/06 Javascript
基于jquery的网页SELECT下拉框美化代码
2010/10/28 Javascript
JavaScript传递变量: 值传递?引用传递?
2011/02/22 Javascript
javascript查找字符串中出现最多的字符和次数的小例子
2013/10/29 Javascript
原生node.js案例--前后台交互
2017/02/20 Javascript
javascript 判断一个对象为数组的方法
2017/05/03 Javascript
jQuery操作css样式
2017/05/15 jQuery
vue路由拦截及页面跳转的设置方法
2018/05/24 Javascript
简单谈谈javascript高级特性
2019/09/04 Javascript
使用 Element UI Table 的 slot-scope方法
2019/10/10 Javascript
微信小程序实现签到弹窗动画
2020/09/21 Javascript
Python3搜索及替换文件中文本的方法
2015/05/22 Python
python简单获取本机计算机名和IP地址的方法
2015/06/03 Python
Python 使用PIL numpy 实现拼接图片的示例
2018/05/08 Python
python主线程捕获子线程的方法
2018/06/17 Python
python对于requests的封装方法详解
2019/01/03 Python
用Python批量把文件复制到另一个文件夹的实现方法
2019/08/16 Python
使用python实现CGI环境搭建过程解析
2020/04/28 Python
Python模拟登录requests.Session应用详解
2020/11/17 Python
HTML5中使用json对象的实例代码
2018/09/10 HTML / CSS
澳大利亚领先的皮肤诊所:Skin Matrix(抗衰老、痤疮专家、药妆护肤)
2018/05/20 全球购物
英国知名小木屋定制网站:Tiger Sheds
2020/03/06 全球购物
Linux如何命名文件--使用文件名时应注意
2014/05/29 面试题
生日庆典策划方案
2014/06/02 职场文书
2014年国庆节庆祝建国65周年比赛演讲稿
2014/09/21 职场文书
委托书格式要求
2015/01/28 职场文书
检察院起诉书
2015/05/20 职场文书
月考总结与反思
2015/10/22 职场文书