Generic SNMP

From Notes

Jump to: navigation, search
#!/usr/bin/perl -w
# Query an arbitrary OID
use strict;
use Net::SNMP;
use Getopt::Long;

use vars qw( $session $result $error $opt_host $opt_comm $opt_oid );

GetOptions(
       'H:s'   =>      \$opt_host,     'hostname:s'    =>      \$opt_host,
       'C:s'   =>      \$opt_comm,     'community:s'   =>      \$opt_comm,
       'o:s'   =>      \$opt_oid,      'oid:s' =>      \$opt_oid
       );

if( ! $opt_host || ! $opt_comm || ! $opt_oid ) {
       &usage();
       exit 3;
}

($session,$error) = Net::SNMP->session(Hostname => $opt_host,
                                       Community => $opt_comm);
die "session error: $error" unless ($session);

$result = $session->get_request("$opt_oid");

die "request error: ".$session->error unless (defined $result);

$session->close;

if( defined($result->{"$opt_oid"}) ) {
       print $result->{"$opt_oid"}, "\n";
       if ($result->{"$opt_oid"} =~ /^WARNING/) {
               exit 1;
       } elsif ($result->{"$opt_oid"} =~ /^CRITICAL/) {
                exit 2;
       } elsif ($result->{"$opt_oid"} =~ /^OK/) {
                exit 0;
       }
} else {
       print "WARNING: unknown/invalid response from snmp agent on $opt_host\n";
       exit 3;
}

sub usage() {
       print <<EOF

       Usage: $0 -H <hostname> -C <community_string> -o <oid>
EOF
}
Personal tools