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自动化测试实例解析
Sep 28 Python
基于python批量处理dat文件及科学计算方法详解
May 08 Python
Python实现html转换为pdf报告(生成pdf报告)功能示例
May 04 Python
python-pyinstaller、打包后获取路径的实例
Jun 10 Python
django框架model orM使用字典作为参数,保存数据的方法分析
Jun 24 Python
python IDLE 背景以及字体大小的修改方法
Jul 12 Python
Djang的model创建的字段和参数详解
Jul 27 Python
python3应用windows api对后台程序窗口及桌面截图并保存的方法
Aug 27 Python
使用python-pptx包批量修改ppt格式的实现
Feb 14 Python
使用Keras训练好的.h5模型来测试一个实例
Jul 06 Python
Python Spyder 调出缩进对齐线的操作
Feb 26 Python
Python开发之QT解决无边框界面拖动卡屏问题(附带源码)
May 27 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
Linux Apache PHP Oracle 安装配置(具体操作步骤)
2013/06/17 PHP
JavaScript prototype属性深入介绍
2012/11/27 Javascript
使用javascript实现Iframe自适应高度
2014/12/24 Javascript
浅析JavaScript中的事件机制
2015/06/04 Javascript
Jquery左右滑动插件之实现超级炫酷动画效果附源码下载
2015/12/02 Javascript
vue调用高德地图实例代码
2017/04/28 Javascript
xmlplus组件设计系列之路由(ViewStack)(7)
2017/05/02 Javascript
浅谈vue中document.getElementById()拿到的是原值的问题
2020/07/26 Javascript
vue打包npm run build时候界面报错的解决
2020/08/13 Javascript
[02:05]2014DOTA2西雅图国际邀请赛 BBC第二天小组赛总结
2014/07/11 DOTA
收集的几个Python小技巧分享
2014/11/22 Python
python定时器(Timer)用法简单实例
2015/06/04 Python
老生常谈Python之装饰器、迭代器和生成器
2017/07/26 Python
Python实现读写sqlite3数据库并将统计数据写入Excel的方法示例
2017/08/07 Python
linux环境下的python安装过程图解(含setuptools)
2017/11/22 Python
Python爬虫框架Scrapy实例代码
2018/03/04 Python
Python基于FTP模块实现ftp文件上传操作示例
2018/04/23 Python
python3下使用cv2.imwrite存储带有中文路径图片的方法
2018/05/10 Python
python 获取当天凌晨零点的时间戳方法
2018/05/22 Python
使用Python进行目录的对比方法
2018/11/01 Python
PyQt5固定窗口大小的方法
2019/06/18 Python
python通过TimedRotatingFileHandler按时间切割日志
2019/07/17 Python
python进程间通信Queue工作过程详解
2019/11/01 Python
Tensorflow tf.nn.depthwise_conv2d如何实现深度卷积的
2020/04/20 Python
Python定义一个Actor任务
2020/07/29 Python
Python脚本打包成可执行文件过程解析
2020/10/20 Python
python3.9实现pyinstaller打包python文件成exe
2020/12/13 Python
Html5 Canvas 实现一个“刮刮乐”游戏
2019/09/05 HTML / CSS
解决html5中的video标签ios系统中无法播放使用的问题
2020/08/10 HTML / CSS
Why we need EJB
2016/10/20 面试题
自主招生推荐信范文
2014/05/10 职场文书
超市仓管员岗位职责范本
2014/09/18 职场文书
安全月宣传标语
2014/10/07 职场文书
个人先进事迹总结
2015/02/26 职场文书
好员工观后感
2015/06/17 职场文书
使用Pytorch实现two-head(多输出)模型的操作
2021/05/28 Python