当前位置: 首页 > 编程笔记 >

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

颛孙正卿
2023-03-14
本文向大家介绍Python实现批量检测HTTP服务的状态,包括了Python实现批量检测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 多线程实现检测服务器在线情况,包括了python 多线程实现检测服务器在线情况的使用技巧和注意事项,需要的朋友参考一下 需要ping一个网段所有机器的在线情况,shell脚步运行时间太长,用python写个多线程ping吧,代码如下: 效果如下: 平一个网段只要2.7s左右,够快!!! 再给大家分享一个检测外网服务器的方法及代码 经常使用python检测服务器是否能pi

  • 本文向大家介绍C++实现简单的HTTP服务器,包括了C++实现简单的HTTP服务器的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了C++实现HTTP服务器的相关代码,供大家参考,具体内容如下 以上就是本文的全部内容,希望对大家的学习有所帮助。

  • 本文向大家介绍Python实现批量下载文件,包括了Python实现批量下载文件的使用技巧和注意事项,需要的朋友参考一下 Python实现批量下载文件 其他网友的方法: 以上便是本文给大家分享的全部内容了,小伙伴们可以测试下哪种方法效率更高呢。

  • 本文向大家介绍Python实现检测服务器是否可以ping通的2种方法,包括了Python实现检测服务器是否可以ping通的2种方法的使用技巧和注意事项,需要的朋友参考一下 好想在2014结束前再赶出个10篇博文来,~(>_<)~,不写博客真不是一个好兆头,至少说明对学习的欲望和对知识的研究都不是那么积极了,如果说这1天的时间我能赶出几篇精致的博文,你们信不信,哈哈,反正我是信了。。。 python

  • 本文向大家介绍Python代码实现http/https代理服务器的脚本,包括了Python代码实现http/https代理服务器的脚本的使用技巧和注意事项,需要的朋友参考一下 一个几百行代码做出http/https代理服务器的脚本,启动即可做http https透明代理使用 python proxy.py 8992 使用非阻塞io模式,性能还可以。 可以和浏览器一样保持长连接,代码有点乱,不管那么

  • 本文向大家介绍python实现canny边缘检测,包括了python实现canny边缘检测的使用技巧和注意事项,需要的朋友参考一下 canny边缘检测原理 canny边缘检测共有5部分组成,下边我会分别来介绍。 1 高斯模糊(略) 2 计算梯度幅值和方向。 可选用的模板:soble算子、Prewitt算子、Roberts模板等等; 一般采用soble算子,OpenCV也是如此,利用soble水平和