#!/usr/bin/perl 
#===============================================================================
#         FILE:  check_cisco_ifs.pl 
#        USAGE:  ./check_cisco_ifs.pl <ip|hostname> <comma separated I/Fs; e.g: 'GigabitEthernet2/10,GigabitEthernet2/11'> <user> <passwd> <enable passwd> <SSH|Telnet> <stop|start|status> [debug]
#  DESCRIPTION:  Perl scriptology for monitoring Cisco I/Fs  
#       AUTHOR:  Jess Portnoy <kernel01@gmail.com> 
#      VERSION:  0.2
#      CREATED:  07/11/2011 10:25:58 AM
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

use lib '.';
use CiscoIOS;
use Data::Dumper;
use English;

$SIG{__DIE__} = sub { print "@_"; exit 3; };

sub analyze
{
	my ($to_print,$if_arr_index)=@_;
	my ($is_if_up,$RC)=(-1,-1);
	my @bad_matches;
	print "Analyzing IOS query results: ";
	while ($to_print=~ m/(.*is up.*)/g){
		$is_if_up++;
		print "$1\n";
	}
	if ($is_if_up == $if_arr_index){
		print "Found ".($is_if_up +1). " I/F up.\n";
		$RC=0;
	# This looks redundant at first glance [why not just "else"?] but we want the last else in case we didn't match these conds.
	}elsif($is_if_up < $if_arr_index){
		push @bad_matches,$1 while $to_print =~ m/(.*is down.*)/g;
		if ($#bad_matches <0){
			print "OK, all I/Fs are up.\n";
			$RC=0;
		}elsif ($#bad_matches < $if_arr_index){
			print "WARNING: found ".($#bad_matches +1) . " I/Fs down: ";
			$RC=1;
		}else{
			print "CRITICAL: all I/Fs are down :(\n";
			$RC=2;
		}
		for my $bad (@bad_matches){
			print "$bad\n";
		}
	}
	if ($RC<0){
		print "UNKNOWN ERROR. Probably no route to Cisco box but check.\n";
		$RC=3;
	}
	return $RC;
}
if ( $#ARGV < 6){
	print "Usage: $0 <ip|hostname> <comma separated I/Fs; e.g: 'GigabitEthernet2/10,GigabitEthernet2/11'> <user> <passwd> <enable passwd> <SSH|Telnet> <stop|start|status> [debug]\n";
	exit (-1);
}
my ($ios_device_ip,$ios_if,$ios_username,$ios_password,$ios_enable_password,$protocol,$cmd,$debug)=@ARGV;
my $box=&ios_connect($ios_device_ip,$ios_username,$ios_password,$ios_enable_password,$protocol,$debug);
my @if_arr;
@if_arr=split /,/, $ios_if;
my @cmd_output;
@cmd_output=&ifstat($box,@if_arr);
my $to_print=Dumper @cmd_output;
my $RC=&analyze($to_print,$#if_arr);
&terminate_session($box);
exit $RC;
