Net: : SNMP eksempel get bulk request

From Teknologisk videncenter
Jump to: navigation, search
#!/usr/bin/perl -w
use strict;

use Net::SNMP qw(:snmp);

my $oidCount=0;
my ($session, $error) = Net::SNMP->session(
   -version     => 'snmpv2c',
   -nonblocking => 1,
   -hostname   => shift || "192.168.22.202",
   -community   => shift || 'public',
   -port        => shift || 161
);

if (!defined($session)) {
   printf("ERROR: %s.\n", $error);
   exit 1;
}

my $ifTable = '1.3.6.1';

my $result = $session->get_bulk_request(
   -callback       => [\& bygTabel, {}],
   -maxrepetitions => 100,
   -varbindlist    => [$ifTable]
);

if (!defined($result)) {
   printf("ERROR: %s.\n", $session->error);
   $session->close;
   exit 1;
}

snmp_dispatcher();

$session->close;

exit 0;

sub bygTabel
{
   my ($session, $table) = @_;

   if (!defined($session->var_bind_list)) {

      printf("ERROR: %s\n", $session->error);

   } else {

      # Loop through each of the OIDs in the response and assign
      # the key/value pairs to the anonymous hash that is passed
      # to the callback.  Make sure that we are still in the table
      # before assigning the key/values.

      my $next;

      foreach my $oid (oid_lex_sort(keys(%{$session->var_bind_list}))) {
         if (!oid_base_match($ifTable, $oid)) {
            $next = undef;
            last;
         }
         $oidCount++;
         $next = $oid;
         $table->{$oid} = $session->var_bind_list->{$oid};
         if ( $table->{$oid} eq 'endOfMibView' ){
            $next = undef;
            last;
         }
      }

      # If $next is defined we need to send another request
      # to get more of the table.

      if (defined($next)) {
        printf("Hentet %5i\r", $oidCount);
        $|++;  # Flush printbuffer
        $result = $session->get_bulk_request(
            -callback       => [\&bygTabel, $table],
            -maxrepetitions => 100,
            -varbindlist    => [$next]
        );

        if (!defined($result)) {
            printf("ERROR: %s\n", $session->error);
        }

      } else {

        # We are no longer in the table, so print the results.
        $oidCount=1;
        foreach my $oid (oid_lex_sort(keys(%{$table}))) {
           printf("%5i: %s => %s\n", $oidCount++, $oid, $table->{$oid});
         }

      }
   }
}