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

 更新时间:2016年10月27日 08:42:34   作者:dgd2010  
本文给大家分享的是一个使用python实现的批量检测web服务可用性的脚本代码,主要功能有测试一组url的可用性(可以包括HTTP状态、响应时间等)并统计出现不可用情况的次数和频率等。

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

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

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

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

脚本中涉及的一些技巧:

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

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

脚本如下:

#!/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持久性管理pickle模块详细介绍

    python持久性管理pickle模块详细介绍

    这篇文章主要介绍了python持久性管理pickle模块详细介绍,本文讲解了什么是持久性、一些经过 pickle 的 Python等内容,并讲给出了18个使用示例,需要的朋友可以参考下
    2015-02-02
  • 详解python路径拼接os.path.join()函数的用法

    详解python路径拼接os.path.join()函数的用法

    os.path.join()函数:连接两个或更多的路径名组件。这篇文章主要介绍了python路径拼接os.path.join()函数的用法,需要的朋友可以参考下
    2019-10-10
  • Python弹出输入框并获取输入值的实例

    Python弹出输入框并获取输入值的实例

    今天小编就为大家分享一篇Python弹出输入框并获取输入值的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06
  • Python中的lstrip()方法使用简介

    Python中的lstrip()方法使用简介

    这篇文章主要介绍了Python中的lstrip()方法使用简介,是Python入门的基础知识,需要的朋友可以参考下
    2015-05-05
  • Python循环结构的应用场景详解

    Python循环结构的应用场景详解

    这篇文章主要介绍了Python循环结构的应用场景详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • python中单下划线与双下划线的区别及说明

    python中单下划线与双下划线的区别及说明

    这篇文章主要介绍了python中单下划线与双下划线的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Python使用execjs执行包含中文参数的JavaScript

    Python使用execjs执行包含中文参数的JavaScript

    爬虫的开发过程中,往往需要对JS进行模拟,简单或者通用的还可以在Python中模拟或者找到对应的第三方库,但是复杂的就可能不好实现了,下面这篇文章主要给大家介绍了关于Python使用execjs执行包含中文参数的JavaScript的相关资料,需要的朋友可以参考下
    2022-03-03
  • python 将Excel转Word的示例

    python 将Excel转Word的示例

    这篇文章主要介绍了python 将Excel转Word的示例,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-03-03
  • Python书单 不将就

    Python书单 不将就

    对于学习Python语言,如何选择合适的Python书单,是不是已经眼花缭乱,不知道该选择哪本好了呢?今天我来为大家分享几本不可错过的Python好书
    2017-07-07
  • Python音频处理库pydub的使用教程详解

    Python音频处理库pydub的使用教程详解

    Pydub是Python音频处理库,可以对音频进行切割、合并、转换、调整音量等操作。本文将对pydub各个知识点和案例进行介绍,需要的可以参考一下
    2023-03-03

最新评论