Net: : SNMP vis interface med request get
From Teknologisk videncenter
#!/usr/bin/perl
#######################################
# Author: Tomas Jensen / TDC #
# Email.: tcj@tdc.dk #
#######################################
#
### Pragma's
use strict;
use warnings;
use Socket;
use Net::SNMP qw(:snmp);
my $IfNumbers = '1.3.6.1.2.1.2.1.0';
my $IfListStart ='1.3.6.1.2.1.2.2.1.';
my %IfProp = ("Description"=>2,
"Type"=>3,
"MTU"=>4,
"Speed"=>5,
"MAC"=>6,
"AdminStatus"=>7,
"InOctets"=>10,
"OutOctets"=>16,
"InErrors"=>14,
"OutErrors"=>20
);
my $intnr;
my %interfaces;
my $interface;
my $key;
my $value;
my $ip;
my $addr;
my @result;
my $i;
#################### SUBS ######################
sub RealIp {
## Find real ip address
my $pip = shift;
if ( $pip =~ /^[1-9][0-9]*\.[0-9]+\.[0-9]+\.[0-9]+$/ ){
# Vi har en aegte ip
return $pip;
} else {
if ( $pip =~ /^0.*/ ) {
# Fjern indledende 0'er
$pip =~ s/^0+//;
return $pip;
} else {
# lav get host by name
$addr = inet_aton("$pip");
$addr = inet_ntoa ($addr);
if ( defined $addr ){
return $addr;
}
}
}
}
sub GetIntNrs {
## Find og returner antal interfaces
# Input : session
# OutPut : antal If
my $session = shift;
my $OID;
my $ifn;
my $result = $session->get_request(
-varbindlist => [$IfNumbers]);
if ( ! defined $result) {
print "Arrrrr - Kiks i GetIntNrs!!!\n";
}
($OID, $ifn) = each %{$result};
return $ifn;
}
sub GetIntInfo {
## Hent et interface
# Input : session
# Input : OID
# Output : Tekstinfo
my $session = shift;
my $OID = shift;
my $info;
my $result = $session->get_request(
-varbindlist => [$OID]);
if ( ! defined $result) {
print "Arrrrr - Kiks i GetIntInfo!!!\n";
}
($OID, $info) = each %{$result};
return $info;
}
##################### MAIN ######################
print "Indtast ip eller host: ";
my $host = <>;
chomp $host;
$ip = RealIp($host);
## Sæt session op
my ($session, $error) = Net::SNMP->session(
-hostname => $ip,
-version => '2c', );
if (!defined($session)) {
printf("Kan ikke åbne session til $host fejl: $error\n");
}
## Hent interface antal
print "Henter antal interfaces: \n";
printf " - Der er %s interfaces.\n", ($intnr = GetIntNrs $session);
print "Følgende findes:\n";
for ($i = 1; $i <= $intnr; $i++) {
printf "%s - %s\n", $i, (GetIntInfo $session, "$IfListStart"."$IfProp{'Description'}".".$i");
}
## Hvilket interface skal vises
print "Hvilket interface skal vises. Vælg mellem 1 og $intnr: ";
$interface = <>;
chomp $interface;
if ( $interface >= $intnr ) {
print "Dette interface findes ikke...\n";
exit;
}
## Præsenter interfacet
foreach $key ( keys %IfProp ){
printf "%12s --> %s\n", $key, (GetIntInfo $session, "$IfListStart"."$IfProp{$key}".".$interface");
}
--Tomas Christian Jensen 09:45, 12 November 2009 (CET)