How to create/write Nrpe plugins using BASH/Python
NRPE is a Open source Project from Nagios , which allows you to remotely execute Nagios plugins on other Linux/Unix machines. This is useful to monitor remote machine metrics like CPU, Load, Memory , Disk , IO and many more application metrics. Usually the NRPE service listen on port 5666 and responds to probes from Nagios Server after executing the plugins locally. You can write the nrpe plugins in your favorite language, like bash, python or perl. Just make sure that the plugins are executable for NRPE service . In this article we will explain how to write Nrpe plugins using BASH/Python.
We will write a simple plugin to monitor the number of open files on your machine.
Nagios uses following exit codes from the remote executor to trigger the alert
Exit Code | Status |
0 | OK |
1 | WARNING |
2 | CRITICAL |
3 | UNKNOWN |
Basically, the plugin exit status decides the state of the service. So we need to keep these exit codes as reference while writing the nrpe plugis
Please see the below script which checks the number of open files in the machine and and throw an alert if it is over the threshold
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#!/bin/bash
OK=0
WARNING=1
CRITICAL=2
UNKNOWN=3
WARNING_THESHOLD=2000
CRITICAL_THESHOLD=5000
openfiles= cat /proc/sys/fs/file-nr | awk '{print $1}'
if [ $openfiles –lt $WARNING_THESHOLD ]
then
echo “OK. There are $openfiles Openfiles”
exit $OK
elif [ $openfiles –lt $CRITICAL_THESHOLD ]
then
echo “WARNING. There are $openfiles Openfiles”
exit $WARNING
elif [ $openfiles –gt $CRITICAL_THESHOLD ]
then
echo “CRITICAL. There are $openfiles Openfiles”
exit $CRITICAL
else
echo “UNKNOWN. Not able to calculate the number of openfiles”
exit $UNKNOWN
fi
|
Please copy this script and keep it under libexec folder, inside Nrpe root folder. Make sure you make the script executable
1 | chmod +x /user/local/nagios/libexec/openfiles.sh |
You can test the script by running it
Now add a new check inside the nrpe configuration file . Please add the following lines in the nrpe configuration file
1 | command[check_openfiles]=/user/local/nagios/libexec/openfiles.sh |
Make sure you restart the nrpe service. Once done, you can invoke this script from your nagios server using following command
1 | /usr/local/nagios/libexec/check_nrpe –H IPADDRESS –c check_openfiles |
Same script can be written in Python also
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #!/usr/bin/python import os, sys WARNING_THESHOLD=3000 CRITICAL_THESHOLD=5000 openfiles=os.popen(“cat /proc/sys/fs/file-nr | awk ‘{print $1}'”).readline().strip() openfiles=int(openfiles) if openfiles |