I’ve just started to rewrite my sh written Nagios Plugins in Python, mainly to get a feeling for writing Python code. First steps with writing object-orientated code were… “not so good, Al!” as Weezer would have said to this. Therefore I’ve began with some lines of functional programming. That’ll do the job for now.
Below you’ll see a rudimentary plugin to check the Apache’s server-status page. Note that it will never go critical at this time. I was just playing around with retrieving a file, putting the content into a dictionary and then transforming it to a proper output which Nagios would understand.
I’ll do more work on this within the next days, expect an update here soon. And if you have any suggestions what could have been done better, let me know.
#!/usr/bin/env python import sys import urllib from optparse import OptionParser stateOK = 0 stateWARN = 1 stateCRIT = 2 stateUNK = 3 parser = OptionParser() parser.add_option( "-H", "--hostname", type="string", dest="hostname", default="localhost", help="Sets the hostname to check.") parser.add_option( "-p", "--port", type="int", dest="port", default=80, help="Sets the port of the host to check.") (options, args) = parser.parse_args() hostname = options.hostname port = options.port def retrieve_status_page(): statusPage = "http://%s:%s/server-status?auto" % (hostname, port) retrPage = urllib.urlretrieve(statusPage, '/tmp/server-status.log') def parse_status_page(): file = open('/tmp/server-status.log', 'r') line = file.readline() dictStatus = {} counter = 1 while line: if "Total Accesses:" in line: key = "totalAcc" elif "Total kBytes:" in line: key = "totalKb" elif "Uptime:" in line: key = "uptime" elif "ReqPerSec:" in line: key = "reqPSec" elif "BytesPerSec:" in line: key = "bytesPSec" elif "BytesPerReq:" in line: key = "bytesPReq" elif "BusyWorkers:" in line: key = "busyWkrs" elif "IdleWorkers:" in line: key = "idleWkrs" else: key = str(counter) line = line.strip() dictStatus[key] = line counter = counter + 1 line = file.readline() return dictStatus def transform_dict(resParse): totalAcc = int(resParse['totalAcc'].strip(" Total Accesses:")) totalKb = float(resParse['totalKb'].strip(" Total kBytes:")) uptime = int(resParse['uptime'].strip(" Uptime:")) reqPSec = float(resParse['reqPSec'].strip(" ReqPerSec:")) + 0 bytesPSec = float(resParse['bytesPSec'].strip(" BytesPerSec:")) if resParse.has_key('bytesPReq'): bytesPReq = float(resParse['bytesPReq'].strip(" BytesPerReq:")) busyWkrs = int(resParse['busyWkrs'].strip(" BusyWorkers:")) idleWkrs = int(resParse['idleWkrs'].strip(" IdleWorkers:")) return [reqPSec, busyWkrs, idleWkrs] retrieve_status_page() resParse = parse_status_page() result = transform_dict(resParse) print "OK: Apache serves %f requests per second. %i busy workers, %i worker " \ "idle." % (result[0], result[1], result[2]) exit(0)
[...] « Porting my Nagios Plugins to Python [...]