perl - Resolve hostname and AP status from SNMP - perl

The idea is that the first get_table gets the AP status off a WLAN controller, then it uses get_request to get the AP's hostname as it's printing out the status table. The problem I'm having is the $ap_name comes back as an array, when I just want the single value.
my ($session, $error) = Net::SNMP->session(
-hostname => "$hostaddr",
-community => "$community",
-timeout => "30",
-version => "2c",
-port => "161");
if (!defined($session)) {
printf("ERROR: %s.\n", $error);
exit 1;
}
my $ap_stat = $session->get_table( -baseoid => $ap_stat_oid );
my $ap_name = $session->get_table( -baseoid => $ap_name_oid);
if (! defined $ap_stat || ! defined $ap_name) {
die "Failed to get OID '$ap_stat_oid': " . $session->error;
$session->close();
}
my #ap_name_array;
foreach my $ap_name_key (keys %$ap_name) {
push(#ap_name_array,$ap_name->{$ap_name_key});
}
my #ap_stat_array;
foreach my $ap_stat_key (keys %$ap_stat) {
push(#ap_stat_array,$ap_stat->{$ap_stat_key});
}
Edit: I changed it up a bit but still can't figure out what's next. I think I want to store the print output's into arrays and then join them and print for the joined array but I'm not sure how.
Edit: Here's my desired output:
AP-01 = 1
AP-02 = 1
AP-03 = 2
AP-04 = 1
etc..
More edits: I got the values into an arrays, now I'm just trying to get the output right.

Figured it out using use List::MoreUtils qw(pairwise); from here
if (! defined $ap_stat || ! defined $ap_name) {
die "Failed to get OID '$ap_stat_oid': " . $session->error;
$session->close();
}
my #ap_name_array;
foreach my $ap_name_key (keys %$ap_name) {
push(#ap_name_array,$ap_name->{$ap_name_key});
}
my #ap_stat_array;
foreach my $ap_stat_key (keys %$ap_stat) {
push(#ap_stat_array,$ap_stat->{$ap_stat_key});
}
print pairwise { "$a = $b\n" } #ap_name_array, #ap_stat_array;
Beat you to it #ThisSuitIsBlackNot, thanks anyways!

Related

Perl LDAP search - over 1500 member in a group

I want to search with an Perl script and ldap connection all members of a group with over 10.000 member.
I can only find results, if i set $first=0 and $last=1499 and than i get only the first 1500 member of the group.
If i use other parameter for $first and $last, then i got no results.
"$ldapsearchresult = $ldapconnect->search (
Sizelimit => 0,
base => 'any_base',
filter => '(objectClass=*)',
attr => ['member;range=$first-$last'],
);"
Thanks for your help!
You need to search the attribute range as a subtype again and again until the last return '*'.
Here is the code I am using, it is also use paged search in AD.
use Net::LDAP;
use Net::LDAP qw(LDAP_CONTROL_PAGED);
use Net::LDAP::Util qw(ldap_error_name canonical_dn ldap_explode_dn ldap_error_text);
use Net::LDAP::Control::Paged;
my $page_page = Net::LDAP::Control::Paged->new( 'size' => $input{'page'} );
my $finished_search = 0;
my $page_cookie;
my $result;
my #page_search_args = (
'base' => $input{"base"},
'scope' => $input{'scope'},
'filter' => $input{'filter'},
'attrs' => $input{'attrs'},
'control' => [ $page_page ],
'deref' => 'never',
'raw' => qr!^DO_NOT_MATCH!,
);
while (!$finished_search) {
my $msg = $ldap->search(#page_search_args);
if ($msg->is_error()) {
die "ERROR: ",$msg->error,"\n";
last;
} else {
my ($response) = $msg->control(LDAP_CONTROL_PAGED);
$page_cookie = $response->cookie();
$finished_search = 1 if !$page_cookie;
$page_page->cookie($page_cookie);
while (my $entry = $msg->pop_entry()){
$ldap_searches++;
print_all_attributes($entry);
}
}
}
if ($page_cookie) {
$page_page->cookie($page_cookie);
$page_page->size(0);
$ldap->search(#page_search_args);
}
sub add_result {
my $dn = shift;
my $attr = shift;
my $data = shift;
my $res = shift;
$attr =~ s!(;range\=\d+\-\d+)!!i;
#print "removed $1 from $attr" if $1;
foreach my $subtype (keys %{$data}){
$attr = $attr.$subtype if $subtype ne '';
$attr =~ s!(;range\=\d+\-\d+)!!i;
if (defined $$res->{$dn}->{$attr}){
push(#{$$res->{$dn}->{$attr}},#{$data->{$subtype}});
} else {
push(#{$$res->{$dn}->{$attr}},#{$data->{$subtype}});
}
}
return $res;
}
sub print_all_attributes {
my $entry = shift;
foreach my $attr ($entry->attributes()) {
if ($attr =~ /;range=/) {
my $last = 0;my $first = 0;
### $var will look like this --> "member;range=0-1499"
(my $pure_attr,my $range) = split /;/, $attr,2;
(my $junk,$range) = split /=/, $range,2;
($first,$last) = split /-/, $range,2;
$i++;
add_result($entry->dn(),$pure_attr,$entry->get_value($attr,alloptions => 1, asref => 1),\$result) if $last eq '*' or $last >= $parms{'attribute_page'};
### if $last eq "*", indicates this is the last range increment, and
### we do not need to perform another supplemental search
if ($last ne "*") {
my $range_diff = ($last - $first) + 1;
my $increment = $last + $range_diff;
$last = $last + 1;
$attr = "$pure_attr;range=$last-$increment";
$parms{'attrs'} = [$attr];
search_nonpaged(%parms);
}
} else {### if $attr matches range pattern
add_result($entry->dn(),$attr,$entry->get_value($attr,alloptions => 1, asref => 1),\$result);
}
}
return 1;
}
sub search_nonpaged{
my %input = #_;
my #page_search_args = (
'base' => $input{"base"},
'scope' => $input{'scope'},
'filter' => $input{'filter'},
'attrs' => $input{'attrs'},
'deref' => 'never',
'raw' => qr!^DO_NOT_MATCH!,
);
my $msg = $ldap->search(#page_search_args);
if ($msg->is_error()) {
die "ERROR: ",$msg->error,"\n";
}
while (my $entry = $msg->pop_entry()){
$ldap_searches++;
print_all_attributes($entry);
}
}
You maybe able to simplify the program by searching for:
memberOf=CN=GroupOne,OU=Security Groups,OU=Groups,DC=YOURDOMAIN,DC=NET
You will still need to use the paged results control but will not need the range control.
Microsoft Active Directory uses the MaxValRange to control the number of values that are returned in the retrieval of multi-valued attributes of an entry.
By using the filter above, you can avoid the MaxValRange settings.
BY THE WAY: if you want to obtain nested members also, try:
(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=YOURDOMAIN,DC=NET)
This filter uses the LDAP_MATCHING_RULE_IN_CHAIN extensible match.
-jim
I found an easier way to search all member of a AD group:
http://permalink.gmane.org/gmane.comp.lang.perl.modules.ldap/246
use Net::LDAP; use Net::LDAP::Util;
# Connect to AD make sure to specify version 3
$ldap = new Net::LDAP("myGC.yy.xx.com",
port => 3268,
debug => 0,
version => 3
) or die "New failed:$ <at> ";
# Do an anonymous bind. You MAY have to do an authenticated bind in your configuration
$result=$ldap->ldapbind() || die "Bind Failed:$ <at> ";
# Some error trapping
$err=$result->code;
if ($err){
$errname=Net::LDAP::Util::ldap_error_name($err);
$errtxt=Net::LDAP::Util::ldap_error_text($err);
if ($errtxt){
print "($err) $errtxt\n";
}
else
{
if ($errname){
print "($err) $errname\n";
}
else
{
print "ERR: $err\n";
}
}
exit;
}
# The combination of the search base and filter determine which object that you
# retrieve
# set search filter to groups of objects. This is what you want to enumerate NT groups.
$filter="(objectClass=group)";
# Set the search base to the DN of the object that you want to retrieve. BTW, using this method on
# groups with less than 1000 members works as well.
$base='CN=mygroup,DCyyy,DC=xxx,DC=com';
# Set the initial attribute indexes and name
$found=1; $startr=0; $endr=-1; $startattr="member";
while($found){
# Create the attribute range specification
$startr=$endr+1;
$endr=$startr+999;
$attr="$startattr;range=$startr-$endr";
$saveattr=$attr;
<at> attr=("$attr");
# Perform the search
$result=$mesg = $ldap->search(base => "$base",filter => $filter,
attrs => [ <at> attr],
scope => "sub") or die "search died";
# Some error trapping
$err=$result->code;
if ($err){
if (!($err == 1)){
$errname=Net::LDAP::Util::ldap_error_name($err);
$errtxt=Net::LDAP::Util::ldap_error_text($err);
if ($errtxt){
print "($err) $errtxt\n";
}
else
{
if ($errname){
print "($err) $errname\n";
}
else
{
print "ERR: $err\n";
}
}
}
else
{
print "COUNT=$cnt\n";
}
exit;
}
$found=0;
# OK, get the attribute range...so we can update the value of the attribute
# on the next pass
foreach $entry ($mesg->all_entries) {
<at> attr=$entry->attributes;
foreach( <at> attr){
$curattr=$_;
}
}
# Print out the current chunk of members
foreach $entry ($mesg->all_entries) {
$ar=$entry->get("$curattr");
foreach( <at> $ar){
$cnt++;
print "$_\n";
}
$found=1;
if (! <at> $ar[0]){
$found=0;
}
}
# Check to see if we got the last chunk. If we did print toe total and set
# the found flag so we don't search for anymore members
if ($curattr=~/\;range=/){
if ($curattr=~/\-\*/){
print "LASTCOUNT:$cnt\n";
$found=0;
}
}
}

Using Redis.pm pipeline in perl

My attempt to Redis pipeline in perl, using Redis.pm, Is this correct approach? Snipped of code below:
...
my $redis = Redis->new(server => '127.0.0.1:6379', reconnect => 60);
foreach my $key (keys %hval) {
my $ok = $redis->zadd($key, $hval{ $key }, &process);
}
sub process {
my ($reply, $error) = #_;
my $cr = sub {
my ($r, $e) = #_;
if ($e) {
warn Dumper('Redis pipelining crapped out', $e);
{
}
}
Have you tried this before? I looked around but could not found any suitable example, Please let me know. I am using all required module and this code is for here only. Actual code is much complex? Thanks in advance.
Here is an example:
use Redis;
my $redis = Redis->new(server => '127.0.0.1:6379', reconnect => 60);
my %hval = ( 'foo', 1, 'bar', 2, 'foobar', 3 );
foreach my $key (keys %hval) {
my $ok = $redis->zadd("myzset", $hval{ $key }, $key, sub {
my ($reply, $error) = #_;
print "Returned $reply with error = [$error]\n" ;
});
}
print "Waiting replies ...\n";
$redis->wait_all_responses;
Please note that:
a wait_all_responses clause is required to put a synchronization point with the server.
zadd requires 3 parameters (zset name, score, key) in that order

DNS Resolver result from multiple nameservers

I am passing two name servers to the Net::DNS::Resolver constructor but I am getting only one result back.
How should I change the code to receive result from all the name servers?
sub resolve_dns()
{
my $dns = $_[0];
my $res = Net::DNS::Resolver->new(
nameservers => [qw(24.116.197.232 114.130.11.67 )],
recurse => 0,
debug => 1,
tcp_timeout => 3
);
my $query = $res->search($dns);
if ($query) {
foreach my $rr ($query->answer) {
next unless $rr->type eq "A";
print $rr->address, "\n";
}
} else {
warn "query failed: ", $res->errorstring, "\n";
}
}
I presume the DNS servers after the first are there for fallback purposes and only a single reply will ever be returned.
The best way seems to be to manipulate the Net::DNS::Resolver server list and explicitly make a request to each of them.
This example code demonstrates the principle
sub resolve_dns {
my $address = shift;
my $res = Net::DNS::Resolver->new
recurse => 0,
debug => 1,
tcp_timeout => 3,
);
for my $ns (qw( 24.116.197.232 114.130.11.67 )) {
$res->nameservers($ns);
my $reply = $res->send($address);
if ($reply) {
my #type_a = grep $_->type eq 'A', $reply->answer;
print $_->address, "\n" for #type_a;
}
else {
warn sprintf "Query to %s failed: %s\n", $ns, $res->errorstring;
}
}
}

mib name printing from mib values in perl

This is the code that I used to walk through the table in net:snmp using perl:
#! /usr/local/bin/perl
use strict;
use warnings;
use Net::SNMP qw(:snmp);
my $OID_hrSystem = '1.3.6.1.2.1.25.1';
my $OID_ifPhysAddress = '1.3.6.1.2.1.2.2.1.6';
my ($session, $error) = Net::SNMP->session(
-hostname => shift || 'localhost',
-community => shift || 'public',
-nonblocking => 1,
-translate => [-octetstring => 0],
-version => 'snmpv2c',
);
if (!defined $session) {
printf "ERROR: %s.\n", $error;
exit 1;
}
my %table; # Hash to store the results
my $result = $session->get_bulk_request(
-varbindlist => [ $OID_hrSystem ],
-callback => [ \&table_callback, \%table ],
-maxrepetitions => 10,
);
if (!defined $result) {
printf "ERROR: %s\n", $session->error();
$session->close();
exit 1;
}
# Now initiate the SNMP message exchange.
snmp_dispatcher();
$session->close();
# Print the results, specifically formatting ifPhysAddress.
for my $oid (oid_lex_sort(keys %table)) {
if (!oid_base_match($OID_ifPhysAddress, $oid)) {
printf "%s = %s\n", $oid, $table{$oid};
} else {
printf "%s = %s\n", $oid, unpack 'H*', $table{$oid};
}
}
exit 0;
sub table_callback
{
my ($session, $table) = #_;
my $list = $session->var_bind_list();
if (!defined $list) {
printf "ERROR: %s\n", $session->error();
return;
}
# Loop through each of the OIDs in the response and assign
# the key/value pairs to the reference that was passed with
# the callback. Make sure that we are still in the table
# before assigning the key/values.
my #names = $session->var_bind_names();
my $next = undef;
while (#names) {
$next = shift #names;
if (!oid_base_match($OID_hrSystem, $next)) {
return; # Table is done. chakri
}
$table->{$next} = $list->{$next};
}
# Table is not done, send another request, starting at the last
# OBJECT IDENTIFIER in the response. No need to include the
# calback argument, the same callback that was specified for the
# original request will be used.
my $result = $session->get_bulk_request(
-varbindlist => [ $next ],
-maxrepetitions => 10,
);
if (!defined $result) {
printf "ERROR: %s.\n", $session->error();
}
return;
}
Output is:
1.3.6.1.2.1.25.1.1.0 = 1 hour, 12:00.77
1.3.6.1.2.1.25.1.2.0 = �
+
1.3.6.1.2.1.25.1.3.0 = 1536
1.3.6.1.2.1.25.1.4.0 = BOOT_IMAGE=/boot/vmlinuz-3.0.0-14-generic root=UUID=5c4c8d22-3cea-4410-aaad-f297c75d217e ro quiet splash vt.handoff=7
1.3.6.1.2.1.25.1.5.0 = 1
1.3.6.1.2.1.25.1.6.0 = 133
1.3.6.1.2.1.25.1.7.0 = 0
But the required output for me is as follows:
hrSystemUptime.0 = 1:08:54.36
hrSystemDate.0 = 2011-12-14,16:0:2.0,+1:0
hrSystemInitialLoadDevice.0 = 1536
hrSystemInitialLoadParameters.0 = "BOOT_IMAGE=/boot/vmlinuz-3.0.0-14-generic root=UUID=5c4c8d22-3cea-4410-aaad-f297c75d217e ro quiet splash vt.handoff=7"
hrSystemNumUsers.0 = 1
hrSystemProcesses.0 = 133
hrSystemMaxProcesses.0 = 0
The main thing in the output is I want mib names to be printed in the output instead of the mib values
You could use the SNMP module (available on Ubuntu as libsnmp-perl) which offers a tied hash to loaded MIBs, %SNMP::MIB. Here's some example code:
use SNMP;
SNMP::initMib();
print "$SNMP::MIB{'1.3.6.1.2.1.25.1.1.0'}{label} = \n";
#Should print "hrSystemUptime = "
Because %SNMP::MIB is a tied hash, you can't just do a lookup and assign to a lexical variable, i.e. my $oid = $SNMP::MIB{$oidstr}. You have to access it directly every time.
There is lots of other information that it loads from the MIB, including data type, which could help with the issue it looks like you have with hrSystemDate. Also, see the man page for mib_api if you need to load specific MIBs. The ones you used in your example loaded by default on my system, though.
have you tried the snmpget command on your server? When I run snmpget direcly on CLI, the result cames with the name:
Ex: /usr/local/bin/snmpget -O Q -v 2c -c Community x.x.x.x .1.3.6.1.2.1.31.1.1.1.6.100663301
IF-MIB::ifHCInOctets.100663301 = 152528664859348
If it works for you, you might want to exectute the command in the PERL code, instead of using the LIB. Then you just have to handle with the output.
Also, tou can use snmptranslate to tranlate your OIDs:
Ex: /usr/local/bin/snmptranslate 1.3.6.1.2.1.25.1.1
HOST-RESOURCES-MIB::hrSystemUptime
More Info -> http://www.net-snmp.org/wiki/index.php/TUT:snmptranslate
EDIT
Why don't you:
my $pathSnmpTranslate = '/your/path/to/snmptranslate';
for my $oid (oid_lex_sort(keys %table)) {
my $oidTrans = `$pathSnmpTranslate $oid`;
if (!oid_base_match($OID_ifPhysAddress, $oid)) {
printf "%s = %s\n", $oidTrans, $table{$oid};
} else {
printf "%s = %s\n", $oidTrans, unpack 'H*',$table{$oid};
}
}
On my machine it worked:
> /xxx % /usr/local/bin/snmptranslate 1.3.6.1.2.1.25.1.1
HOST-RESOURCES-MIB::hrSystemUptime
> /xxx % /usr/local/bin/snmptranslate 1.3.6.1.2.1.25.1.1.0
HOST-RESOURCES-MIB::hrSystemUptime.0

Why is Net::SNMP::Dispatcher failing with "select() error [No child processes]"?

I need some help identifying, and eliminating, the cause of an odd child process error when polling SNMP services.
During SNMP connect, I verify SNMP connectivity by polling for the
device name until it times out:
sub snmp_close {
my $self = shift;
$self->{SNMP_SESSION}->close if (defined $self->{SNMP_SESSION} && $self->{SNMP_SESSION});
$self->{SNMP_SESSION} = undef;
}
sub {
my ($self, $ip, $community) = #_;
# If there's a leftover session around, make sure it's closed
$self->snmp_close;
my ($session, $error) = Net::SNMP->session(
-hostname => $ip,
-community => $community,
-nonblocking => 1,
-version => 'snmpv2c',
-translate => [
-timeticks => 0x0
],
);
if (!defined $session) {
$self->_logger->logcluck("Can't create SNMP object, error: '$error'");
return;
}
$self->{SNMP_SESSION} = $session;
my $end = time() + 90;
while (time < $end) {
$self->_logger->debug("Probing for SNMP connectivity, giving up in " . int($end - time()) . " seconds");
my %sysName = $self->get_bulk('1.3.6.1.2.1.1.5');
if(scalar keys %sysName >= 1) { # try polling sysName..
return 1;
}
else {
sleep 5;
}
}
# if we've made it this far there's no hope for snmp...
$self->_logger->warn("No SNMP connectivity after 90 seconds");
$self->{SNMP_SESSION} = 0;
return;
}
sub get_bulk { # return a hash of oid keys and values
my ($self, $oid) = #_;
$self->_logger->logdie("Not connected; call snmp_connect") if not defined $self->{SNMP_SESSION};
$self->_logger->logdie("Connection failed") if not $self->{SNMP_SESSION};
my %table;
my $result = $self->snmp->get_bulk_request(
-varbindlist => [ $oid ],
-maxrepetitions => 20,
-callback => [\&_table_callback, $self, \%table, $oid],
);
if (!defined $result) {
$self->_logger->warn("SNMP error: '" . $self->snmp->error() . "'");
return;
}
snmp_dispatcher();
use Data::Dumper; my %_table = map {s/\Q$oid.\E//; $_} %table; $self->_logger->debug("SNMP Debug, OID polled: '$oid', response is: " . Dumper(\%_table));
return %table;
}
Most of the time, this works flawlessly, but some percentage of the time
I get a FATAL error out of Net::SNMP::Dispatcher:
FATAL: select() error [No child processes] at perl/lib/perl5.8/Net/SNMP/Dispatcher.pm line 635.
at perl/lib/perl5.8/Net/SNMP/Dispatcher.pm line 635
Net::SNMP::Dispatcher::_event_select('Net::SNMP::Dispatcher=HASH(0xaca5ce0)', 4.99994683265686) called at perl/lib/perl5.8/Net/SNMP/Dispatcher.pm line 601
Net::SNMP::Dispatcher::_event_handle('Net::SNMP::Dispatcher=HASH(0xaca5ce0)') called at perl/lib/perl5.8/Net/SNMP/Dispatcher.pm line 80
Net::SNMP::Dispatcher::activate('Net::SNMP::Dispatcher=HASH(0xaca5ce0)') called at perl/lib/perl5.8/Net/SNMP.pm line 611
Net::SNMP::snmp_dispatcher() called at perl/lib/perl5.8/Device.pm line 857
Device::get_bulk('Device::Class=HASH(0xb1e405c)', 1.3.6.1.2.1.1.5) called at perl/lib/perl5.8/Device.pm line 824
Device::snmp_connect('Device::Class=HASH(0xb1e405c)', 10.0.0.1, 'COMMUNITY_STRING') called at perl/lib/perl5.8/Device.pm line 912
(Line 857 is the snmp_dispatcher in get_bulk, above)
I'm new enough to perl -- and totally new to SNMP -- that I don't really
know how to troubleshoot this. The method in question is executed in a
mod_perl CGI call, if that helps isolate the problem.
Some local investigation turned up the fact that this is a side effect of multi-core machines; the child process ran on another core, and its pipe file handle was not available to the parent process.