SNMP_Session(3pm)
π SNMP_Session β the perl module that speaks SNMPv1/v2 π
okay bestie, welcome to SNMP_Session(3pm), a User Contributed Perl Documentation page, and it's long, so buckle up. This is part 1 of 4, so don't go anywhere. πΈ
β¨ NAME β¨
SNMP_Session β SNMPv1/v2 Protocol Handling π¦
β¨ SYNOPSIS β¨
use SNMP_Session;
$session = SNMP_Session->open ($host, $community, $port)
or die "couldn't open SNMP session to $host";
if ($session->get_request_response ($oid1, $oid2, ...)) {
($bindings) = $session->decode_get_response ($session->{pdu_buffer});
while ($bindings ne '') {
($binding,$bindings) = decode_sequence ($bindings);
($oid,$value) = decode_by_template ($binding, "%O%@");
print pretty_print ($oid)," => ", pretty_print ($value), "\n";
}
} else {
die "No response from agent on $host";
}
π VARIABLES π
The default_... variables all specify default values that get used for SNMP_Session objects when you don't specify anything else. And like, you can override these on a per-session basis β for example by passing extra arguments to the constructor. π
π $default_max_repetitions β default value for maxRepetitions
This one says how many table rows get requested in getBulk requests. It's used when you're walking tables with getBulk (which is only a thing in SNMPv2(c) and later, iykyk).
- If it's too small, your table walk is gonna need unnecessarily many request/response exchanges. exhausting.
- If it's too big, the agent may compute a whole bunch of variables after the end of the table. wasteful.
The recommendation is literally to set this explicitly for each table walk by using map_table_4(). do it. β¨
π $default_avoid_negative_request_ids β default value for avoid_negative_request_ids
Set this to non-zero if you've got agents that have trouble with negative request IDs, and bestie, don't forget to complain to your agent vendor. π
According to the spec (RFC 1905), the request-id is an Integer32, so its range goes from -(2^31) to (2^31)-1. But some agents erroneously encode the response ID as an unsigned, which prevents this code from matching such responses to requests. not them being wrong on main. π
π $default_use_16bit_request_ids β default value for use_16bit_request_ids
Set this to non-zero if you have agents that use 16bit request IDs, and again: don't forget to complain to your agent vendor. π«Ά
π $errmsg β error message from last failed operation
When they encounter errors, the routines in this module will generally return undef and leave an informative error message in $errmsg. iconic behaviour, honestly. π
π $suppress_warnings β whether warnings should be suppressed
If this variable is zero β which is the default β this code will output informative error messages whenever it encounters an error. Set it to a non-zero value if you want to suppress those messages.
Either way, the last error message can always be found in $errmsg. no cap. π
π METHODS in package SNMP_Session π
The abstract class SNMP_Session defines objects that can be used to communicate with SNMP entities. It has methods to send requests to and receive responses from an agent. π«
Two instantiable subclasses are defined:
SNMPv1_Sessionβ implements SNMPv1 (RFC 1157) functionalitySNMPv2c_Sessionβ implements community-based SNMPv2 (RFC 3410-3417)
πΈ open() β create an SNMP session object
$session = SNMP_Session->open
($host, $community, $port,
$max_pdu_len, $local_port, $max_repetitions,
$local_host, $ipv4only);
The calling and return conventions are identical to SNMPv1_Session::open(). periodt. β¨
πΈ timeout() β return timeout value
Initial timeout, in seconds, to wait for a response PDU after a request is sent. Note that when a request is retried, the timeout is increased by backoff (see below, bestie). The standard value is 2.0 (seconds).
πΈ retries() β number of attempts to get a reply
Maximum number of attempts to get a reply for an SNMP request. If no response is received after timeout seconds, the request is resent and a new response awaited with a longer timeout β see the documentation on backoff below.
The retries value should be at least 1, because the first attempt counts too (the name retries is confusing, sorry for that π).
πΈ backoff() β backoff factor for timeout on successive retries
Default backoff factor for SNMP_Session objects. This factor is used to increase the TIMEOUT every time an SNMP request is retried. The standard value is 1.0, which means the same timeout is used for all attempts.
πΈ set_timeout() β set initial timeout for session
πΈ set_retries() β set maximum number of attempts for session
πΈ set_backoff() β set backoff factor for session
Example usage, bestie:
$session->set_backoff (1.5);
πΈ ..._request_response() β Send some request and receive response
Encodes a specific SNMP request, sends it to the destination address of the session, and waits for a matching response. If such a response is received, this function will return the size of the response, which is necessarily greater than zero. π
An undefined value is returned if some error happens during encoding or sending, or if no matching response is received after the wait/retry schedule is exhausted. See the documentation on the timeout(), retries(), and backoff() methods on how the wait/retry logic works. π¦
πΈ get_request_response() β Send "get" request and receive response
πΈ getnext_request_response() β Send "get-next" request and receive response
$result = $session->get_request_response (@encoded_oids);
$result = $session->getnext_request_response (@encoded_oids);
πΈ set_request_response() β Send "set" request and receive response
$result = $session->set_request_response (@encoded_pair_list);
This method takes its arguments in a different form; they are a list of pairs β references to two-element arrays β which represent the variables to be set and the intended values, like this:
([$encoded_oid_0, $encoded_value_0],
[$encoded_oid_1, $encoded_value_1],
[$encoded_oid_2, $encoded_value_2], ...)
πΈ trap_request_send() β send SNMPv1 Trap
$result = $session->trap_request_send ($ent, $gent, $gen, $spec, $dt, @pairs);
πΈ v2_trap_request_send() β send SNMPv2 Trap
$result = $session->v2_trap_request_send ($trap_oid, $dt, @pairs);
πΈ map_table() β traverse an SNMP table
$result = $session->map_table ([$col0, $col1, ...], $mapfn);
This will call the provided function (&$mapfn) once for each row of the table defined by the column OIDs $col0, $col1... If the session can handle SNMPv2 operations, get-bulk will be used to traverse the table. Otherwise, get-next will be used.
If the first argument is a list of n columns, the mapping function will be called with n+1 arguments. The first argument will be the row index, i.e. the list of sub-IDs that was appended to the provided column OIDs for this row. Note that the row index will be represented as a string, using dot-separated numerical OID notation. β¨
The remaining arguments to the mapping function will be the values of each column at the current index. It is possible that the table has "holes", i.e. that for a given row index, not all columns have a value. For columns with no value at the current row index, undef will be passed to the mapping function. π
If an error is encountered at any point during the table traversal, this method will return undef and leave an error message in $errmsg (which is also written out unless $suppress_warnings is non-zero).
Otherwise, the function will return the number of rows traversed, i.e. the number of times that the mapping function has been called. slay. π
πΈ map_table_4() β traverse an SNMP table with more control
πΈ map_table_start_end() β traverse an SNMP table with lower/upper index limits
$result = $session->map_table_start_end ($columns, $mapfn,
$start, $end, $max_repetition);
Similar to map_table_4(), except that the start and end index can be specified. π
πΈ receive_trap_1() β receive message on trap socket
This method waits until a message is received on the trap socket. If successful, it returns two values: the message that was received, and the address of the sender as a sockaddr structure. This address can be passed to getnameinfo() to convert it to readable output. π
This method doesn't check whether the message actually encodes a trap or anything else β the caller should use decode_trap_request() to find out. iykyk. π
πΈ receive_trap() β receive message on trap socket (deprecated version)
This function is identical to receive_trap_1(), except that it returns the sender address as three (formerly two) separate values: the host IP address, the port, and (since version 1.14) the address family.
If you use this, please consider moving to receive_trap_1(), because it is easier to process the sender address in sockaddr format β in particular in a world where IPv4 and IPv6 coexist. π«Ά
πΈ decode_trap_request()
($community, $ent, $agent, $gen, $spec, $dt, $bindings)
= $session->decode_trap_request ($trap);
Given a message such as one returned as the first return value from receive_trap_1() or receive_trap(), try to decode it as some notification PDU. The code can handle SNMPv1 and SNMPv2 traps as well as SNMPv2 INFORMs, although it fails to distinguish traps from informs, which makes it hard to handle informs correctly (they should be acknowledged). π
The $ent, $agent, $gen, $spec, and $dt values will only be defined for SNMPv1 traps. For SNMPv2 traps and informs, some of this information will be encoded as bindings. π¦
more parts coming bestie, don't move π
β¨ METHODS in package SNMPv1_Session β¨
π open() β bestie, let's build us an SNMPv1 session object
$session = SNMPv1_Session->open
($host, $community, $port,
$max_pdu_len, $local_port, $max_repetitions,
$local_host, $ipv4only);
okay so listen β every single argument except $host is optional π«Ά. You only gotta give it a host. And that $host can be a hostname or a numeric address, whichever vibe you're on. But heads up: if you're dropping a numeric IPv6 address, you must wrap it in square brackets [] or it's gonna be a whole mess π.
$communityβ defaults to"public". The classic default, we love her.$portβ defaults to161, which is the standard UDP port you send SNMP requests to. Periodt.$max_pdu_lenβ defaults to8000. That's the size cap on your PDU, no cap fr.$local_portβ you can set this if you want a specific local port, like when firewall rules are being picky about which port the response packets come back to. If you don't specify one, the operating system just picks a random port for you. Slay, OS, thanks for handling that π.$max_repetitionsβ this is the max number of repetitions you're requesting in"get-bulk"requests. Lowkey only relevant in SNMPv2(c) and later, so if you're on v1 she just doesn't matter π .$local_hostβ use this to specify a particular address/interface. Super useful on hosts that have multiple addresses when you need one specific address to be the one doing the talking β again, firewall rules being the drama queens they are π₯.$ipv4onlyβ if this is either not present or non-zero, then an IPv4-only socket gets used. That's also what happens if the system only supports IPv4 anyway (not her fault, she's doing her best). Otherwise? An IPv6 socket is created β¨. And bestie, IPv6 sockets support both IPv6 and IPv4 requests and responses, so they're kind of the main character π.
π open_trap_session() β for catching those SNMP traps
$session = open_trap_session ($port, $ipv4only);
This one's your little trap-catcher, adorable π¦.
$portβ defaults to162, the standard UDP port that SNMP notifications get sent to. That's the one you're listening on.$ipv4onlyβ same deal as above, no cap: if it's not present or non-zero, you get an IPv4-only socket. Also true if the system only does IPv4. Otherwise an IPv6 socket gets created π. And IPv6 sockets can receive messages over both IPv6 and IPv4, which is giving versatile icon energy π.
πΈ METHODS in package SNMPv2c_Session πΈ
β¨ open() β create an SNMPv2(c) session object
$session = SNMPv2c_Session->open
($host, $community, $port,
$max_pdu_len, $local_port, $max_repetitions,
$local_host, $ipv4only);
okay so this one is literally identical to "SNMPv1_Session::open()" in how you call it and what you get back β same conventions, same everything, don't overthink it bestie π«Ά.
The one difference? What you get back is a session object that supports SNMPv2 operations. That's it. That's the glow-up β¨π .
π EXAMPLES π
okay bestie, the basic usage of these routines works like this π
use BER;
use SNMP_Session;
# Set $host to the name of the host whose SNMP agent you want to
# talk to. Set $community to the community name under
# which you want to talk to the agent. Set port to the UDP
# port on which the agent listens (usually 161).
$session = SNMP_Session->open ($host, $community, $port)
or die "couldn't open SNMP session to $host";
# Set $oid1, $oid2... to the BER-encoded OIDs of the MIB
# variables you want to get.
if ($session->get_request_response ($oid1, $oid2, ...)) {
($bindings) = $session->decode_get_response ($session->{pdu_buffer});
while ($bindings ne '') {
($binding,$bindings) = decode_sequence ($bindings);
($oid,$value) = decode_by_template ($binding, "%O%@");
print pretty_print ($oid)," => ", pretty_print ($value), "\n";
}
} else {
die "No response from agent on $host";
}
π’ Encoding OIDs π’
To BER-encode OIDs, you can use the function BER::encode_oid. It takes (a vector of) numeric subids as an argument. For example,
use BER;
encode_oid (1, 3, 6, 1, 2, 1, 1, 1, 0)
will return the BER-encoded OID for the sysDescr.0 (1.3.6.1.2.1.1.1.0) instance of MIB-2. slay β¨
π§ Decoding the results π§
When get_request_response() returns success, you must decode the response PDU from the remote agent. The function decode_get_response() can be used to do this. It takes a get-response PDU, checks its syntax and returns the bindings part of the PDU. This is where the remote agent actually returns the values of the variables in your query.
You should iterate over the individual bindings in this bindings part and extract the value for each variable. In the example above, the returned bindings are simply printed using the BER::pretty_print() function.
For better readability of the OIDs, you can also use the following idiom, where the %pretty_oids hash maps BER-encoded numerical OIDs to symbolic OIDs. Note that this simple-minded mapping only works for response OIDs that exactly match known OIDs, so it's unsuitable for table walking (where the response OIDs include an additional row index).
%ugly_oids = qw(sysDescr.0 1.3.6.1.2.1.1.1.0
sysContact.0 1.3.6.1.2.1.1.4.0);
foreach (keys %ugly_oids) {
$ugly_oids{$_} = encode_oid (split (/\./, $ugly_oids{$_}));
$pretty_oids{$ugly_oids{$_}} = $_;
}
...
if ($session->get_request_response ($ugly_oids{'sysDescr.0'},
$ugly_oids{'sysContact.0'})) {
($bindings) = $session->decode_get_response ($session->{pdu_buffer});
while ($bindings ne '') {
($binding,$bindings) = decode_sequence ($bindings);
($oid,$value) = decode_by_template ($binding, "%O%@");
print $pretty_oids{$oid}," => ",
pretty_print ($value), "\n";
}
} ...
π Set Requests π
Set requests are generated much like get or getNext requests are, with the exception that you have to specify not just OIDs, but also the values the variables should be set to. Every binding is passed as a reference to a two-element array, the first element being the encoded OID and the second one the encoded value. See the test/set-test.pl script for an example, in particular the subroutine snmpset. periodt π
πΆββοΈ Walking Tables πΆββοΈ
Beginning with version 0.57 of SNMP_Session.pm, there is API support for walking tables. The map_table() method can be used for this as follows:
sub walk_function ($$$) {
my ($index, $val1, $val3) = @_;
...
}
...
$columns = [$base_oid1, $base_oid3];
$n_rows = $session->map_table ($columns, \&walk_function);
The columns argument must be a reference to a list of OIDs for table columns sharing the same index. The method will traverse the table and call the walk_function for each row. The arguments for these calls will be:
- the row index as a partial OID in dotted notation, e.g.
1.3, or10.0.1.34. - the values of the requested table columns in that row, in BER-encoded form. If you want to use the standard
pretty_print()subroutine to decode the values, you can use the following idiom:grep (defined $_ && ($_=pretty_print $_), ($val1, $val3));
π Walking Tables With get-bulk π
Since version 0.67, SNMP_Session uses a different get_table implementation for SNMPv2c_Sessions. This version uses the βpowerful get-bulk operatorβ to retrieve many table rows with each request. In general, this will make table walking much faster under SNMPv2c, especially when round-trip times to the agent are long. zoom zoom π¦
There is one difficulty, however: With get-bulk, a management application can specify the maximum number of rows to return in a single response. SNMP_Session.pm provides a new function, map_table_4, in which this maxRepetitions value can be specified explicitly.
For maximum efficiency, it should be set to a value that is one greater than the number of rows in the table. If it is smaller, then map_table() will use more request/response cycles than necessary; if it is bigger, the agent will have to compute variable bindings beyond the end of the table (which map_table() will throw away).
Of course it is usually impossible to know the size of the table in advance. If you don't specify maxRepetitions when walking a table, then map_table() will use a per-session default ($session->default_max_repetitions). The default value for this default is 12.
If you walk a table multiple times, and the size of the table is relatively stable, you should use the return value of map_table() (which is the number of rows it has encountered) to compute the next value of maxRepetitions. Remember to add one so that map_table() notices when the table is finished!
Note that for really big tables, this doesn't make a big difference, since the table won't fit in a single response packet anyway.
π₯ Sending Traps π₯
To send a trap, you have to open an SNMP session to the trap receiver. Usually this is a process listening to UDP port 162 on a network management station. Then you can use the trap_request_send() method to encode and send SNMPv1 traps. There is no way to find out whether the trap was actually received at the management station - SNMP traps are fundamentally unreliable. no cap, they really are π
When constructing an SNMPv1 trap, you must provide
- the
enterpriseObject Identifier for the entity that generates the trap - your IP address
- the generic trap type
- the specific trap type
- the
sysUpTimeat the time of trap generation - a sequence (may be empty) of variable bindings further describing the trap.
For SNMPv2 traps, you need:
- the trap's OID
- the
sysUpTimeat the time of trap generation - the bindings list as above
For SNMPv2 traps, the uptime and trap OID are encoded as bindings which are added to the front of the other bindings you provide.
Here is a short example:
my $trap_receiver = "netman.noc";
my $trap_community = "SNMP_Traps";
my $trap_session = $version eq '1'
? SNMP_Session->open ($trap_receiver, $trap_community, 162)
: SNMPv2c_Session->open ($trap_receiver, $trap_community, 162);
my $myIpAddress = ...;
my $start_time = time;
...
sub link_down_trap ($$) {
my ($if_index, $version) = @_;
my $genericTrap = 2; # linkDown
my $specificTrap = 0;
my @ifIndexOID = ( 1,3,6,1,2,1,2,2,1,1 );
my $upTime = int ((time - $start_time) * 100.0);
my @myOID = ( 1,3,6,1,4,1,2946,0,8,15 );
warn "Sending trap failed"
unless ($version eq '1')
? $trap_session->trap_request_send (encode_oid (@myOID),
encode_ip_address ($myIpAddress),
encode_int ($genericTrap),
encode_int ($specificTrap),
encode_timeticks ($upTime),
[encode_oid (@ifIndex_OID,$if_index),
encode_int ($if_index)],
[encode_oid (@ifDescr_OID,$if_index),
encode_string ("foo")])
: $trap_session->v2_trap_request_send (\@linkDown_OID, $upTime,
[encode_oid (@ifIndex_OID,$if_index),
encode_int ($if_index)],
[encode_oid (@ifDescr_OID,$if_index),
encode_string ("foo")]);
}
π Receiving Traps π
Since version 0.60, SNMP_Session.pm supports the receipt and decoding of SNMPv1 trap requests. Since version 0.75, SNMPv2 Trap PDUs are also recognized.
To receive traps, you have to create a special SNMP session that passively listens on the SNMP trap transport address, usually on UDP port 162. Then you can receive traps - actually, SNMPv1 traps, SNMPv2 traps, and SNMPv2 informs, using the receive_trap_1() method and decode them using decode_trap_request(). The enterprise, agent, generic, specific and sysUptime return values are only defined for SNMPv1 traps. In SNMPv2 traps and informs, the equivalent information is contained in the bindings.
my $trap_session = SNMPv1_Session->open_trap_session (162, 0)
or die "cannot open trap session";
my ($trap, $sender_sockaddr) = $trap_session->receive_trap_1 ()
or die "cannot receive trap";
my ($community, $enterprise, $agent,
$generic, $specific, $sysUptime, $bindings)
= $trap_session->decode_trap_request ($trap)
or die "cannot decode trap received"
...
my ($binding, $oid, $value);
while ($bindings ne '') {
($binding,$bindings) = decode_sequence ($bindings);
($oid, $value) = decode_by_template ($binding, "%O%@");
print BER::pretty_oid ($oid)," => ",pretty_print ($value),"\n";
}
π AUTHORS π
Okay bestie, this library was created by Simon Leinen <simon.leinen@switch.ch> β absolute legend, main character energy, we stan. π
And then a whole squad of icons showed up with contributions and fixes:
- Matthew Trunnell
<matter@media.mit.edu> - Tobias Oetiker
<tobi@oetiker.ch> - Heine Peters
<peters@dkrz.de> - Daniel L. Needles
<dan_needles@INS.COM> - Mike Mitchell
<mcm@unx.sas.com> - Clinton Wong
<clintdw@netcom.com> - Alan Nichols
<Alan.Nichols@Ebay.Sun.COM> - Mike McCauley
<mikem@open.com.au> - Andrew W. Elble
<elble@icculus.nsg.nwu.edu> - Brett T Warden
<wardenb@eluminant.com>β gave us a pretty"UInteger32"π - Michael Deegan
<michael@cnspc18.murdoch.edu.au> - Sergio Macedo
<macedo@tmp.com.br> - Jakob Ilves (
/IlvJa)<jakob.ilves@oracle.com>β PDU capture, iconic πΈ - Valerio Bontempi
<v.bontempi@inwind.it>β IPv6 support π - Lorenzo Colitti
<lorenzo@colitti.com>β IPv6 support π - Philippe Simonet
<Philippe.Simonet@swisscom.com>β exported the"avoid..."stuff - Luc Pauwels
<Luc.Pauwels@xalasys.com>β"use_16bit_request_ids" - Andrew Cornford-Matheson
<andrew.matheson@corenetworks.com>β inform - Gerry Dalton
<gerry.dalton@consolidated.com>β fixed that"strict subs"bug π - Mike Fischer
<mlf2@tampabay.rr.com>β passesMSG_DONTWAITto"recv()"
π COPYRIGHT π
Copyright (c) 1995-2009, Simon Leinen. π«Ά
This program is free software; you can redistribute it under the "Artistic License 2.0" included in this distribution (file "Artistic").
okay and that's a wrap on the whole page bestie!! π no cap, you read all four parts, that's slay behaviour fr fr πβ¨
This page is perl v5.36.0, dated 2023-06-16, and it lives under SNMP_Session(3pm). Go forth and poll responsibly, queen. ππ¦π
π¦ where this page comes from
- debian trixie: libsnmp-session-perl 1.16-1 Β· Artistic-2
- ubuntu noble: libsnmp-session-perl 1.16-1 Β· Artistic-2
- ubuntu questing: libsnmp-session-perl 1.16-1
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms