Nagios WMI 2 – Creating A Perl WMI Script

Nagios WMI 2 – Creating A Perl WMI Script

This section of the installation articles provides the information for creating a simple Perl script to interrogate whether a Windows Service is running over WMI from Nagios.

It is by no means an approved script by Nagios standards but is written using some of the guidelines found here.  The script does achieve the simple result of if the service is Running then it returns an OK to Nagios and for any other reason it returns a CRITICAL.

Of course it could be expanded out so that things like Starting are shown as a WARNING but for the purposes of this script a simple Running / Not Running result was required.

The script:
use strict;

use Getopt::Long;
use lib "/usr/lib64/nagios/plugins";
use utils qw (%ERRORS);

my ($opt_u, $opt_p, $opt_H, $opt_s);

GetOptions (
        "u=s" => \$opt_u, "username" => \$opt_u,
        "p=s" => \$opt_p, "password" => \$opt_p,
        "H=s" => \$opt_H, "hostname" => \$opt_H,
        "s=s" => \$opt_s, "service" => \$opt_s);

my $cmd = `wmic -U wonderland/$opt_u%"$opt_p" //$opt_H "select DisplayName,State,StartMode FROM Win32_Service where DisplayName = '$opt_s'"`;
my $output = $cmd;

if (substr($output, 0, 20) ne "CLASS: Win32_Service")
         print "ERROR: Cannot connect to WMI or service not found\n";
         exit $ERRORS{'CRITICAL'};
my @result = split(/\n/, $output);

my @status = split(/\|/, $result[2]);

if (@status[3] ne "Running")
         print "CRITICAL: " . $opt_s . " Is Not Running\n";
         exit $ERRORS{'CRITICAL'};
         print "OK: " . $opt_s . " Is Running\n";
         exit $ERRORS{'OK'};