nagios检测http和https的插件,python检测http和https的插件

一个检测http和https状态和返回时间的程序,nagios可以使用的插件

代码中饱含注释, 如果不明之处和认为有错误的地方, 请各位指出

#!/bin/env python
#coding:utf8
#########################################################################
#
#File name: check_http_status.py
#Description: 利用python的pycurl模块,获取url的返回状态和返回时间
#Author:pangli
#mail:[email protected]
#
#########################################################################
import pycurl
import fcntl
import sys
import os
import StringIO
import time
from optparse  import OptionParser

TIME = int(time.time())
data_path = os.path.split(os.path.realpath(__file__))[0] + "/http_data/"
#判断数据文件夹是否存在
if not os.path.isdir(data_path):
    os.makedirs(data_path)

#返回代码:200-207成功状态,300-307重定向状态,此处也划分到成功里
code_rule = [200, 201, 202, 203, 204, 205, 206, 207, 300, 301, 302, 303, 304, 305, 306, 307]
usage = "python %(script_name)s -u <url|ipaddress> -w <connectTime,totalTime> -c <connectTime,totalTime> -t <http|https>"

parser = OptionParser(usage=usage % {"script_name" : sys.argv[0]})
parser.add_option("-u", "--url", dest="url", help="url or ipaddress")
parser.add_option("-t", "--type", dest="type", help="transport protocols type,http|https")
parser.add_option("-w", "--warning", dest="w_value", help="alarm value(warning)")
parser.add_option("-c", "--critical", dest="c_value", help="alarm value(critical)")

option,args = parser.parse_args()
if option.url == -1 or option.w_value == -1 or option.c_value == -1 or option.type == -1:
    parser.print_help()
    sys.exit(3)

def http_url_req(url):
    try:
        buf = StringIO.StringIO()
        status = dict()
        #去掉用户输入的url头
        format_url = url.replace("http://", "")
        req = pycurl.Curl()
        #perform返回写入缓存忽略掉
        req.setopt(req.WRITEFUNCTION, buf.write)
        #设置请求的URL
        req.setopt(req.URL,"http://" + format_url)
        #设置连接超时
        req.setopt(req.TIMEOUT,5)
        #执行请求
        req.perform()
        status["return_code"] = req.getinfo(pycurl.HTTP_CODE)
        status["con_time"] = float("%0.3f" % req.getinfo(pycurl.CONNECT_TIME))
        status["tol_time"] = float("%0.3f" % req.getinfo(pycurl.TOTAL_TIME))
        req.close()
        return status
    except pycurl.error,e:
        print "The http status  : CRITICAL | connect failed "
        sys.exit(2)
    except Exception, e:
        print str(e)
        sys.exit(3)

def https_url_req(url):
    try:
        buf = StringIO.StringIO()
        status = dict()
        #去掉用户输入的url头
        format_url = url.replace("https://", "")
        req = pycurl.Curl()
        #perform返回写入缓存忽略掉
        req.setopt(req.WRITEFUNCTION, buf.write)
        #忽略证书检查
        req.setopt(req.SSL_VERIFYPEER, 0)
        #忽略主机验证
        req.setopt(req.SSL_VERIFYHOST, 0)
        #设置请求的URL
        req.setopt(req.URL,"https://" + format_url)
        #设置超时连接
        req.setopt(req.TIMEOUT,5)
        #执行请求
        req.perform()
        status["return_code"] = req.getinfo(pycurl.HTTP_CODE)
        status["con_time"] = float("%0.3f" % req.getinfo(pycurl.CONNECT_TIME))
        status["tol_time"] = float("%0.3f" % req.getinfo(pycurl.TOTAL_TIME))
        req.close()
        return status
    except pycurl.error:
        print "The https status  : CRITICAL | connect failed "
        sys.exit(2)
    except Exception, e:
        print str(e)
        sys.exit(3)

#判断报警状态
def alarm(**params):
    w = dict()
    c = dict()
    print_result  = "The http status  : %(status)s | URL=%(ip)s http_return_code=%(return_code)s connect_time=%(c_time)s total_time=%(t_time)s"
    code = params["return_code"]
    con_time = round(params["con_time"],3)
    tol_time = round(params["tol_time"],3)
    URL = params["url"]
    w["cTime"],w["tTime"] = [float(each) for each in (option.w_value).split(",")]
    c["cTime"],c["tTime"] = [float(each) for each in (option.c_value).split(",")]
    #报警判断
    if cmp(con_time,c["cTime"]) >= 0 or cmp(tol_time,c["tTime"]) >= 0 or code not in code_rule:
        print print_result % {"status":"CRITICAL","ip":URL, "return_code":code,"c_time":con_time,"t_time":tol_time}
        sys.exit(2)
    
    elif cmp(con_time,w["cTime"]) >= 0 or cmp(tol_time,w["tTime"]) >= 0 or code not in code_rule:
        print print_result % {"status":"WARNING","ip":URL, "return_code":code,"c_time":con_time,"t_time":tol_time} 
        sys.exit(1)

    else:
        print print_result % {"status":"OK","ip":URL,"return_code":code,"c_time":con_time,"t_time":tol_time}
        sys.exit(0)

if __name__ == ‘__main__‘:
    url = option.url
    
    if option.type == "http":
        return_data = http_url_req(url)
        alarm(return_code = return_data["return_code"],
            url=option.url,
            con_time = return_data["con_time"],
            tol_time = return_data["tol_time"])
    elif option.type == "https":
        return_data = https_url_req(url)
        alarm(return_code = return_data["return_code"],
            url=option.url,
            con_time = return_data["con_time"],
            tol_time = return_data["tol_time"])
    else:
        print "ERROR: transport protocols type error"
        parser.print_help()
        sys.exit(3)

执行结果展示

时间: 2024-08-02 00:01:54

nagios检测http和https的插件,python检测http和https的插件的相关文章

Notepad++插件Python Script和Emmet的安装使用教程(转载)

安装插件Python Script和Emmet: 最近在做一个项目,涉及到大量的HTML.CSS代码的编写,手动写代码效率实在是低下.于是想搜索一下,有没有Notepad++插件可以支持自动生成的,果不其然还真有.Emmet,这款神器其实就是 Zen Coding的升级版,它可以极大的提高代码编写的效率,并提供了一种非常简练的语法规则,立刻生成对应的 HTML 结构或者 CSS代码,同时还有多种实用的功能帮助进行前端开发. Emmet支持多种编辑器,如Sublime Text 2,TextMat

Python | 安装和配置智能提示插件Anaconda (转)

作为Python开发环境的Sublime Text 3,有了Anaconda就会如虎添翼.Anaconda是目前最流行也是最有威力的Python代码提示插件. 工具/原料 Sublime Text 3 build3103 插件安装 1 我们使用Sublime Text插件安装工具package control来安装,怎么安装package control这个插件大家参考下面的应用文章 4Sublime Text 3 怎么安装插件 2 好,现在打开package control菜单,输入insta

atom下python好用的几个插件

atom下python好用的几个插件 atom-beautify 代码优化 atom-python-run 运行 autocomplete-python 代码补全 file-icons 图标优化 highlight-selected 选择高亮 hyperclick 跳转定义 minimap 小视图 原文地址:https://www.cnblogs.com/Huzr/p/9102000.html

人脸检测真的不难,50行Python代码就能实现人脸检测

Python现在非常火,语法简单而且功能强大,很多同学都想学Python!所以小的给各位看官们准备了高价值Python学习视频教程,都放在了文章结尾,欢迎前来领取! *注意:全文代码可以滑动查看 现在的人脸识别技术已经得到了非常广泛的应用,支付领域.身份验证.美颜相机里都有它的应用.用iPhone的同学们应该对下面的功能比较熟悉. iPhone的照片中有一个"人物"的功能,能够将照片里的人脸识别出来并分类,背后的原理也是人脸识别技术. 这篇文章主要介绍怎样用Python实现人脸检测.人

python检测linux进程是否运行

python检测linux下运行的进程 # -*- coding:utf8 -*- import subprocess import sys status_ok = 0 status_critical = 2 def c(d_name):     cmd = 'ps -ef|grep %s|grep -v "grep"' % d_name     p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)     if p

python检测手机号码是否合法

1 !/usr/bin/python 2 #encoding:utf-8 3 #这是一个用来检测用户输入手机号码是否合法的小脚本. 4 5 def phonecheck(s): 6 #号码前缀,如果运营商启用新的号段,只需要在此列表将新的号段加上即可. 7 phoneprefix=['130','131','132','133','134','135','136','137','138','139','150','151','152','153','156','158','159','170',

python检测文件的MD值

使用hashlib模块,可对文件MD5一致性加密验证: #python 检测文件MD5值 #python version 2.6 import hashlib import os,sys #简单的测试一个字符串的MD5值 def GetStrMd5(src): m0=hashlib.md5() m0.update(src) print m0.hexdigest() pass #大文件的MD5值 def GetFileMd5(filename): if not os.path.isfile(fil

使用python检测一个设备是否ping的通

使用python检测一个设备是否ping的通 一,subprocess以及常用的封装函数 运行python的时候,我们都是在创建并运行一个进程.像Linux进程那样,一个进程可以fork一个子进程,并让这个子进程exec另外一个程序.在Python中,我们通过标准库中的subprocess包来fork一个子进程,并运行一个外部的程序. subprocess 包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所以我们可以根据需要来从中选取一个使用.另外subprocess还提供了

python检测服务器是否ping通

好想在2014结束前再赶出个10篇博文来,~(>_<)~,不写博客真不是一个好兆头,至少说明对学习的欲望和对知识的研究都不是那么积极了,如果说这1天的时间我能赶出几篇精致的博文,你们信不信,哈哈,反正我是信了... python检测服务器是否ping通的2种方法 1.第一种比较挫,就是用ping,python调用shell,这个适用于较少的服务器数量,几百台已经很慢了(当然是说python同步的方法,要是nodejs异步方式还是很快的,但是nodejs CPU计算不行,所以尝试了下只能200台