用 Python 编写一个nagios监控磁盘负载的插件



清单 8. Python 插件—获取平均负载的完整插件
               
#!/usr/bin/env python

import os
import sys
import getopt

def usage():
    print """Usage: check_getloadavg [-h|--help] [-m|--mode 1|2|3] /
    [-w|--warning level] [-c|--critical level]"

Mode: 1 - last minute ; 2 - last 5 minutes ; 3 - last 15 minutes"
Warning level defaults to 2.0
Critical level defaults to 5.0"""
    sys.exit(3)

try:
    options, args = getopt.getopt(sys.argv[1:],
        "hm:w:c:",
        "--help --mode= --warning= --critical=",
        )
except getopt.GetoptError:
    usage()
    sys.exit(3)

argMode = "1"
argWarning = 2.0
argCritical = 5.0

for name, value in options:
    if name in ("-h", "--help"):
        usage()
    if name in ("-m", "--mode"):
        if value not in ("1", "2", "3"):
            usage()
        argMode = value
    if name in ("-w", "--warning"):
        try:
            argWarning = 0.0 + value
        except Exception:
            print "Unable to convert to floating point value/n"
            usage()
    if name in ("-c", "--critical"):
        try:
            argCritical = 0.0 + value
        except Exception:
            print "Unable to convert to floating point value/n"
            usage()

try:
    (d1, d2, d3) = os.getloadavg()
except Exception:
    print "GETLOADAVG UNKNOWN: Error while getting load average"
    sys.exit(3)

if argMode == "1":
    d = d1
elif argMode == "2":
    d = d2
elif argMode == "3":
    d = d3

if d >= argCritical:
    print "GETLOADAVG CRITICAL: Load average is %.2f" % (d)
    sys.exit(2)
elif d >= argWarning:
    print "GETLOADAVG WARNING: Load average is %.2f" % (d)
    sys.exit(1)
else:
    print "GETLOADAVG OK: Load average is %.2f" % (d)
    sys.exit(0)
   
为了使用这个新的插件,需要使用下面的方法来注册 /etc/nagios-plugins/config/mygetloadavg2.cfg:

清单 9. Python 插件—使用 Nagios 进行注册
               
define command{
        command_name    check_mygetloadavg2
    command_line    /path/to/check_getloadavg2 -m $ARG1$ -w $ARG2$ -c $ARG3$
    }

另外,根据下面的示例,在 services.cfg文件中添加或者更改服务条目。请注意,使用感叹号 !来分隔插件参数。与前面一样,必须在 hosts.cfg配置文件中定义 localhost。

清单 10. 创建一个使用 Python 插件的服务
               
define service{
        use                             service-template
        host_name                       localhost
        service_description             LoadAverage2
        check_period                    24x7
        contact_groups                  server-admins
        notification_options            c,r
        check_command                   check_mygetloadavg2!1!3.0!6.0
        }

你可能感兴趣的:(exception,python,command,service,nagios)