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 theTheirHostnameparameter 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 ifsnmptrapd.confhas"-e 0x8000000001020304", useSecEngineId => '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 theSecEngineIdvalue 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 aVarFormatmathces first (e.g.,$sess->{TypeFormats}{INTEGER} = \&mapEnum();although this can be done more efficiently by enabling$SNMP::use_enumsor session creation param'UseEnums').UseLongNamesβ defaults to the value ofSNMP::use_long_namesat time of session creation. set to non-zero to have<tags>for'getnext'methods generated preferring longer Mib name convention (e.g.,system.sysDescrvs justsysDescr).UseSprintValueβ defaults to the value ofSNMP::use_sprint_valueat time of session creation. set to non-zero to have return values for'get'and'getnext'methods formatted with the librariessnprint_valuefunction. 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 ofSNMP::use_enumsat 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 ofSNMP::use_numericat time of session creation. set to non-zero to have<tags>for get methods returned as numeric OID's rather than descriptions.UseLongNameswill be set so that the full OID is returned to the caller.BestGuessβ defaults to the value ofSNMP::best_guessat 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-Ibin snmpcmd) and setting to 2 causes a random access lookup (defined as-IRin snmpcmd).NonIncreasingβ defaults to the value ofSNMP::non_increasingat 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 translatedDestHostfield.SessPtrβ internal field used to cache a created session structure.RemotePortβ Obsolete. Please use theDestHostspecifier to indicate the hostname and port combination instead of this paramet.
β¨ SNMP::Session methods β¨
$sess->update(<fields>)β Updates theSNMP::Sessionobject with the values fields passed in as a hash list (similar tonew(<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 returnssnmp_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 thegetbulk()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 => \&subroutinecallback => [\&subroutine, optarg1, optarg2, ...]β if a callback is specified,gettablereturns 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 ofSNMP::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 theSecEngineIdparameter when you create a session in the future β¨. Returnsundefif we haven't had any contact with the remote agent yet πΈ.$sess->get_context_engine_idβ likeget_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:- a leaf identifier (e.g.
'sysDescr') β the code just assumes it's unique, which is fine for practical purposes - a fully qualified identifier (e.g.
'.iso.org.dod.internet.mgmt.mib-2.system.sysDescr') - a fully qualified, dotted-decimal, numeric OID (e.g.
'.1.3.6.1.2.1.1.1')
- a leaf identifier (e.g.
<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 octetsINTEGERβ decimal signed integer (or enum)NETADDRβ dotted-decimalIPADDRβ dotted-decimalCOUNTERβ decimal unsigned integerCOUNTER64β decimal unsigned integerGAUGEβ decimal unsigned integerUINTEGERβ decimal unsigned integerTICKSβ decimal unsigned integerOPAQUEβ perl scalar containing octetsNULLβ 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 asyncSNMP::Sessioncalls.MainLoopmust 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 anSNMP::MainLoop()callback function, it makes the currentSNMP::MainLoop()return once that callback is completed. sofinish()is your escape hatch to terminate an otherwise-infiniteMainLoop. and then you can start a brand newMainLoop()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 to0to disable automatic reading of the MIB when a session is created. set it to non-zero to callinitMibat session creation, which loads the MIB according to Net-SNMP env. variables (seeman 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 bySNMP::debuggingβ see below)$SNMP::use_long_namesβ defaults to'0', set it non-zero to enable the use of longer Mib identifiers. seetranslateObj. 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 librariessnprint_valuefunction. can also be set on a per session basis (seeUseSprintValue). 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 (seeUseEnums)$SNMP::use_numericβ defaults to'0', set it non-zero to have<tags>for'get'methods returned as numeric OID's rather than descriptions.UseLongNameswill be set so the entire OID gets returned. set on a per-session basis (seeUseNumeric)$SNMP::best_guessβ defaults to'0'. this setting controls how<tags>are parsed. setting it to0causes a regular lookup. setting it to1causes a regular expression match (defined as-Ibinsnmpcmd) and setting it to2causes a random access lookup (defined as-IRinsnmpcmd). can also be set on a per session basis (seeBestGuess)$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:- enables
'SNMP::verbose'(see above) - level 1 plus
snmp_set_do_debugging(1) - level 2 plus
snmp_set_dump_packet(1)
- enables
$SNMP::dump_packetβ defaults to'0', set [non-]zero to independently setsnmp_set_dump_packet()SNMP::register_debug_tokens()β lets you register one or more debug tokens, exactly like the-Doption ofsnmpd. 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 OIDlabelβ leaf textual identifier (e.g.'sysDescr')subIDβ leaf numeric OID component ofobjectID(e.g.'1')moduleIDβ textual identifier for module (e.g.'RFC1213-MIB')parentβ parent nodechildrenβ array reference of children nodesnextNodeβ next lexico node (BUG! does not return in lexico order π)typeβ returns application type (seegetTypefor 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-CONVENTIONTCDescriptionβ returns the TEXTUAL-CONVENTION's DESCRIPTION field.unitsβ returns UNITShintβ returns HINTenumsβ returns hash ref{tag => num, ...}rangesβ returns array ref of hash ref[{low => num, high => num}, ...]descriptionβ returns DESCRIPTION ($SNMP::save_descriptionsmust be set prior to MIB initialization/parsing)referenceβ returns the REFERENCE clauseindexesβ returns the objects in the INDEX clauseimpliedβ 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 likeinitMib, loading up the MIBs that the environment variables tell it to (peep the Net-SNMPmib_apidocs 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'sinit_mibfunction 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 (seeman mib_api,MIBDIRS,MIBS,MIBFILE(S), etc.)&SNMP::addMibDirs(<dir>,...)β calls the library'sadd_mibdirfor every directory you hand it. this adds the directory(s) to the internal list so they're available for searching in laterloadModulescalls π«Ά&SNMP::addMibFiles(<file>,...)β calls the library'sread_mibfunction. 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'sread_modulefunction. 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_namesis 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_guessoption is what's driving. and if no Mib is loaded when you call it and$SNMP::auto_init_mibis 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,COUNTERGAUGE,TIMETICKS,OPAQUE, orundef&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 ofSNMP::Session::newfollowed by the args ofSNMP::Session::get&snmp_getnext()β takes the args ofSNMP::Session::newfollowed by the args ofSNMP::Session::getnext&snmp_set()β takes the args ofSNMP::Session::newfollowed by the args ofSNMP::Session::set&snmp_trap()β takes the args ofSNMP::TrapSession::newfollowed by the args ofSNMP::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 π
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
- ubuntu stonking: libsnmp-perl 5.9.5.2+dfsg-2.1ubuntu5 Β· BSD-3-Clause
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms