Sunday, September 26, 2010

Nagios: Automatically restart IIS after a CRITICAL alert

You can execute code when a service or host changes state.  These are called event handlers.

  1. Go to the Windows server and create a local user
  2. Create the following script called iisreset.sh in your Nagios plugins directory replacing the username and password in the three locations below



    #!/bin/sh
    #
    # Event handler script for restarting IIS on windows server
    #    Requires a local user on the server with the username and password below
    
    if [ $# -eq 3 ]
    then
            if [ "$1" = "CRITICAL" ]
            then
                    if [ "$2" = "HARD" ]
                    then
                            # Start the service
                            /usr/bin/net rpc service stop W3SVC -I $3 -U User%password >/dev/null
                            sleep 4
                            /usr/bin/net rpc service start W3SVC -I $3 -U User%password >/dev/null 2>&1
                            sleep 4
                            /usr/bin/net rpc service status W3SVC -I $3 -U User%password | grep 'W3SVC'
                            exit 0
                    fi
            fi
    else
            echo "Invalid number of arguments"
            exit 1
    fi
    

  3. Edit your commands.cfg file in the Nagios configuration directory



    define command {
            command_name    iisreset
            command_line    $USER1$/iisreset.sh $SERVICESTATE$ $SERVICESTATETYPE$ $HOSTADDRESS$
            }
    

  4. Add the event handler command to an existing service definition



    define service{
                    host_name                         somehost
                    service_description        HTTP
                    event_handler                  iisreset
                    ...
                    }
    

  5. The script will be called like this.  You can put this in a command line to confirm it will work. /usr/lib/nagios/plugins/iisreset.sh CRITICAL HARD 10.10.0.2
  6. Reload or start Nagios
    /etc/init.d/nagios3 reload

3 comments:

  1. In step 3. Your missing a the dollar sign ($) after $SERVICESTATE.

    Should be $SERVICESTATE$ then all will work.

    Cheers

    ReplyDelete
  2. Hello, great script.

    I followed all the steps and actually works, when i rum the command (iisreset.sh CRITICAL HARD 10.10.0.2) commnads rese my iis server.

    But when called by nagios by event_handler, only sends the command to stop the W3SVC service, and does not send the command to start the service.

    Can yoy help me?

    Sorry for my english, I write form from Brazil. :o)

    ReplyDelete