#!/usr/local/groundwork/bin/perl

#

# ping_discovery.pl

# v1.0

#

# Copyright 2009 GroundWork Open Source, Inc.

 

use strict;

use warnings;

use Net::hostent;

use Socket;

 

# first make sure we got a valid IP address as the first parameter

if (! defined $ARGV[0]) {

die "Fatal error: input does not include a valid IP address \n";

}

 

if ($ARGV[0] !~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/) {

die "Fatal error: input does not include a valid IP address \n";

}

# predefine all variables

my $hostaddr = $ARGV[0];

my $ping = "";

my $host = "";

my $hostname = "";

my $hostalias = "";

my $hostprofile = "";

my $svcprofile = "";

my $service = "";

my $output = "";

# ping the specified IP address and store the results

$ping = qx(/usr/local/groundwork/nagios/libexec/check_icmp -H $hostaddr) or die;

 

# if we get an OK or WARNING response, start looking for hostname information

if (($ping =~ /^(OK.+)\|/) || ($ping =~ /^(WARNING.+)\|/)) {

# clean the test results

$ping = $1;

chomp ($ping);

 

# see if any hostname information is defined for the host

if ($host = gethost($hostaddr)) {

 

# if the hostname is an FQDN, use the short version

if ($host->name =~ /^(\S+?)\./) {

$hostname = $1;

}

 

else {

$hostname = $host->name;

}

 

# if an alias is defined and is different from the short

# hostname, use it

if ((@{$host->aliases}) && (@{$host->aliases}[0] ne $hostname)) {

$hostalias = @{$host->aliases}[0];

}

 

# otherewise, if the original hostname is an FQDN, use that

# for the alias

elsif ($host->name =~ /^(\S+?)\./) {

$hostalias = $host->name;

}

 

# if all else fails, reuse the hostname for the alias

else {

$hostalias = $hostname;

}

}

# host does not have a known hostname, so reuse the IP address

else {

$hostname = $hostaddr;

$hostalias = $hostaddr;

}

# set the Nagios profile data

$hostprofile = "host-profile-service-ping";

$svcprofile = "service-ping";

$service = "icmp_ping_alive";

# generate the appropriate output for the automation schema definition

# name;;alias;;address;;description;;parent;;profile;;service profile;;service

$output = $hostname . ";;" .

$hostalias . ";;" .

$hostaddr . ";;" .

$ping . ";;" .

";;" .

$hostprofile . ";;" .

$svcprofile . ";;" .

$service ;

}

 

# host did not respond to ping, so return empty response data

# name;;alias;;address;;description;;parent;;profile;;service profile;;service

else {

$output = ";;" .

";;" .

";;" .

";;" .

";;" .

";;" .

";;";

}

 

# return the output

print $output . "\n";

exit;