How to build a Nagios plugin using a simple example

A Nagios plugin can be built using practically any language. There are only a few requirements:

  1. A set of one or more inputs (parameters) which the Nagios server will send in order to give it essential information to operate (such as which host to monitor, thresholds, etc.)
  2. Text output of the program, showing the result of the check. The first line will be shown in the services preview of the host in the Nagios web interface. Clicking in to the service will show all of the output.
  3. An exit code returned by the plugin program to indicate the results of the check. That is, the current state of the plugin. This will be: “OK”, “Warning”, or “Critical”.

The text below is an example plugin written in Bash which scans a host using nmap and tests the result against a known MD5 hash of the expected output. If the status of any of the ports change, then the MD5 hash will change and return a ‘CRITICAL’ state.

The output of the nmap scan and the hash are printed out by the plugin in all cases and is available by clicking on the service in the web interface.

#!/bin/bash

NMAPOUTPUT=$(nmap -oG - $1 | grep "Ports")

NMAPOUTPUTHASH=$(echo $NMAPOUTPUT | md5sum | cut -d ' ' -f 1)

if [ $NMAPOUTPUTHASH == $2 ]; then
        echo "OK: Hash of nmap portscan consistent."
        STATUS=0
else
        echo "CRITICAL: Hash of nmap portscan inconsistent."
        STATUS=2
fi

echo $NMAPOUTPUT
echo $NMAPOUTPUTHASH

exit $STATUS

This plugin is run using two parameters: hostname and md5sum. In bash, $0 is the name of the program which is being run. $1 is the first parameter, here the hostname. $2 is the second parameter, here the md5sum.

Nagios will interpret the exit status of the plugin as the state of the plugin check. All plugins will return with an exit code of 0, 1, or 2. These correspond to: “OK”, “Warning”, and “Critical”, respectively.

Here is a useful guide on how to configure Nagios to use a new plugin you just wrote: