Created
April 15, 2017 03:45
-
-
Save sherwind/f24a2b5d723b9611d983e506fff99524 to your computer and use it in GitHub Desktop.
Nagios plugin to check network interface throughput
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# Nagios plugin to check network interface throughput | |
# by Sherwin Daganato, 20170415 | |
use CHI; | |
use Time::HiRes qw(gettimeofday tv_interval); | |
use Cwd qw(realpath); | |
use Monitoring::Plugin; | |
use List::Util qw(max); | |
my $np = Monitoring::Plugin->new( | |
usage => "Usage: %s [ -i interface ] -w threshold -c threshold", | |
version => 1.0, | |
); | |
$np->add_arg( | |
spec => 'interface|i=s', | |
help => 'Network interface (default: eth0)', | |
default => 'eth0' | |
); | |
$np->add_arg( | |
spec => 'warning|w=i', | |
help => 'Exit with WARNING status if either inbound or outbound throughput is more than INTEGER bytes per seconds', | |
required => 1 | |
); | |
$np->add_arg( | |
spec => 'critical|c=i', | |
help => 'Exit with CRITICAL status if either inbound or outbound throughput is more than INTEGER bytes per seconds', | |
required => 1 | |
); | |
$np->getopts; | |
my $stats_dir = sprintf '/sys/class/net/%s/statistics', $np->opts->interface; | |
$np->plugin_die("Network statistics for " . $np->opts->interface . " don't exist") unless -f "$stats_dir/rx_bytes"; | |
my $cache = CHI->new( | |
driver => 'File', | |
namespace => realpath($0), | |
); | |
my $then = $cache->get('then'); | |
if (! defined $then) { | |
$then->{time} = [ gettimeofday() ]; | |
$then->{rx_bytes} = cat_file("$stats_dir/rx_bytes"); | |
$then->{tx_bytes} = cat_file("$stats_dir/tx_bytes"); | |
sleep 1; | |
} | |
my $now; | |
$now->{time} = [ gettimeofday() ]; | |
$now->{rx_bytes} = cat_file("$stats_dir/rx_bytes"); | |
$now->{tx_bytes} = cat_file("$stats_dir/tx_bytes"); | |
$cache->set('then', $now, '60 minutes'); | |
my $elapsed_seconds = tv_interval($then->{time}, $now->{time}); | |
my $rx_bytes_delta = $now->{rx_bytes} - $then->{rx_bytes}; | |
my $tx_bytes_delta = $now->{tx_bytes} - $then->{tx_bytes}; | |
$np->plugin_die('Elapsed time is too short') unless $elapsed_seconds > 0; | |
my $rx_bps = sprintf '%.2f', $rx_bytes_delta / $elapsed_seconds; | |
my $tx_bps = sprintf '%.2f', $tx_bytes_delta / $elapsed_seconds; | |
$np->plugin_exit( | |
return_code => $np->check_threshold(max($rx_bps, $tx_bps)), | |
message => $np->opts->interface . ": rx = $rx_bps B/s; tx = $tx_bps B/s" | |
); | |
exit; | |
sub cat_file { | |
local $/; | |
open (my $fh, '<', $_[0]) || die "can't open $_[0]: $!"; | |
return <$fh>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment