Invoke a shell script execution using nagios

Arya picture Arya · Jul 27, 2015 · Viewed 7.2k times · Source

Hi all I am having a script which restarts all the components(.jar files) present in the server (/scripts/startAll.sh). So whenever my server goes down, I want to invoke the execution of the script using nagios, which is running on different linux server. is it possible to do so? kindly help on How to invoke execution of this script using nagios?

Answer

EE1213 picture EE1213 · Jul 27, 2015

Event Handlers

Nagios and Naemon allow executing custom scripts, both for hosts and for services entering a 'problem state.' Since your implementation is for restarting specific applications, yours will most likely need to be service event handlers.

From Nagios Documentation:

Event handlers can be enabled or disabled on a program-wide basis by using the enable_event_handlers in your main configuration file.

Host- and service-specific event handlers can be enabled or disabled by using the event_handler_enabled directive in your host and service definitions. Host- and service-specific event handlers will not be executed if the global enable_event_handlers option is disabled.


Enabling and Creating Event Handler Commands for a Service or Host

  1. First, enable event handlers by modifying or adding the following line to your Nagios config file.

[IE: /usr/local/nagios/etc/nagios.cfg]:

enable_event_handlers=1

  1. Define and enable an event handler on the service failure(s) that will trigger the script. Do so by adding two event_handler directives inside of the service you've already defined.

[IE: /usr/local/nagios/etc/services.cfg]:

define service{
    host_name       my-server
    service_description my-check
    check_command       my-check-command!arg1!arg2!etc
    ....
    event_handler my-eventhandler
    event_handler_enabled   1
    }
  1. The last step is to create the event_handler command named in step 2, and point it to a script you've already created. There are a few approaches to this (SSH, NRPE, Locally-Hosted, Remotely Hosted). I'll use the simplest method, hosting a BASH script on the monitor system that will connect via SSH and execute:

[IE: /usr/local/nagios/etc/objects/commands.cfg]:

 define command{

        command_name    my-eventhandler

        command_line    /usr/local/nagios/libexec/eventhandlers/my-eventhandler.sh

        }

In this example, the script "my-eventhandler.sh" should use SSH to connect to the remote system, and execute the commands you've decided on.

NOTE: This is only intended as a quick, working solution for one box in your environment. In practice, it is better to create an event handler script remotely, and to use an agent such as NRPE to execute the command while passing a $HOSTNAME$ variable (thus allowing the solution to scale across more than one system). The simplest tutorial I've found for using NRPE to execute an event handler can be found here.