SNMP(3pm)

πŸ’– SNMP(3pm) πŸ’–

User Contributed Perl Documentation β€” but make it bestie-coded ✨

✨ NAME ✨

SNMP β€” The Perl5 'SNMP' Extension Module for the Net-SNMP SNMP package. πŸ’…

🌸 SYNOPSIS 🌸

use SNMP;
...
$sess = new SNMP::Session(DestHost => localhost, Community => public);
$val = $sess->get('sysDescr.0');
...
$vars = new SNMP::VarList([sysDescr,0], [sysContact,0], [sysLocation,0]);
@vals = $sess->get($vars);
...
$vb = new SNMP::Varbind();
do {
   $val = $sess->getnext($vb);
   print "@{$vb}\n";
} until ($sess->{ErrorNum});
...
$SNMP::save_descriptions = 1;
SNMP::initMib(); # assuming mib is not already loaded
print "$SNMP::MIB{sysDescr}{description}\n";

πŸ¦‹ DESCRIPTION πŸ¦‹

okay so lowkey first things first, bestie: the perl SNMP 5.0 module that comes with net-snmp 5.0 and higher is different than previous versions in a number of ways. Most importantly, it behaves like a proper net-snmp application and calls init_snmp properly, which means it will read configuration files and use those defaults where appropriate automatically parse MIB files, etc. πŸ’– This will likely affect your perl applications if you have, for instance, default values set up in your snmp.conf file (as the perl module will now make use of those defaults). The documentation, however, has sadly not been updated yet (aside from this note), nor is the read_config default usage implementation fully complete. 😭

The basic operations of the SNMP protocol are provided by this module through an object oriented interface for modularity and ease of use. The primary class is SNMP::Session which encapsulates the persistent aspects of a connection between the management application and the managed agent. Internally the class is implemented as a blessed hash reference. This class supplies 'get', 'getnext', 'set', 'fget', and 'fgetnext' method calls. The methods take a variety of input argument formats and support both synchronous and asynchronous operation through a polymorphic API (i.e., method behaviour varies dependent on args passed - see below). πŸ¦‹


πŸ‘‘ SNMP::Session πŸ‘‘

$sess = new SNMP::Session(DestHost => 'host', ...)

The following arguments may be passed to new as a hash. periodt. πŸ’…

✨ Basic Options ✨

  • DestHost β€” Hostname or IP address of the SNMP agent you want to talk to. Specified in Net-SNMP formatted agent addresses. These addresses typically look like one of the following:
localhost
tcp:localhost
tls:localhost
tls:localhost:9876
udp6:[::1]:9876
unix:/some/path/to/file/socket

Defaults to 'localhost'.

  • Version β€” SNMP version to use. The default is taken from library configuration - probably 3 [1, 2 (same as 2c), 2c, 3].
  • Timeout β€” The number of micro-seconds to wait before resending a request. The default is '1000000'.
  • Retries β€” The number of times to retry a request. The default is '5'.
  • RetryNoSuch β€” If enabled NOSUCH errors in 'get' pdus will be repaired, removing the varbind in error, and resent - undef will be returned for all NOSUCH varbinds, when set to '0' this feature is disabled and the entire get request will fail on any NOSUCH error (applies to v1 only). The default is '0'.

✨ SNMPv3/TLS Options ✨

  • OurIdentity β€” Our X.509 identity to use, which should either be a fingerprint or the filename that holds the certificate.
  • TheirIdentity β€” The remote server's identity to connect to, specified as either a fingerprint or a file name. Either this must be specified, or the hostname below along with a trust anchor.
  • TheirHostname β€” The remote server's hostname that is expected. If their certificate was signed by a CA then their hostname presented in the certificate must match this value or the connection fails to be established (to avoid man-in-the-middle attacks).
  • TrustCert β€” A trusted certificate to use as trust anchor (like a CA certificate) for verifying a remote server's certificate. If a CA certificate is used to validate a certificate then the TheirHostname parameter must also be specified to ensure their presented hostname in the certificate matches.

✨ SNMPv3/USM Options ✨

  • SecName β€” The SNMPv3 security name to use (most for SNMPv3 with USM). The default is 'initial'.
  • SecLevel β€” The SNMPv3 security level to use [noAuthNoPriv, authNoPriv, authPriv] (v3). The default is 'noAuthNoPriv'.
  • SecEngineId β€” The SNMPv3 security engineID to use (if the snmpv3 security model needs it; for example USM). The format is as a string without the leading '0x'. So if snmptrapd.conf has "-e 0x8000000001020304", use SecEngineId => '8000000001020304'. The default is <none>, security engineID and it will be probed if not supplied (v3).
  • ContextEngineId β€” The SNMPv3 context engineID to use. The default is the <none> and will be set either to the SecEngineId value if set or discovered or will be discovered in other ways if using TLS (RFC5343 based discovery).
  • Context β€” The SNMPv3 context name to use. The default is '' (an empty string).
  • AuthProto β€” The SNMPv3/USM authentication protocol to use [MD5, SHA]. The default is 'MD5'.
  • AuthPass β€” The SNMPv3/USM authentication passphrase to use. default <none>, authentication passphrase.
  • PrivProto β€” The SNMPv3/USM privacy protocol to use [DES, AES]. The default is 'DES'.
  • PrivPass β€” The SNMPv3/USM privacy passphrase to use. default <none>, privacy passphrase (v3).
  • AuthMasterKey, PrivMasterKey, AuthLocalizedKey, PrivLocalizedKey β€” Directly specified SNMPv3 USM user keys (used if you want to specify the keys instead of deriving them from a password as above).

✨ SNMPv1 and SNMPv2c Options ✨

  • Community β€” For SNMPv1 and SNMPv2c, the clear-text community name to use. The default is 'public'.

✨ Other Configuration Options ✨

  • VarFormats β€” default 'undef', used by 'fget[next]', holds an hash reference of output value formatters, (e.g., {<obj> => <sub-ref>, ... }, <obj> must match the <obj> and format used in the get operation. A special <obj>, '*', may be used to apply all <obj>s, the supplied sub is called to translate the value to a new format. The sub is called passing the Varbind as the arg.
  • TypeFormats β€” default 'undef', used by 'fget[next]', holds an hash reference of output value formatters, (e.g., {<type> => <sub-ref>, ... }, the supplied sub is called to translate the value to a new format, unless a VarFormat mathces first (e.g., $sess->{TypeFormats}{INTEGER} = \&mapEnum(); although this can be done more efficiently by enabling $SNMP::use_enums or session creation param 'UseEnums').
  • UseLongNames β€” defaults to the value of SNMP::use_long_names at time of session creation. set to non-zero to have <tags> for 'getnext' methods generated preferring longer Mib name convention (e.g., system.sysDescr vs just sysDescr).
  • UseSprintValue β€” defaults to the value of SNMP::use_sprint_value at time of session creation. set to non-zero to have return values for 'get' and 'getnext' methods formatted with the libraries snprint_value function. This will result in certain data types being returned in non-canonical format Note: values returned with this option set may not be appropriate for 'set' operations (see discussion of value formats in <vars> description section).
  • UseEnums β€” defaults to the value of SNMP::use_enums at time of session creation. set to non-zero to have integer return values converted to enumeration identifiers if possible, these values will also be acceptable when supplied to 'set' operations.
  • UseNumeric β€” defaults to the value of SNMP::use_numeric at time of session creation. set to non-zero to have <tags> for get methods returned as numeric OID's rather than descriptions. UseLongNames will be set so that the full OID is returned to the caller.
  • BestGuess β€” defaults to the value of SNMP::best_guess at time of session creation. this setting controls how <tags> are parsed. setting to 0 causes a regular lookup. setting to 1 causes a regular expression match (defined as -Ib in snmpcmd) and setting to 2 causes a random access lookup (defined as -IR in snmpcmd).
  • NonIncreasing β€” defaults to the value of SNMP::non_increasing at time of session creation. this setting controls if a non-increasing OID during bulkwalk will causes an error. setting to 0 causes the default behaviour (which may, in very badly performing agents, result in a never-ending loop). setting to 1 causes an error (OID not increasing) when this error occur.
  • ErrorStr β€” read-only, holds the error message assoc. w/ last request.
  • ErrorNum β€” read-only, holds the snmp_err or staus of last request.
  • ErrorInd β€” read-only, holds the snmp_err_index when appropriate.
  • Private variables:
    • DestAddr β€” internal field used to hold the translated DestHost field.
    • SessPtr β€” internal field used to cache a created session structure.
    • RemotePort β€” Obsolete. Please use the DestHost specifier to indicate the hostname and port combination instead of this paramet.

✨ SNMP::Session methods ✨

  • $sess->update(<fields>) β€” Updates the SNMP::Session object with the values fields passed in as a hash list (similar to new(<fields>)) (WARNING! not fully implemented).
  • $sess->get(<vars> [,<callback>]) β€” do SNMP GET, multiple <vars> formats accepted. for syncronous operation <vars> will be updated with value(s) and type(s) and will also return retrieved value(s). If <callback> supplied method will operate asynchronously.
  • $sess->fget(<vars> [,<callback>]) β€” do SNMP GET like 'get' and format the values according the handlers specified in $sess->{VarFormats} and $sess->{TypeFormats}.
  • $sess->getnext(<vars> [,<callback>]) β€” do SNMP GETNEXT, multiple <vars> formats accepted, returns retrieved value(s), <vars> passed as arguments are updated to indicate next lexicographical <obj>,<iid>,<val>, and <type>. Note: simple string <vars>,(e.g., 'sysDescr.0') form is not updated. If <callback> supplied method will operate asynchronously.
  • $sess->fgetnext(<vars> [,<callback>]) β€” do SNMP GETNEXT like getnext and format the values according the handlers specified in $sess->{VarFormats} and $sess->{TypeFormats}.
  • $sess->set(<vars> [,<callback>]) β€” bestie this is how you do an SNMP SET πŸ’…, and it takes multiple <vars> formats, so no stress. Just know that the value field in every one of those <vars> formats has to be in a canonical format (i.e., a well known format) so the translation to an SNMP MIB data value is totally unambiguous β€” the canonical value format stuff is covered up in the <vars> description section, go peek 🫢. It returns snmp_errno. And if you hand it a <callback>, the method goes asynchronous on you ✨
  • $sess->getbulk(<non-repeaters>, <max-repeaters>, <vars>) β€” does an SNMP GETBULK πŸ”₯. From the list of Varbinds, the single next lexico instance gets fetched for the first n Varbinds, where n is what you put in <non-repeaters>. For the remaining Varbinds, the m lexico instances are retrieved for each of the remaining ones, and m is <max-repeaters> πŸ‘‘
  • $sess->bulkwalk(<non-repeaters>, <max-repeaters>, <vars> [,<callback>]) β€” the "bulkwalk" of the Varbind list πŸ’–. It works by sending a GETBULK request (that's the getbulk() above, iykyk) for the Varbinds. For each requested variable, the response gets examined to see whether the next lexico instance has left the requested sub-tree πŸ¦‹. Any further instances that come back for that variable get ignored, and the walk for that sub-tree is considered complete, periodt.

And if any sub-trees weren't done by the time the end of the responses is reached, another request gets composed out of the remaining variables ✨. That whole process repeats until either all sub-trees are complete, or too many packets have been exchanged (which is the guard against loops, thank u).

bulkwalk() returns an array containing an array of Varbinds, one for each requested variable, in the order of the variable requests 🌸. On error it returns undef and sets $sess->ErrorStr and $sess->ErrorNum 😭. If you supply a callback, bulkwalk() returns the SNMP request id and returns immediately β€” the callback gets called with the supplied argument list and the returned variables list πŸ’œ.

Note: because the client has to "discover" that the tree is complete by comparing the returned variables with the ones that were requested, there's a potential "gotcha" lurking when you use the max-repeaters value πŸ‘€. Consider this code to print a list of interfaces and byte counts:
$numInts = $sess->get('ifNumber.0');
($desc, $in, $out) = $sess->bulkwalk(0, $numInts,
              [['ifDescr'], ['ifInOctets'], ['ifOutOctets']]);

for $i (0..($numInts - 1)) {
    printf "Interface %4s: %s inOctets, %s outOctets\n",
              $$desc[$i]->val, $$in[$i]->val, $$out[$i]->val;
}

This code will produce two requests to the agent β€” the first to get the interface values, and the second to discover that all the information was already in the first packet πŸ’€. To get around this, use $numInts + 1 for the max_repeaters value. That asks the agent to include one additional (unrelated) variable that signals the end of the sub-tree, which lets bulkwalk() figure out the request is complete πŸŽ€.

  • $results = $sess->gettable(<TABLE OID>, <OPTIONS>) β€” this one retrieves an entire table of data and hands back a hash reference to it 🌈. The returned hash reference has the OID suffixes for the index data as its keys, and the value for each entry is another hash holding the data for that row. The keys to that hash are the column names, and the values are the actual data ✨.

Example:

#!/usr/bin/perl

use SNMP;
use Data::Dumper;

my $s = new SNMP::Session(DestHost => 'localhost');

print Dumper($s->gettable('ifTable'));

On my machine it produces:

$VAR1 = {
          '6' => {
                   'ifMtu' => '1500',
                   'ifPhysAddress' => 'PV',
                   # ...
                   'ifInUnknownProtos' => '0'
                 },
          '4' => {
                   'ifMtu' => '1480',
                   'ifPhysAddress' => '',
                   # ...
                   'ifInUnknownProtos' => '0'
                 },
          # ...
         };

By default it tries to do the retrieval as optimized as possible β€” it'll request multiple columns at once and use GETBULK if it can πŸ”₯. There are a few options you can specify by passing in an OPTIONS hash with various parameters:

  • noindexes => 1 β€” tells the code NOT to parse the indexes and place the results in the second hash πŸ™ˆ. If you don't need the index data, this is faster, periodt.
  • columns => [ colname1, ... ] β€” this specifies which columns to collect 🌸. By default it'll try to collect all the columns defined in the MIB table.
  • repeat => COUNT β€” specifies a GETBULK repeat COUNT. Meaning it'll request this many varbinds back per column when it uses the GETBULK operation πŸ’…. Shortening this makes smaller packets, which can genuinely help when you're going through some systems. By default this value is calculated and it tries to guess at what will fit all the results into 1000 bytes. That calculation is fairly safe, hopefully, but you can raise or lower the number with this option if you want 🫢. On lossy networks you want to make sure the packets don't get fragmented, and lowering this value is one way to help with that.
  • nogetbulk => 1 β€” forces the use of GETNEXT rather than GETBULK πŸ‘‘. (This is always true for SNMPv1, since it doesn't have GETBULK anyway.) Some agents are great implementers of GETBULK, and this lets you force GETNEXT operations instead.
  • callback => \&subroutine
  • callback => [\&subroutine, optarg1, optarg2, ...] β€” if a callback is specified, gettable returns quickly without returning results ⚑. When the results are finally retrieved, the callback subroutine gets called (go read the other sections that define callback behaviour, and how to make use of SNMP::MainLoop, which is required for this to work). An additional argument of the normal hash result gets added to the callback subroutine arguments πŸ’–.
Note 1: internally, the gettable function uses its own callbacks, which get passed to getnext/getbulk as appropriate.
Note 2: callback support is only available in the SNMP module version 5.04 and above πŸŽ€. To test for this in code intending to support both versions prior to 5.04 and 5.04 and up, the following should work:
if ($response = $sess->gettable('ifTable', callback => \&my_sub)) {
    # got a response, gettable doesn't support callback
    my_sub($response);
    $no_mainloop = 1;
}

Deciding on whether to use SNMP::MainLoop is left as an exercise to the reader, since it depends on whether your code uses other callbacks as well 😌.

  • $sess->get_sec_engine_id β€” returns the security engine ID for the current session, whether it was probed or provided by the client, in hex format suitable for the SecEngineId parameter when you create a session in the future ✨. Returns undef if we haven't had any contact with the remote agent yet 🌸.
  • $sess->get_context_engine_id β€” like get_sec_engine_id, but for the context engine ID (ContextEngineId) πŸ’œ.

πŸ’– SNMP::TrapSession πŸ’–

$sess = new SNMP::Session(DestHost => 'host', ...)

It supports all applicable fields from SNMP::Session (see above, bestie 🫢).

πŸŽ€ SNMP::TrapSession methods πŸŽ€

  • $sess->trap(enterprise, agent, generic, specific, uptime, <vars>)
$sess->trap(enterprise=>'.1.3.6.1.4.1.2021', # or 'ucdavis' [default]
            agent => '127.0.0.1', # or 'localhost',[dflt 1st intf on host]
            generic => specific,  # can be omitted if 'specific' supplied
            specific => 5,        # can be omitted if 'generic' supplied
            uptime => 1234,       # dflt to localhost uptime (0 on win32)
            [[ifIndex, 1, 1],[sysLocation, 0, "here"]]); # optional vars
                                                         # always last
  • trap(oid, uptime, <vars>) β€” this is the v2 format 🌈
$sess->trap(oid => 'snmpRisingAlarm',
            uptime => 1234,
            [[ifIndex, 1, 1],[sysLocation, 0, "here"]]); # optional vars
                                                         # always last

Acceptable variable formats πŸŽ€

so <vars> can show up in any one of these shapes, bestie:

SNMP::VarList ✨

an array of MIB objects to get or set β€” literally a blessed reference to an array stuffed with SNMP::Varbinds, like [<varbind1>, <varbind2>, ...]

SNMP::Varbind 🌸

one single MIB object to get or set β€” a blessed reference to a 4 element array, and the shape is [<obj>, <iid>, <val>, <type>]. let's break down every slot:

  • <obj> β€” one of these three vibes:
    1. a leaf identifier (e.g. 'sysDescr') β€” the code just assumes it's unique, which is fine for practical purposes
    2. a fully qualified identifier (e.g. '.iso.org.dod.internet.mgmt.mib-2.system.sysDescr')
    3. a fully qualified, dotted-decimal, numeric OID (e.g. '.1.3.6.1.2.1.1.1')
  • <iid> β€” the dotted-decimal, instance identifier. for scalar MIB objects you use '0', periodt.
  • <val> β€” the SNMP data value retrieved from, or being set to, the agent's MIB. for (f)get(next) operations <val> can be in a whole variety of formats, all depending on your session and package settings 🫢. but for set operations, <val> has got to be canonical, so the translation stays unambiguous, no guessing. the canonical forms are:
    • OBJECTID β€” dotted-decimal (e.g. .1.3.6.1.2.1.1.1)
    • OCTETSTR β€” perl scalar containing octets
    • INTEGER β€” decimal signed integer (or enum)
    • NETADDR β€” dotted-decimal
    • IPADDR β€” dotted-decimal
    • COUNTER β€” decimal unsigned integer
    • COUNTER64 β€” decimal unsigned integer
    • GAUGE β€” decimal unsigned integer
    • UINTEGER β€” decimal unsigned integer
    • TICKS β€” decimal unsigned integer
    • OPAQUE β€” perl scalar containing octets
    • NULL β€” perl scalar containing nothing
  • <type> β€” the SNMP data type (peep the list right above this ✨). this field gets populated for you by 'get' and 'getnext' operations. sometimes though, the programmer has to fill it in themselves when handing it to a 'set' operation. it doesn't need to be supplied when the attribute indicated by <tag> is already described by loaded Mib modules. but for 'set's β€” if you're using a numeric OID and the object is not currently in the loaded Mib, you must supply the <type> field. no exceptions, fr fr.

simple string πŸ¦‹

the light weight form of <var>, used to 'set' or 'get' a single attribute without ever constructing an SNMP::Varbind. it lives in a perl scalar and looks like '<tag>.<iid>' (e.g. 'sysDescr.0'). for 'set' operations the value gets passed as a second arg. Note: this argument form is not updated in get[next] operations the way the other forms are β€” so don't get caught lacking.


Acceptable callback formats πŸ’…

<callback> can be one of these:

  • with no arguments:
\&subname
sub { ... }
  • or with arguments:
[ \&subname, $arg1, ... ]
[ sub { ... }, $arg1, ... ]
[ "method", $obj, $arg1, ... ]

the callback gets called when a response is received or a timeout occurs. the last argument passed to the callback will be an SNMP::VarList reference. in the case of a timeout, that last argument is undef. 😭

  • &SNMP::MainLoop([<timeout>, [<callback>]]) β€” this one's for use with async SNMP::Session calls. MainLoop must be called after the initial async calls so the return packets from the agent actually get processed. if you supply no args at all, this function enters an infinite loop β€” so the program has to be exited in a callback or interrupted externally. If `<timeout(sic)
  • &SNMP::finish() β€” when you call this from inside an SNMP::MainLoop() callback function, it makes the current SNMP::MainLoop() return once that callback is completed. so finish() is your escape hatch to terminate an otherwise-infinite MainLoop. and then you can start a brand new MainLoop() instance to handle further requests. iconic.

SNMP package variables and functions πŸ‘‘

  • $SNMP::VERSION β€” the current version specifier (e.g. 3.1.0)
  • $SNMP::auto_init_mib β€” defaults to '1', set it to 0 to disable automatic reading of the MIB when a session is created. set it to non-zero to call initMib at session creation, which loads the MIB according to Net-SNMP env. variables (see man mib_api)
  • $SNMP::verbose β€” defaults to '0', controls warning/info output of the SNMP module. 0 => no output, 1 => enables warning/info output from the SNMP module itself (it's also controlled by SNMP::debugging β€” see below)
  • $SNMP::use_long_names β€” defaults to '0', set it non-zero to enable the use of longer Mib identifiers. see translateObj. it'll also influence the formatting of <tag> in varbinds returned from 'getnext' operations. can be set on a per session basis too (UseLongNames)
  • $SNMP::use_sprint_value β€” defaults to '0', set it non-zero to enable formatting of response values using the snmp libraries snprint_value function. can also be set on a per session basis (see UseSprintValue). Note: the returned values may not be suitable for 'set' operations πŸ™ˆ
  • $SNMP::use_enums β€” defaults to '0', set it non-zero to return values as enums and allow sets using enums where appropriate. integer data will still be accepted for set operations. can also be set on a per session basis (see UseEnums)
  • $SNMP::use_numeric β€” defaults to '0', set it non-zero to have <tags> for 'get' methods returned as numeric OID's rather than descriptions. UseLongNames will be set so the entire OID gets returned. set on a per-session basis (see UseNumeric)
  • $SNMP::best_guess β€” defaults to '0'. this setting controls how <tags> are parsed. setting it to 0 causes a regular lookup. setting it to 1 causes a regular expression match (defined as -Ib in snmpcmd) and setting it to 2 causes a random access lookup (defined as -IR in snmpcmd). can also be set on a per session basis (see BestGuess)
  • $SNMP::save_descriptions β€” defaults to '0', set it non-zero to have the mib parser save attribute descriptions. must be set prior to mib initialization ⚠️
  • $SNMP::debugging β€” defaults to '0', controls debugging output level within the SNMP module and libsnmp:
    1. enables 'SNMP::verbose' (see above)
    2. level 1 plus snmp_set_do_debugging(1)
    3. level 2 plus snmp_set_dump_packet(1)
  • $SNMP::dump_packet β€” defaults to '0', set [non-]zero to independently set snmp_set_dump_packet()
  • SNMP::register_debug_tokens() β€” lets you register one or more debug tokens, exactly like the -D option of snmpd. each debug token enables a group of debug statements. an example: SNMP::register_debug_tokens("tdomain,netsnmp_unix");

%SNMP::MIB 🌈

a tied hash that gives you access to parsed MIB information. once the MIB is loaded, this hash lets you at all the parsed-in MIB meta-data (the structure of the MIB, i.e. the schema). the hash hands back blessed references to SNMP::MIB::NODE objects, and each one of those represents a single MIB attribute 🫢. you can fetch the nodes with multiple 'key' formats β€” the leaf name (e.g. sysDescr), or the fully/partially qualified name (e.g. system.sysDescr), or the fully qualified numeric OID. the returned node object supports all these fields:

  • objectID β€” dotted decimal fully qualified OID
  • label β€” leaf textual identifier (e.g. 'sysDescr')
  • subID β€” leaf numeric OID component of objectID (e.g. '1')
  • moduleID β€” textual identifier for module (e.g. 'RFC1213-MIB')
  • parent β€” parent node
  • children β€” array reference of children nodes
  • nextNode β€” next lexico node (BUG! does not return in lexico order πŸ’€)
  • type β€” returns application type (see getType for values)
  • access β€” returns ACCESS (ReadOnly, ReadWrite, WriteOnly, NoAccess, Notify, Create)
  • status β€” returns STATUS (Mandatory, Optional, Obsolete, Deprecated)
  • syntax β€” returns 'textualConvention' if defined, else 'type'
  • textualConvention β€” returns TEXTUAL-CONVENTION
  • TCDescription β€” returns the TEXTUAL-CONVENTION's DESCRIPTION field.
  • units β€” returns UNITS
  • hint β€” returns HINT
  • enums β€” returns hash ref {tag => num, ...}
  • ranges β€” returns array ref of hash ref [{low => num, high => num}, ...]
  • description β€” returns DESCRIPTION ($SNMP::save_descriptions must be set prior to MIB initialization/parsing)
  • reference β€” returns the REFERENCE clause
  • indexes β€” returns the objects in the INDEX clause
  • implied β€” returns true if the last object in the INDEX is IMPLIED

🌸 MIB Functions 🌸

okay bestie these are the ones that talk directly to the MIB layers, and they're kinda the whole vibe of the module, ngl.

  • &SNMP::setMib(<file>) β€” this one lets you parse a MIB dynamically and specify the exact MIB file yourself, without letting environment variables boss you around. call it with no args and it acts like initMib, loading up the MIBs that the environment variables tell it to (peep the Net-SNMP mib_api docs for the deets). if you pass a non-zero second arg it forces the previous MIB to be freed and replaced β€” πŸ’€ but heads up: that second arg has not been working since freeing the previous Mib turned out to be way more involved than it used to be).
  • &SNMP::initMib() β€” calls the library's init_mib function if the Mib isn't already loaded β€” if it's already loaded it just does nothing, chill. it'll parse directories and load modules according to the environment variables described in the Net-SNMP docs (see man mib_api, MIBDIRS, MIBS, MIBFILE(S), etc.)
  • &SNMP::addMibDirs(<dir>,...) β€” calls the library's add_mibdir for every directory you hand it. this adds the directory(s) to the internal list so they're available for searching in later loadModules calls 🫢
  • &SNMP::addMibFiles(<file>,...) β€” calls the library's read_mib function. the file(s) you supply get read and every Mib module definition inside them gets added to the internal mib tree structure ✨
  • &SNMP::loadModules(<mod>,...) β€” calls the library's read_module function. the module(s) you give it get searched for in the current mibdirs and added to the internal mib tree. pass the special <mod> value 'ALL' and literally every known module gets loaded, iconic behaviour πŸ’…
  • &SNMP::unloadModules(<mod>,...) β€” Not Implemented. she's not here, bestie 😭
  • &SNMP::translateObj(<var>[,arg,[arg]]) β€” converts a text obj tag to an OID, and vice-versa. any iid suffix it finds gets retained numerically. default behaviour when converting a numeric OID to text form is to return only the leaf identifier (like 'sysDescr'), but when $SNMP::use_long_names is non-zero β€” or you supply a non-zero second arg β€” it returns a longer textual identifier instead. an optional third argument that's non-zero makes it prepend the module name to the text name (like 'SNMPv2-MIB::sysDescr'). when it's converting a text obj, the $SNMP::best_guess option is what's driving. and if no Mib is loaded when you call it and $SNMP::auto_init_mib is enabled, the Mib will get loaded for you. returns 'undef' on failure πŸ˜”
  • &SNMP::getType(<var>) β€” returns the SNMP data type for the textual identifier you give it: OBJECTID, OCTETSTR, INTEGER, NETADDR, IPADDR, COUNTER GAUGE, TIMETICKS, OPAQUE, or undef
  • &SNMP::mapEnum(<var>) β€” converts an integer value into the enumertion tag defined in the Mib, or converts a tag into an integer, depending on what you feed it. it returns the corresponding integer value or tag for a given MIB attribute and value, and it can sense which direction to convert all on its own, no cap. various arg formats are supported:
$val = SNMP::mapEnum($varbind);

where $varbind is an SNMP::Varbind or equivalent. note: $varbind will be updated πŸ‘€

$val = SNMP::mapEnum('ipForwarding', 'forwarding');
$val = SNMP::mapEnum('ipForwarding', 1);

🧚 Exported SNMP utility functions 🧚

Note: utility functions do not support async operation yet. 😭
  • &snmp_get() β€” takes the args of SNMP::Session::new followed by the args of SNMP::Session::get
  • &snmp_getnext() β€” takes the args of SNMP::Session::new followed by the args of SNMP::Session::getnext
  • &snmp_set() β€” takes the args of SNMP::Session::new followed by the args of SNMP::Session::set
  • &snmp_trap() β€” takes the args of SNMP::TrapSession::new followed by the args of SNMP::TrapSession::trap

πŸ’€ Trouble Shooting πŸ’€

okay if things are going wrong, there are a bunch of places to look to narrow down what's actually happening. vibe check time, let's go through them.

the first step should be to test the Net-SNMP installation independently from the Perl5 SNMP interface.

try running the apps from the Net-SNMP distribution.

make sure your agent (snmpd) is running and properly configured with read-write access for the community you're using.

ensure that your MIBs are installed and enviroment variables are set appropriately (see man mib_api).

be sure to remove old net-snmp installations, and make sure headers and libraries from old CMU installations aren't being used by mistake πŸ™ˆ

if the problem happens during compilation/linking, check that the snmp library being linked is actually the Net-SNMP library (there have been name conflicts with existing snmp libs, it's giving chaos).

also check that the header files are correct and up to date.

sometimes compiling the Net-SNMP library with 'position-independent-code' enabled is required (HPUX specifically).

if you cannot resolve the problem you can post to comp.lang.perl.modules or net-snmp-users@net-snmp-users@lists.sourceforge.net

please give sufficient information to analyze the problem (OS type, versions for OS/Perl/Net-SNMP/compiler, complete error output, etc.) πŸ™


πŸŽ€ Acknowledgements πŸŽ€

many thanks to all those who supplied patches, suggestions and feedback. genuinely, we're obsessed with you all πŸ’–

  • Joe Marzot (the original author)
  • Wes Hardaker and the net-snmp-coders
  • Dave Perkins
  • Marcel Wiget
  • David Blackburn
  • John Stofell
  • Gary Hayward
  • Claire Harrison
  • Achim Bohnet
  • Doug Kingston
  • Jacques Vidrine
  • Carl Jacobsen
  • Wayne Marquette
  • Scott Schumate
  • Michael Slifcak
  • Srivathsan Srinivasagopalan
  • Bill Fenner
  • Jef Peeraer
  • Daniel Hagerty
  • Karl "Rat" Schilke and Electric Lightwave, Inc.
  • Perl5 Porters
  • Alex Burger

apologies to any/all who's patch/feature/request was not mentioned or included β€” most likely it was lost when paying work intruded on my fun. please try again if you do not see a desired feature. this may actually turn out to be a decent package with such excellent help and the fact that I have more time to work on it than in the past. 🫢


πŸ‘‘ AUTHOR πŸ‘‘

bugs, comments, questions to net-snmp-users@lists.sourceforge.net


     Copyright (c) 1995-2000 G. S. Marzot. All rights reserved.
     This program is free software; you can redistribute it and/or
     modify it under the same terms as Perl itself.

     Copyright (c) 2001-2002 Networks Associates Technology, Inc.  All
     Rights Reserved.  This program is free software; you can
     redistribute it and/or modify it under the same terms as Perl
     itself.

and that's a wrap bestie πŸ’… this whole page was perl v5.42.3, dated 2026-09-29, for SNMP(3pm) β€” go be the main character of your own monitoring setup, ily πŸ¦‹βœ¨

πŸ“¦ where this page comes from