Next: Trap Handlers
Up: Polling Applications
Previous: Simple Polling with PERL
Contents
The Net-SNMP distribution comes complete with a PERL module. You'll notice that several SNMP modules
exist in CPAN but these are deprecated and should not be used.
The module is loaded in the usual way, with a "use" statement. It is recommended that you
supply a module version number to avoid any possible problems.
Three main statements are used in a basic application: SNMP::Session(), SNMP::VarList,
and SNMP::getnext(). The SNMP::Session method connects to the target agent and returns
a session handle. Once a handle is open, a varlist can be populated by passing
a number of OIDs (typically just the unique key name). The VarList method builds a list
and stores it using it's own internal format. We can use the GetNext method to actually fetch and
then output all the returned values into a normal flat array to be used by other parts of our script.
Here is an example of our previous APC monitoring tool re-written using the Net-SNMP PERL module.
#!/usr/local/bin/perl
use SNMP '5.0.2.pre1' || die("Cannot load module\n");
$ENV{'MIBS'}="ALL"; #Load all available MIBs
$SNMP_TARGET = "10.10.1.224";
$SNMP_COMMUNITY = "public";
$SESSION = new SNMP::Session (DestHost => $SNMP_TARGET,
Community => $SNMP_COMMUNITY,
Version => 1);
# Populate a VarList with OID values.
$APC_VLIST = new SNMP::VarList(['upsBasicIdentModel'], #0
['upsAdvIdentSerialNumber'], #1
['upsAdvBatteryCapacity'], #2
['upsAdvBatteryTemperature'], #3
['upsAdvOutputLoad'], #4
['upsAdvOutputVoltage'], #5
['upsAdvOutputFrequency'], #6
['upsBasicOutputStatus']); #7
# Pass the VarList to getnext building an array of the output
@APC_INFO = $SESSION->getnext($APC_VLIST);
$APC_INFO[0] =~ s/\"//g; # Ditch the quotes.
$APC_INFO[1] =~ s/\"//g;
# Output the results.
print <<END;
APC UPS ${SNMP_TARGET}
Model: ${APC_INFO[0]} Serial No: ${APC_INFO[1]}
Battery Capacity: ${APC_INFO[2]}
Battery Temp(F): ${APC_INFO[3]}
Output Status: ${APC_INFO[7]}
Output Load: ${APC_INFO[4]}
Output: ${APC_INFO[5]}VAC @ ${APC_INFO[6]}Hz
END
Notice that in the header of our script we're defining the MIBS environmental variable to "ALL",
which loads all of the MIBs in the Net-SNMP system MIBs directory.
Several varlists can be created from a single session to provide clear organization. When I
create varlists I find it is helpful to put commented reference numbers next to each element of
the list so that when I later use the populated array I can quickly check which OID is in which element.
The output looks the same as the previous versions did:
$ ./apc_status_mod.pl
APC UPS 10.10.1.224
Model: Silcon DP340E Serial No: SE0010000515
Battery Capacity: 100
Battery Temp(F): 33
Output Status: onLine
Output Load: 53
Output: 118VAC @ 60Hz
Next: Trap Handlers
Up: Polling Applications
Previous: Simple Polling with PERL
Contents
2004-11-23