Custom nagios plugins in python

For monitoring different service and function you may need to build some custom monitoring plugins. I have some build for nrpe and will work with both nagios and icinga.
This script will do and mysql check and then send the data back and also start graphing the data back if you use pnp4nagios 🙂

Every plugin must have two things.

1. an exit code thet will say the state of the plugin (OK.Critical,warning) <- this will generate the alerts

  • 1 = ok
  • 2= Critical
  • 3=Warnings
  • 4= unknown

 

2. Some text to abaout the plugin saying for exampel disk space.

 

Here below is my small script that will de some db qestions ans return the result to nagios. If the values return is under 0 then it will exit in state 2 and then nagios will alert.

 

#!/usr/bin/env python
#Mysql stats
#Get stats from mysql server
#then prints the stats to icinga to process
import MySQLdb
from datetime import date, timedelta
import datetime
import sys
'''
MYSQL
'''
mysqlhost="localhost"
mysqluser="monitor"
mysqlpass="XXXXXXX"
mysqldb="db"
def mysql_query(sql):
 '''
 run an mysql mysql_query
 '''
 try:
 con = None
 con = MySQLdb.Connection(mysqlhost, mysqluser,
 mysqlpass, mysqldb)
 curs = con.cursor()
 curs.execute(sql)
 con.commit()
 back=[]
 for value in curs:
 back.append(value[0])
 return back
 except MySQLdb.Error, e:
 print "Error in MYSQL {0} : {1}".format(e.args[0], e.args[1])
 sys.exit(1)
 finally:
 if con:
 con.close()

#mysql to run on the mysql server
qery="""SELEC your own super mysql qery and the group by"""

#Send mysql to server
back =mysql_query(qery)

#Testing result and building string back to nagios
if back[0] <= 30:
 print "CRITICAL | 'value'="+str(back[0])+" 'value'="+str(back[1])
 sys.exit(2)
else:
 print "OK: | 'value'="+str(back[0])+" 'value'="+str(back[1])
 sys.exit(0)