SNMP V3 and Perl

与世无争的帅哥 提交于 2019-12-14 04:07:29

问题


I'm trying to use SNMPget on linux to get information regarding devices on my network. I'm able to successfully use snmpget on the linux terminal but now would like to write a script in perl/python and have it do the work for me.

SNMPget example

snmpgetnext -v 3 -n "" -u USER -a MD5 -A PASSWORD -l authNoPriv 192.168.1.1 sysDescr

I'm trying to do the same thing in perl, but I can't seem to find any good documentation on how to do it. What I found on the internet (but this is not SNMP v3):

$cat snmp

#!/usr/bin/perl
use Net::SNMP;
my $desc = 'sysDescr';
( $session, $error ) = Net::SNMP->session(
    -hostname  => "192.168.1.1",
    -community => "public",
    -timeout   => "30",
    -port      => "161"
);

if ( !defined($session) ) {
    printf( "ERROR: %s.\n", $error );
    exit 1;
}
my $response = $session->get_request($desc);
my %pdesc    = %{$response};

my $err = $session->error;
if ($err) {
    return 1;
}
print %pdesc;
exit 0;

I tried to modify it to snmp v3 but was unable to. Anybody familiar with this?


回答1:


SNMPv3 is much more complicated than v1 and v2c, it requires at least username (by that it is like v1 annd v2c) and in real cases, you must add authentication and privacy protocols and passwords.

You can use the official NET::SNMP documents to learn how to use this module, I'm adding an example for Set (not Get) usage from it:

#! /usr/local/bin/perl

use strict;
use warnings;

use Net::SNMP;

my $OID_sysContact = '1.3.6.1.2.1.1.4.0';

my ($session, $error) = Net::SNMP->session(
   -hostname     => 'myv3host.example.com',
    -version      => 'snmpv3',
   -username     => 'myv3Username',
   -authprotocol => 'sha1',
   -authkey      => '0x6695febc9288e36282235fc7151f128497b38f3f',
   -privprotocol => 'des',
   -privkey      => '0x6695febc9288e36282235fc7151f1284',
);

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

my $result = $session->set_request(
   -varbindlist => [ $OID_sysContact, OCTET_STRING, 'Help Desk x911' ],
);

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

printf "The sysContact for host '%s' was set to '%s'.\n",
      $session->hostname(), $result->{$OID_sysContact};

$session->close();

exit 0;

The session creation ($session) part is the main issue, after that you can use regular command like v1/v2c.

Another issue, you need to ask for OID (e.g. .1.3) format and not string names, unless you import a MIB module for translation.

Good luck...



来源:https://stackoverflow.com/questions/25374612/snmp-v3-and-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!