#!/usr/bin/perl -w
## $Id: check_nuttcp.pl 2012-07-06 16:23:55Z ektanoor $
##	ektanoor@telecet.com
##
## Fully based on check_iperf.pl by julien.touche@touche.fr.st
##
## nagios script to check speed between network links
##
## windows or unix, with nuttcp installed and an nuttcp service on target
# nagios: -epn

use strict;

$ENV{'PATH'}='';
$ENV{'BASH_ENV'}='';
$ENV{'ENV'}='';

my ($target,$exit);
#my $nuttcp = "c:\\temp\\nuttcp.exe";
my $nuttcp = "/usr/bin/nuttcp";

if ($#ARGV+1 !=4) {
	usage();
	exit;
} elsif (! -f "$nuttcp") {
	print "didn't find nuttcp here '$nuttcp'.\n";
	exit;
} else {
	$target = $ARGV[1];
}


our ($connect_ok,$speed,$unit,$retrans,$rtt);
$unit='bps';
$connect_ok = 0;
$speed = "UNKNOWN";

my ($maxwarn,$maxcrit,$minwarn,$mincrit,$ms);
$mincrit = $ARGV[2];
if ($mincrit =~ m/([0-9].+):([0-9].+)/) {
	$mincrit = $1;
	$maxcrit = $2;
}
$minwarn = $ARGV[3];
if ($minwarn =~ m/([0-9].+):([0-9].+)/) {
	$minwarn = $1;
	$maxwarn = $2;
}


#print "DEBUG: $nuttcp -c $target -m\n";
open(OUT, "$nuttcp $target |");
while (<OUT>) {
	chomp;
	#print "DEBUG: '$_'\n";
#  107.2194 MB /  10.09 sec =   89.1449 Mbps 0 %TX 4 %RX 48 retrans 0.96 msRTT
	if (m/^\s+[0-9\.]+ MB \/\s+[0-9\.]+ sec =\s+([0-9\.]+) ([A-z]+) [0-9]+ \%TX [0-9]+ \%RX ([0-9]+) retrans ([0-9\.]+) msRTT/) {
#		print "DEBUG: '$_' ; '$1', '$2' \n";
		$connect_ok = 1;
		$speed = $1;
		$unit = $2;
		$retrans = $3;
		$rtt = $4;
		$ms='ms';
	}
}

if ($connect_ok == 0) {
	print "UNKNOWN - nuttcp didn't connect to '$target'.|bd=0$unit\n"; $exit = 3;
} elsif ($speed<$mincrit) {
	print "CRITICAL - nuttcp speed of '$target': $speed ($unit) < $mincrit.|bd=$speed$unit retrans=$retrans rtt=$rtt$ms\n";$exit=2;
} elsif (defined($maxcrit) && $speed > $maxcrit) {
	print "CRITICAL - nuttcp speed of '$target': $speed ($unit) > $maxcrit.|bd=$speed$unit retrans=$retrans rtt=$rtt$ms\n";$exit=2;
} elsif ($speed < $minwarn) {
	print "WARNING - nuttcp speed of '$target': $speed ($unit) < $minwarn.|bd=$speed$unit retrans=$retrans rtt=$rtt$ms\n";$exit=1;
} elsif (defined($maxwarn) && $speed > $maxwarn) {
	print "WARNING - nuttcp speed of '$target': $speed ($unit) > $maxwarn.|bd=$speed$unit retrans=$retrans rtt=$rtt$ms\n";$exit=2;
} else {
	print "OK - nuttcp returns $speed $unit |bd=$speed$unit retrans=$retrans rtt=$rtt$ms\n"; $exit = 0;
}



sub usage {
	print <<EOL
 $0 -H <target host> "Critical speed" "Warning speed": 
 	this plugin returns nuttcp usage

 examples:
	$0 -H <host> 10 15: critical if speed under 10 units
	$0 -H <host> 10 15:50: warning if speed out of 15:50 units
	$0 -H <host> 10:100 15:90
	$0 -H <host> 10:40 15:90
	
EOL

}


exit $exit;

