#!/usr/bin/perl -w
############################## check_snmp_hsrp ##############
# Version : 0.1
# Date : Feb 20 2012
# Author  : Abinadi Rendon (abi@azuretek.com)
# Help : http://www.abirendon.com
# Licence : GPL - http://www.fsf.org/licenses/gpl.txt
# Based on VRRP Script by: Patrick Proy (patrick at proy.org)
#################################################################
#
# Help : ./check_snmp_hsrp.pl -h
#

use strict;
use Net::SNMP;
use Getopt::Long;

# Nagios specific

use lib "/usr/local/nagios/libexec";
use utils qw(%ERRORS $TIMEOUT);
#my $TIMEOUT = 15;
#my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);

# SNMP Datas

######### Cisco (standard ???)
my $all_hsrp  = "1.3.6.1.4.1.9.9.106";
my $cisco_base_hsrp = "1.3.6.1.4.1.9.9.106.1.2.1.1";   # oid for hsrp
my $cisco_hsrp_oper = "1.3.6.1.4.1.9.9.106.1.2.1.1.15";   # hsrp operational status
my $cisco_hsrp_admin ="1.3.6.1.4.1.9.9.106.1.2.1.1.17";   # hsrp admin status
my $cisco_hsrp_prio = "1.3.6.1.4.1.9.9.106.1.2.1.1.3";   # hsrp priority

######### Make an array
my %base_hsrp = ("cisco",$cisco_base_hsrp);
my %hsrp_oper = ("cisco",$cisco_hsrp_oper);
my %hsrp_admin =("cisco",$cisco_hsrp_admin);
my %hsrp_prio = ("cisco",$cisco_hsrp_prio);

my %state_master=("cisco",6);
my %state_backup=("cisco",5);

# Globals

my $Version='0.1';

my $o_host =    undef;          # hostname
my $o_community = undef;        # community
my $o_version2  = undef;        #use snmp v2c
my $o_port =    161;            # port
my $o_help=     undef;          # wan't some help ?
my $o_verb=     undef;          # verbose mode
my $o_version=  undef;          # print version
my $o_state=    undef;          # Check master or backup state for ok
my $o_clustnum= undef;          # number of cluster members
my $o_clustprct=        undef;  # Max % assigned to one cluster.
my $o_long=             undef;          # Make output long
my $o_timeout=  5;              # Default 5s Timeout

# SNMPv3 specific
my $o_login=    undef;          # Login for snmpv3
my $o_passwd=   undef;          # Pass for snmpv3
my $v3protocols=undef;  # V3 protocol list.
my $o_authproto='md5';          # Auth protocol
my $o_privproto='des';          # Priv protocol
my $o_privpass= undef;          # priv password

# functions

sub p_version { print "check_snmp_hsrp version : $Version\n"; }

sub print_usage {
    print "Usage: $0 [-v] -H <host> -C <snmp_community> [-2] | (-l login -x passwd [-X pass -L <authp>,<privp>]) -s <master|backup|num,%> [-p <port>] [-t <timeout>] [-V]\n";
}

sub isnnum { # Return true if arg is not a number
  my $num = shift;
  if ( $num =~ /^(\d+\.?\d*)|(^\.\d+)$/ ) { return 0 ;}
  return 1;
}

sub help {
   print "\nSNMP HSRP Monitor for Nagios version ",$Version,"\n";
   print "(c)2012 Author : Abinadi Rendon\n\n";
   print_usage();
   print <<EOT;
-v, --verbose
   print extra debugging information (including interface list on the system)
-h, --help
   print this help message
-H, --hostname=HOST
   name or IP address of host to check
-C, --community=COMMUNITY NAME
   community name for the host's SNMP agent (implies v1 protocol)
-2, --v2c
   Use snmp v2c
-l, --login=LOGIN ; -x, --passwd=PASSWD
   Login and auth password for snmpv3 authentication
   If no priv password exists, implies AuthNoPriv
-X, --privpass=PASSWD
   Priv password for snmpv3 (AuthPriv protocol)
-L, --protocols=<authproto>,<privproto>
   <authproto> : Authentication protocol (md5|sha : default md5)
   <privproto> : Priv protocole (des|aes : default des)
-P, --port=PORT
   SNMP port (Default 161)
-s, --state=master|backup|num,%
   Nokia ipso clustering : number of members, max % assigned to nodes.
   Other : check HSRP interface to be master or backup
-g, --long
   Make output long even is all is OK
-t, --timeout=INTEGER
   timeout for SNMP in seconds (Default: 5)
-V, --version
   prints version number
EOT
}

# For verbose output
sub verb { my $t=shift; print $t,"\n" if defined($o_verb) ; }

# Get the alarm signal (just in case snmp timout screws up)
$SIG{'ALRM'} = sub {
     print ("ERROR: Alarm signal (Nagios time-out)\n");
     exit $ERRORS{"UNKNOWN"};
};

sub check_options {
    Getopt::Long::Configure ("bundling");
    GetOptions(
        'v'     => \$o_verb,            'verbose'       => \$o_verb,
        'h'     => \$o_help,            'help'          => \$o_help,
        'H:s'   => \$o_host,            'hostname:s'    => \$o_host,
        'p:i'   => \$o_port,            'port:i'        => \$o_port,
        'C:s'   => \$o_community,       'community:s'   => \$o_community,
        't:i'   => \$o_timeout,         'timeout:i'     => \$o_timeout,
        'V'     => \$o_version,         'version'       => \$o_version,
        'g'     => \$o_long,            'long'          => \$o_long,
        '2'     => \$o_version2,        'v2c'           => \$o_version2,
        'l:s'   => \$o_login,           'login:s'       => \$o_login,
        'x:s'   => \$o_passwd,          'passwd:s'      => \$o_passwd,
        'X:s'   => \$o_privpass,                'privpass:s'    => \$o_privpass,
        'L:s'   => \$v3protocols,               'protocols:s'   => \$v3protocols,
        's:s'   => \$o_state,           'state:s'       => \$o_state
    );
    if (defined ($o_help) ) { help(); exit $ERRORS{"UNKNOWN"}};
    if (defined($o_version)) { p_version(); exit $ERRORS{"UNKNOWN"}};
    if ( ! defined($o_host) ) # check host and filter
        { print_usage(); exit $ERRORS{"UNKNOWN"}}
    # check snmp information
    if ( !defined($o_community) && (!defined($o_login) || !defined($o_passwd)) )
          { print "Put snmp login info!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
        if ((defined($o_login) || defined($o_passwd)) && (defined($o_community) || defined($o_version2)) )
          { print "Can't mix snmp v1,2c,3 protocols!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
        if (defined ($v3protocols)) {
          if (!defined($o_login)) { print "Put snmp V3 login info with protocols!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
          my @v3proto=split(/,/,$v3protocols);
          if ((defined ($v3proto[0])) && ($v3proto[0] ne "")) {$o_authproto=$v3proto[0];        }       # Auth protocol
          if (defined ($v3proto[1])) {$o_privproto=$v3proto[1]; }       # Priv  protocol
          if ((defined ($v3proto[1])) && (!defined($o_privpass))) {
            print "Put snmp V3 priv login info with priv protocols!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}
        }

}

########## MAIN #######

check_options();

# Check gobal timeout if snmp screws up
if (defined($TIMEOUT)) {
  verb("Alarm at $TIMEOUT");
  alarm($TIMEOUT);
} else {
  verb("no timeout defined : $o_timeout + 10");
  alarm ($o_timeout+10);
}

# Connect to host
my ($session,$error);
if ( defined($o_login) && defined($o_passwd)) {
  # SNMPv3 login
  verb("SNMPv3 login");
    if (!defined ($o_privpass)) {
  verb("SNMPv3 AuthNoPriv login : $o_login, $o_authproto");
    ($session, $error) = Net::SNMP->session(
      -hostname         => $o_host,
      -version          => '3',
      -username         => $o_login,
      -authpassword     => $o_passwd,
      -authprotocol     => $o_authproto,
      -timeout          => $o_timeout
    );
  } else {
    verb("SNMPv3 AuthPriv login : $o_login, $o_authproto, $o_privproto");
    ($session, $error) = Net::SNMP->session(
      -hostname         => $o_host,
      -version          => '3',
      -username         => $o_login,
      -authpassword     => $o_passwd,
      -authprotocol     => $o_authproto,
      -privpassword     => $o_privpass,
          -privprotocol => $o_privproto,
      -timeout          => $o_timeout
    );
  }
} else {
        if (defined ($o_version2)) {
                # SNMPv2 Login
                verb("SNMP v2c login");
                  ($session, $error) = Net::SNMP->session(
                 -hostname  => $o_host,
                 -version   => 2,
                 -community => $o_community,
                 -port      => $o_port,
                 -timeout   => $o_timeout
                );
        } else {
          # SNMPV1 login
          verb("SNMP v1 login");
          ($session, $error) = Net::SNMP->session(
                -hostname  => $o_host,
                -community => $o_community,
                -port      => $o_port,
                -timeout   => $o_timeout
          );
        }
}
if (!defined($session)) {
   printf("ERROR opening session: %s.\n", $error);
   exit $ERRORS{"UNKNOWN"};
}

########### get HSRP table ############

# Get HSRP table
my $resultat;
if (Net::SNMP->VERSION < 4) {
  $resultat = $session->get_table( $base_hsrp{'cisco'} );
} else {
  $resultat = $session->get_table( Baseoid => $base_hsrp{'cisco'} );
}
if (!defined($resultat)) {
   printf("ERROR: Description table : %s.\n", $session->error);
   $session->close;
   exit $ERRORS{"UNKNOWN"};
}
$session->close;

my @vrid=undef;
my $nvrid=0;
my $oid0=undef;
my @oid=undef;
my $key=undef;

foreach $key ( keys %$resultat) {
 if ( $key =~ /$hsrp_oper{'cisco'}/){
	# Get rid of the hsrp oper part
	$key =~ s/$hsrp_oper{'cisco'}\.//;

	@oid=split (/\./,$key);
	$vrid[$nvrid]=pop(@oid);
	$oid0=pop(@oid);
	while ( defined ($oid0)) {
			#print($oid0, " ", $nvrid, " ", $vrid[$nvrid], "\n");
	   $vrid[$nvrid] = $oid0 . "." . $vrid[$nvrid];
	   $oid0=pop(@oid);
	}
	verb("Added vrid $vrid[$nvrid]");
	$nvrid++;
 }
}

if ( $nvrid == 0 )
{ printf("No vrid found : CRITICAL\n");exit $ERRORS{"CRITICAL"};}

my $ok=0;
my $value;
my $output=undef;
my $vrid_out;
for (my $i=0;$i<$nvrid;$i++) {
   $output .= ", " if  (defined($output));
   # Get last part of oid to output the vrid
   $vrid_out = $vrid[$i];
   $vrid_out =~ s/.*\.//;
   $output .= "$vrid_out(";
   # Get the state
   $key=$hsrp_oper{'cisco'}.".".$vrid[$i];

   $value = ($$resultat{$key} == $state_master{'cisco'}) ? "master" :
            ($$resultat{$key} == $state_backup{'cisco'}) ? "backup" : "initialise : ".$$resultat{$key};
   $output.=$value . "/";
   ($value eq $o_state) && $ok++;
   # Get the administrative status
   $key= $hsrp_admin{'cisco'} . "." . $vrid[$i];
   $value = ($$resultat{$key} == 1) ? "up" : "down";
   $output.= $value . "/";
   ($value eq "up" ) && $ok++;
   
   # Get the priority
   $key=$hsrp_prio{'cisco'}.".".$vrid[$i];
   $value = $$resultat{$key};
   $output.=$value . ")";
}

verb("verif : $ok");

if ( $ok == (2*$nvrid) ) {
   if (defined($o_long)) {
      printf("Vrid : %s : %s %s : OK\n",$output,$nvrid,$o_state) ;
   } else {
     printf("%s vrid %s :OK\n",$nvrid,$o_state) ;
   }
   exit $ERRORS{"OK"}
}
printf("Vrid : %s : not all %s : NOK\n",$output,$o_state);
exit $ERRORS{"CRITICAL"};
