1Net::SNMP(3)          User Contributed Perl Documentation         Net::SNMP(3)
2
3
4

NAME

6       Net::SNMP - Object oriented interface to SNMP
7

SYNOPSIS

9       The Net::SNMP module implements an object oriented interface to the
10       Simple Network Management Protocol.  Perl applications can use the
11       module to retrieve or update information on a remote host using the
12       SNMP protocol.  The module supports SNMP version-1, SNMP version-2c
13       (Community-Based SNMPv2), and SNMP version-3. The Net::SNMP module
14       assumes that the user has a basic understanding of the Simple Network
15       Management Protocol and related network management concepts.
16

DESCRIPTION

18       The Net::SNMP module abstracts the intricate details of the Simple
19       Network Management Protocol by providing a high level programming
20       interface to the protocol.  Each Net::SNMP object provides a one-to-one
21       mapping between a Perl object and a remote SNMP agent or manager.  Once
22       an object is created, it can be used to perform the basic protocol
23       exchange actions defined by SNMP.
24
25       A Net::SNMP object can be created such that it has either "blocking" or
26       "non-blocking" properties.  By default, the methods used to send SNMP
27       messages do not return until the protocol exchange has completed
28       successfully or a timeout period has expired. This behavior gives the
29       object a "blocking" property because the flow of the code is stopped
30       until the method returns.
31
32       The optional named argument -nonblocking can be passed to the object
33       constructor with a true value to give the object "non-blocking"
34       behavior.  A method invoked by a non-blocking object queues the SNMP
35       message and returns immediately, allowing the flow of the code to
36       continue. The queued SNMP messages are not sent until an event loop is
37       entered by calling the "snmp_dispatcher()" method.  When the SNMP
38       messages are sent, any response to the messages invokes the subroutine
39       defined by the user when the message was originally queued. The event
40       loop exits when all messages have been removed from the queue by either
41       receiving a response, or by exceeding the number of retries at the
42       Transport Layer.
43
44   Blocking Objects
45       The default behavior of the methods associated with a Net::SNMP object
46       is to block the code flow until the method completes.  For methods that
47       initiate a SNMP protocol exchange requiring a response, a hash
48       reference containing the results of the query is returned. The
49       undefined value is returned by all methods when a failure has occurred.
50       The "error()" method can be used to determine the cause of the failure.
51
52       The hash reference returned by a SNMP protocol exchange points to a
53       hash constructed from the VarBindList contained in the SNMP response
54       message.  The hash is created using the ObjectName and the ObjectSyntax
55       pairs in the VarBindList.  The keys of the hash consist of the OBJECT
56       IDENTIFIERs in dotted notation corresponding to each ObjectName in the
57       VarBindList.  The value of each hash entry is set equal to the value of
58       the corresponding ObjectSyntax.  This hash reference can also be
59       retrieved using the "var_bind_list()" method.
60
61   Non-blocking Objects
62       When a Net::SNMP object is created having non-blocking behavior, the
63       invocation of a method associated with the object returns immediately,
64       allowing the flow of the code to continue.  When a method is invoked
65       that would initiate a SNMP protocol exchange requiring a response,
66       either a true value (i.e. 0x1) is returned immediately or the undefined
67       value is returned if there was a failure.  The "error()" method can be
68       used to determine the cause of the failure.
69
70       The contents of the VarBindList contained in the SNMP response message
71       can be retrieved by calling the "var_bind_list()" method using the
72       object reference passed as the first argument to the callback.  The
73       value returned by the "var_bind_list()" method is a hash reference
74       created using the ObjectName and the ObjectSyntax pairs in the
75       VarBindList.  The keys of the hash consist of the OBJECT IDENTIFIERs in
76       dotted notation corresponding to each ObjectName in the VarBindList.
77       The value of each hash entry is set equal to the value of the
78       corresponding ObjectSyntax. The undefined value is returned if there
79       has been a failure and the "error()" method may be used to determine
80       the reason.
81

METHODS

83       When named arguments are expected by the methods, two different styles
84       are supported.  All examples in this documentation use the dashed-
85       option style:
86
87              $object->method(-argument => $value);
88
89       However, the IO:: style is also allowed:
90
91              $object->method(Argument => $value);
92
93       Non-blocking Objects Arguments
94           When a Net::SNMP object has been created with a "non-blocking"
95           property, most methods that generate a SNMP message take additional
96           arguments to support this property.
97
98           Callback
99               Most methods associated with a non-blocking object have an
100               optional named argument called -callback.  The -callback
101               argument expects a reference to a subroutine or to an array
102               whose first element must be a reference to a subroutine.  The
103               subroutine defined by the -callback option is executed when a
104               response to a SNMP message is received, an error condition has
105               occurred, or the number of retries for the message has been
106               exceeded.
107
108               When the -callback argument only contains a subroutine
109               reference, the subroutine is evaluated passing a reference to
110               the original Net::SNMP object as the only parameter.  If the
111               -callback argument was defined as an array reference, all
112               elements in the array are passed to subroutine after the
113               reference to the Net::SNMP object.  The first element, which is
114               required to be a reference to a subroutine, is removed before
115               the remaining arguments are passed to that subroutine.
116
117               Once one method is invoked with the -callback argument, this
118               argument stays with the object and is used by any further calls
119               to methods using the -callback option if the argument is
120               absent.  The undefined value may be passed to the -callback
121               argument to delete the callback.
122
123               NOTE: The subroutine being passed with the -callback named
124               argument should not cause blocking itself.  This will cause all
125               the actions in the event loop to be stopped, defeating the non-
126               blocking property of the Net::SNMP module.
127
128           Delay
129               An optional argument -delay can also be passed to non-blocking
130               objects.  The -delay argument instructs the object to wait the
131               number of seconds passed to the argument before executing the
132               SNMP protocol exchange.  The delay period starts when the event
133               loop is entered.  The -delay parameter is applied to all
134               methods associated with the object once it is specified.  The
135               delay value must be set back to 0 seconds to disable the delay
136               parameter.
137
138       SNMPv3 Arguments
139           A SNMP context is a collection of management information accessible
140           by a SNMP entity.  An item of management information may exist in
141           more than one context and a SNMP entity potentially has access to
142           many contexts.  The combination of a contextEngineID and a
143           contextName unambiguously identifies a context within an
144           administrative domain.  In a SNMPv3 message, the contextEngineID
145           and contextName are included as part of the scopedPDU.  All methods
146           that generate a SNMP message optionally take a -contextengineid and
147           -contextname argument to configure these fields.
148
149           Context Engine ID
150               The -contextengineid argument expects a hexadecimal string
151               representing the desired contextEngineID.  The string must be
152               10 to 64 characters (5 to 32 octets) long and can be prefixed
153               with an optional "0x".  Once the -contextengineid is specified
154               it stays with the object until it is changed again or reset to
155               default by passing in the undefined value.  By default, the
156               contextEngineID is set to match the authoritativeEngineID of
157               the authoritative SNMP engine.
158
159           Context Name
160               The contextName is passed as a string which must be 0 to 32
161               octets in length using the -contextname argument.  The
162               contextName stays with the object until it is changed.  The
163               contextName defaults to an empty string which represents the
164               "default" context.
165
166   session() - create a new Net::SNMP object
167          ($session, $error) = Net::SNMP->session(
168                                  [-hostname      => $hostname,]
169                                  [-port          => $port,]
170                                  [-localaddr     => $localaddr,]
171                                  [-localport     => $localport,]
172                                  [-nonblocking   => $boolean,]
173                                  [-version       => $version,]
174                                  [-domain        => $domain,]
175                                  [-timeout       => $seconds,]
176                                  [-retries       => $count,]
177                                  [-maxmsgsize    => $octets,]
178                                  [-translate     => $translate,]
179                                  [-debug         => $bitmask,]
180                                  [-community     => $community,]   # v1/v2c
181                                  [-username      => $username,]    # v3
182                                  [-authkey       => $authkey,]     # v3
183                                  [-authpassword  => $authpasswd,]  # v3
184                                  [-authprotocol  => $authproto,]   # v3
185                                  [-privkey       => $privkey,]     # v3
186                                  [-privpassword  => $privpasswd,]  # v3
187                                  [-privprotocol  => $privproto,]   # v3
188                               );
189
190       This is the constructor for Net::SNMP objects.  In scalar context, a
191       reference to a new Net::SNMP object is returned if the creation of the
192       object is successful.  In list context, a reference to a new Net::SNMP
193       object and an empty error message string is returned.  If a failure
194       occurs, the object reference is returned as the undefined value.  The
195       error string may be used to determine the cause of the error.
196
197       Most of the named arguments passed to the constructor define basic
198       attributes for the object and are not modifiable after the object has
199       been created.  The -timeout, -retries, -maxmsgsize, -translate, and
200       -debug arguments are modifiable using an accessor method.  See their
201       corresponding method definitions for a complete description of their
202       usage, default values, and valid ranges.
203
204       Transport Domain Arguments
205           The Net::SNMP module uses UDP/IPv4 as the default Transport Domain
206           to exchange SNMP messages between the local and remote devices.
207           The module also supports UDP/IPv6, TCP/IPv4, and TCP/IPv6 as
208           alternative Transport Domains.  The -domain argument can be used to
209           change the Transport Domain by setting the value to one of the
210           following strings: 'udp6', 'udp/ipv6'; 'tcp', 'tcp4', 'tcp/ipv4';
211           'tcp6', or 'tcp/ipv6'.  The -domain argument also accepts the
212           strings 'udp', 'udp4', or 'udp/ipv4' which correspond to the
213           default Transport Domain of UDP/IPv4.
214
215           The transport address of the destination SNMP device can be
216           specified using the -hostname argument.  This argument is optional
217           and defaults to "localhost".  The destination port number can be
218           specified as part of the transport address or by using the -port
219           argument.  Either a numeric port number or a textual service name
220           can be specified.  A numeric port number in parentheses can
221           optionally follow the service name.  This port number will be used
222           if the service name cannot be resolved.  If the destination port
223           number is not specified, the well-known SNMP port number 161 is
224           used.
225
226           By default the source transport address and port number are
227           assigned dynamically by the local device on which the Net::SNMP
228           module is being used.  This dynamic assignment can be overridden by
229           using the -localaddr and -localport arguments.  These arguments
230           accept the same values as the -hostname and -port arguments
231           respectively.  The resolved address must correspond to a valid
232           address of an interface on the local device.
233
234           When using an IPv4 Transport Domain, the transport address can be
235           specified as either an IP network hostname or an IPv4 address in
236           standard dotted notation.  The port information can be optionally
237           appended to the hostname or address delimited by a colon.  The
238           accepted IPv4 transport address formats are "address",
239           "address:port", "hostname", and "hostname:port".
240
241           When using an IPv6 Transport Domain, the transport address can be
242           specified as an IP hostname (which will be looked up as a DNS quad-
243           A record) or an IPv6 address in presentation format.  The port
244           information can optionally be included following a colon after the
245           hostname or address.  When including this information after an IPv6
246           address, the address must be enclosed in square brackets.  The
247           scope zone index (described in RFC 4007) can be specified after the
248           address as a decimal value delimited by a percent sign.  The
249           accepted transport address formats for IPv6 are "address",
250           "address%zone", "[address]:port", "[address%zone]:port",
251           "hostname", and "hostname:port".
252
253       Security Model Arguments
254           The -version argument controls which other arguments are expected
255           or required by the "session()" constructor.  The Net::SNMP module
256           supports SNMPv1, SNMPv2c, and SNMPv3.  The module defaults to
257           SNMPv1 if no -version argument is specified.  The -version argument
258           expects either a digit (i.e.  '1', '2', or '3') or a string
259           specifying the version (i.e. 'snmpv1', 'snmpv2c', or 'snmpv3') to
260           define the SNMP version.
261
262           The Security Model used by the Net::SNMP object is based on the
263           SNMP version associated with the object.  If the SNMP version is
264           SNMPv1 or SNMPv2c a Community-based Security Model will be used,
265           while the User-based Security Model (USM) will be used if the
266           version is SNMPv3.
267
268           Community-based Security Model Argument
269               If the Security Model is Community-based, the only argument
270               available is the -community argument.  This argument expects a
271               string that is to be used as the SNMP community name.  By
272               default the community name is set to 'public' if the argument
273               is not present.
274
275           User-based Security Model Arguments
276               The User-based Security Model (USM) used by SNMPv3 requires
277               that a securityName be specified using the -username argument.
278               The creation of a Net::SNMP object with the version set to
279               SNMPv3 will fail if the -username argument is not present.  The
280               -username argument expects a string 1 to 32 octets in length.
281
282               Different levels of security are allowed by the User-based
283               Security Model which address authentication and privacy
284               concerns.  A SNMPv3 Net::SNMP object will derive the security
285               level (securityLevel) based on which of the following arguments
286               are specified.
287
288               By default a securityLevel of 'noAuthNoPriv' is assumed.  If
289               the -authkey or -authpassword arguments are specified, the
290               securityLevel becomes 'authNoPriv'.  The -authpassword argument
291               expects a string which is at least 1 octet in length.
292               Optionally, the -authkey argument can be used so that a plain
293               text password does not have to be specified in a script.  The
294               -authkey argument expects a hexadecimal string produced by
295               localizing the password with the authoritativeEngineID for the
296               specific destination device.  The "snmpkey" utility included
297               with the distribution can be used to create the hexadecimal
298               string (see snmpkey).
299
300               Two different hash algorithms are defined by SNMPv3 which can
301               be used by the Security Model for authentication.  These
302               algorithms are HMAC-MD5-96 "MD5" (RFC 1321) and HMAC-SHA-96
303               "SHA-1" (NIST FIPS PUB 180-1).   The default algorithm used by
304               the module is HMAC-MD5-96.  This behavior can be changed by
305               using the -authprotocol argument.  This argument expects either
306               the string 'md5' or 'sha' to be passed to modify the hash
307               algorithm.
308
309               By specifying the arguments -privkey or -privpassword the
310               securityLevel associated with the object becomes 'authPriv'.
311               According to SNMPv3, privacy requires the use of
312               authentication.  Therefore, if either of these two arguments
313               are present and the -authkey or -authpassword arguments are
314               missing, the creation of the object fails.  The -privkey and
315               -privpassword arguments expect the same input as the -authkey
316               and -authpassword arguments respectively.
317
318               The User-based Security Model described in RFC 3414 defines a
319               single encryption protocol to be used for privacy.  This
320               protocol, CBC-DES "DES" (NIST FIPS PUB 46-1), is used by
321               default or if the string 'des' is passed to the -privprotocol
322               argument.  The module also supports RFC 3826 which describes
323               the use of CFB128-AES-128 "AES" (NIST FIPS PUB 197) in the USM.
324               The AES encryption protocol can be selected by passing 'aes' or
325               'aes128' to the -privprotocol argument.  By working with the
326               Extended Security Options Consortium
327               <http://www.snmp.com/protocol/eso.shtml>, the module also
328               supports CBC-3DES-EDE "Triple-DES" (NIST FIPS 46-3) in the
329               User-based Security Model.  This is defined in the draft
330               <http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt>.
331               The Triple-DES encryption protocol can be selected using the
332               -privprotocol argument with the string '3des' or '3desede'.
333
334   close() - clear the Transport Domain associated with the object
335          $session->close();
336
337       This method clears the Transport Domain and any errors associated with
338       the object.  Once closed, the Net::SNMP object can no longer be used to
339       send or receive SNMP messages.
340
341   snmp_dispatcher() - enter the non-blocking object event loop
342          $session->snmp_dispatcher();
343
344       This method enters the event loop associated with non-blocking
345       Net::SNMP objects.  The method exits when all queued SNMP messages have
346       received a response or have timed out at the Transport Layer. This
347       method is also exported as the stand alone function "snmp_dispatcher()"
348       by default (see "EXPORTS").
349
350   get_request() - send a SNMP get-request to the remote agent
351          $result = $session->get_request(
352                                 [-callback        => sub {},]     # non-blocking
353                                 [-delay           => $seconds,]   # non-blocking
354                                 [-contextengineid => $engine_id,] # v3
355                                 [-contextname     => $name,]      # v3
356                                 -varbindlist      => \@oids,
357                              );
358
359       This method performs a SNMP get-request query to gather data from the
360       remote agent on the host associated with the Net::SNMP object.  The
361       message is built using the list of OBJECT IDENTIFIERs in dotted
362       notation passed to the method as an array reference using the
363       -varbindlist argument.  Each OBJECT IDENTIFIER is placed into a single
364       SNMP GetRequest-PDU in the same order that it held in the original
365       list.
366
367       A reference to a hash is returned in blocking mode which contains the
368       contents of the VarBindList.  In non-blocking mode, a true value is
369       returned when no error has occurred.  In either mode, the undefined
370       value is returned when an error has occurred.  The "error()" method may
371       be used to determine the cause of the failure.
372
373   get_next_request() - send a SNMP get-next-request to the remote agent
374          $result = $session->get_next_request(
375                                 [-callback        => sub {},]     # non-blocking
376                                 [-delay           => $seconds,]   # non-blocking
377                                 [-contextengineid => $engine_id,] # v3
378                                 [-contextname     => $name,]      # v3
379                                 -varbindlist      => \@oids,
380                              );
381
382       This method performs a SNMP get-next-request query to gather data from
383       the remote agent on the host associated with the Net::SNMP object.  The
384       message is built using the list of OBJECT IDENTIFIERs in dotted
385       notation passed to the method as an array reference using the
386       -varbindlist argument.  Each OBJECT IDENTIFER is placed into a single
387       SNMP GetNextRequest-PDU in the same order that it held in the original
388       list.
389
390       A reference to a hash is returned in blocking mode which contains the
391       contents of the VarBindList.  In non-blocking mode, a true value is
392       returned when no error has occurred.  In either mode, the undefined
393       value is returned when an error has occurred.  The "error()" method may
394       be used to determine the cause of the failure.
395
396   set_request() - send a SNMP set-request to the remote agent
397          $result = $session->set_request(
398                                 [-callback        => sub {},]     # non-blocking
399                                 [-delay           => $seconds,]   # non-blocking
400                                 [-contextengineid => $engine_id,] # v3
401                                 [-contextname     => $name,]      # v3
402                                 -varbindlist      => \@oid_value,
403                              );
404
405       This method is used to modify data on the remote agent that is
406       associated with the Net::SNMP object using a SNMP set-request.  The
407       message is built using a list of values consisting of groups of an
408       OBJECT IDENTIFIER, an object type, and the actual value to be set.
409       This list is passed to the method as an array reference using the
410       -varbindlist argument.  The OBJECT IDENTIFIERs in each trio are to be
411       in dotted notation.  The object type is an octet corresponding to the
412       ASN.1 type of value that is to be set.  Each of the supported ASN.1
413       types have been defined and are exported by the package by default (see
414       "EXPORTS").
415
416       A reference to a hash is returned in blocking mode which contains the
417       contents of the VarBindList.  In non-blocking mode, a true value is
418       returned when no error has occurred.  In either mode, the undefined
419       value is returned when an error has occurred.  The "error()" method may
420       be used to determine the cause of the failure.
421
422   trap() - send a SNMP trap to the remote manager
423          $result = $session->trap(
424                                 [-delay           => $seconds,]   # non-blocking
425                                 [-enterprise      => $oid,]
426                                 [-agentaddr       => $ipaddress,]
427                                 [-generictrap     => $generic,]
428                                 [-specifictrap    => $specific,]
429                                 [-timestamp       => $timeticks,]
430                                 -varbindlist      => \@oid_value,
431                              );
432
433       This method sends a SNMP trap to the remote manager associated with the
434       Net::SNMP object.  All arguments are optional and will be given the
435       following defaults in the absence of a corresponding named argument:
436
437       ·   The default value for the trap -enterprise is "1.3.6.1.4.1", which
438           corresponds to "iso.org.dod.internet.private.enterprises".  The
439           enterprise value is expected to be an OBJECT IDENTIFER in dotted
440           notation.
441
442       ·   When the Transport Domain is UDP/IPv4 or TCP/IPv4, the default
443           value for the trap -agentaddr is the IP address associated with the
444           interface on which the trap will be transmitted.  For other
445           Transport Domains the -agentaddr is defaulted to "0.0.0.0".  When
446           specified, the agent-addr is expected to be an IpAddress in dotted
447           notation.
448
449       ·   The default value for the -generictrap type is 6 which corresponds
450           to "enterpriseSpecific".  The generic-trap types are defined and
451           can be exported upon request (see "EXPORTS").
452
453       ·   The default value for the -specifictrap type is 0.  No pre-defined
454           values are available for specific-trap types.
455
456       ·   The default value for the trap -timestamp is the "uptime" of the
457           script.  The "uptime" of the script is the number of hundredths of
458           seconds that have elapsed since the script began running.  The
459           time-stamp is expected to be a TimeTicks number in hundredths of
460           seconds.
461
462       ·   The default value for the trap -varbindlist is an empty array
463           reference.  The variable-bindings are expected to be in an array
464           format consisting of groups of an OBJECT IDENTIFIER, an object
465           type, and the actual value of the object.  This is identical to the
466           list expected by the "set_request()" method.  The OBJECT
467           IDENTIFIERs in each trio are to be in dotted notation.  The object
468           type is an octet corresponding to the ASN.1 type for the value.
469           Each of the supported types have been defined and are exported by
470           default (see "EXPORTS").
471
472       A true value is returned when the method is successful. The undefined
473       value is returned when a failure has occurred.  The "error()" method
474       can be used to determine the cause of the failure. Since there are no
475       acknowledgements for Trap-PDUs, there is no way to determine if the
476       remote host actually received the trap.
477
478       NOTE: When the object is in non-blocking mode, the trap is not sent
479       until the event loop is entered and no callback is ever executed.
480
481       NOTE: This method can only be used when the version of the object is
482       set to SNMPv1.
483
484   get_bulk_request() - send a SNMP get-bulk-request to the remote agent
485          $result = $session->get_bulk_request(
486                                 [-callback        => sub {},]     # non-blocking
487                                 [-delay           => $seconds,]   # non-blocking
488                                 [-contextengineid => $engine_id,] # v3
489                                 [-contextname     => $name,]      # v3
490                                 [-nonrepeaters    => $non_reps,]
491                                 [-maxrepetitions  => $max_reps,]
492                                 -varbindlist      => \@oids,
493                              );
494
495       This method performs a SNMP get-bulk-request query to gather data from
496       the remote agent on the host associated with the Net::SNMP object.  All
497       arguments are optional except -varbindlist and will be given the
498       following defaults in the absence of a corresponding named argument:
499
500       ·   The default value for the get-bulk-request -nonrepeaters is 0.  The
501           non-repeaters value specifies the number of variables in the
502           variable-bindings list for which a single successor is to be
503           returned.
504
505       ·   The default value for the get-bulk-request -maxrepetitions is 0.
506           The max-repetitions value specifies the number of successors to be
507           returned for the remaining variables in the variable-bindings list.
508
509       ·   The -varbindlist argument expects an array reference consisting of
510           a list of OBJECT IDENTIFIERs in dotted notation.  Each OBJECT
511           IDENTIFER is placed into a single SNMP GetBulkRequest-PDU in the
512           same order that it held in the original list.
513
514       A reference to a hash is returned in blocking mode which contains the
515       contents of the VarBindList.  In non-blocking mode, a true value is
516       returned when no error has occurred.  In either mode, the undefined
517       value is returned when an error has occurred.  The "error()" method may
518       be used to determine the cause of the failure.
519
520       NOTE: This method can only be used when the version of the object is
521       set to SNMPv2c or SNMPv3.
522
523   inform_request() - send a SNMP inform-request to the remote manager
524          $result = $session->inform_request(
525                                 [-callback        => sub {},]     # non-blocking
526                                 [-delay           => $seconds,]   # non-blocking
527                                 [-contextengineid => $engine_id,] # v3
528                                 [-contextname     => $name,]      # v3
529                                 -varbindlist      => \@oid_value,
530                              );
531
532       This method is used to provide management information to the remote
533       manager associated with the Net::SNMP object using an inform-request.
534       The message is built using a list of values consisting of groups of an
535       OBJECT IDENTIFIER, an object type, and the actual value to be
536       identified.  This list is passed to the method as an array reference
537       using the -varbindlist argument.  The OBJECT IDENTIFIERs in each trio
538       are to be in dotted notation.  The object type is an octet
539       corresponding to the ASN.1 type of value that is to be identified.
540       Each of the supported ASN.1 types have been defined and are exported by
541       the package by default (see "EXPORTS").
542
543       The first two variable-bindings fields in the inform-request are
544       specified by SNMPv2 and should be:
545
546       ·   sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
547
548       ·   snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
549
550       A reference to a hash is returned in blocking mode which contains the
551       contents of the VarBindList.  In non-blocking mode, a true value is
552       returned when no error has occurred.  In either mode, the undefined
553       value is returned when an error has occurred.  The "error()" method may
554       be used to determine the cause of the failure.
555
556       NOTE: This method can only be used when the version of the object is
557       set to SNMPv2c or SNMPv3.
558
559   snmpv2_trap() - send a SNMP snmpV2-trap to the remote manager
560          $result = $session->snmpv2_trap(
561                                 [-delay           => $seconds,]   # non-blocking
562                                 -varbindlist      => \@oid_value,
563                              );
564
565       This method sends a snmpV2-trap to the remote manager associated with
566       the Net::SNMP object.  The message is built using a list of values
567       consisting of groups of an OBJECT IDENTIFIER, an object type, and the
568       actual value to be identified.  This list is passed to the method as an
569       array reference using the -varbindlist argument.  The OBJECT
570       IDENTIFIERs in each trio are to be in dotted notation.  The object type
571       is an octet corresponding to the ASN.1 type of value that is to be
572       identified.  Each of the supported ASN.1 types have been defined and
573       are exported by the package by default (see "EXPORTS").
574
575       The first two variable-bindings fields in the snmpV2-trap are specified
576       by SNMPv2 and should be:
577
578       ·   sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
579
580       ·   snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
581
582       A true value is returned when the method is successful. The undefined
583       value is returned when a failure has occurred.  The "error()" method
584       can be used to determine the cause of the failure. Since there are no
585       acknowledgements for SNMPv2-Trap-PDUs, there is no way to determine if
586       the remote host actually received the snmpV2-trap.
587
588       NOTE: When the object is in non-blocking mode, the snmpV2-trap is not
589       sent until the event loop is entered and no callback is ever executed.
590
591       NOTE: This method can only be used when the version of the object is
592       set to SNMPv2c.  SNMPv2-Trap-PDUs are supported by SNMPv3, but require
593       the sender of the message to be an authoritative SNMP engine which is
594       not currently supported by the Net::SNMP module.
595
596   get_table() - retrieve a table from the remote agent
597          $result = $session->get_table(
598                                 [-callback        => sub {},]     # non-blocking
599                                 [-delay           => $seconds,]   # non-blocking
600                                 [-contextengineid => $engine_id,] # v3
601                                 [-contextname     => $name,]      # v3
602                                 -baseoid          => $oid,
603                                 [-maxrepetitions  => $max_reps,]  # v2c/v3
604                              );
605
606       This method performs repeated SNMP get-next-request or get-bulk-request
607       (when using SNMPv2c or SNMPv3) queries to gather data from the remote
608       agent on the host associated with the Net::SNMP object.  The first
609       message sent is built using the OBJECT IDENTIFIER in dotted notation
610       passed to the method by the -baseoid argument.   Repeated SNMP requests
611       are issued until the OBJECT IDENTIFIER in the response is no longer a
612       child of the base OBJECT IDENTIFIER.
613
614       The -maxrepetitions argument can be used to specify the max-repetitions
615       value that is passed to the get-bulk-requests when using SNMPv2c or
616       SNMPv3.  If this argument is not present, a value is calculated based
617       on the maximum message size for the Net::SNMP object.  If the value is
618       set to 1 or less, get-next-requests will be used for the queries
619       instead of get-bulk-requests.
620
621       A reference to a hash is returned in blocking mode which contains the
622       contents of the VarBindList.  In non-blocking mode, a true value is
623       returned when no error has occurred.  In either mode, the undefined
624       value is returned when an error has occurred.  The "error()" method may
625       be used to determine the cause of the failure.
626
627       WARNING: Results from this method can become very large if the base
628       OBJECT IDENTIFIER is close to the root of the SNMP MIB tree.
629
630   get_entries() - retrieve table entries from the remote agent
631          $result = $session->get_entries(
632                                 [-callback        => sub {},]     # non-blocking
633                                 [-delay           => $seconds,]   # non-blocking
634                                 [-contextengineid => $engine_id,] # v3
635                                 [-contextname     => $name,]      # v3
636                                 -columns          => \@columns,
637                                 [-startindex      => $start,]
638                                 [-endindex        => $end,]
639                                 [-maxrepetitions  => $max_reps,]  # v2c/v3
640                              );
641
642       This method performs repeated SNMP get-next-request or get-bulk-request
643       (when using SNMPv2c or SNMPv3) queries to gather data from the remote
644       agent on the host associated with the Net::SNMP object.  Each message
645       specifically requests data for each OBJECT IDENTIFIER specified in the
646       -columns array.  The OBJECT IDENTIFIERs must correspond to column
647       entries for a conceptual row in a table.  They may however be columns
648       in different tables as long as each table is indexed the same way.  The
649       optional -startindex and -endindex arguments may be specified to limit
650       the query to specific rows in the table(s).
651
652       The -startindex can be specified as a single decimal value or in dotted
653       notation if the index associated with the entry so requires.  If the
654       -startindex is specified, it will be include as part of the query
655       results.  If no -startindex is specified, the first request message
656       will be sent without an index.  To insure that the -startindex is
657       included, the last sub-identifier in the index is decremented by one.
658       If the last sub-identifier has a value of zero, the sub-identifier is
659       removed from the index.
660
661       The optional -endindex argument can be specified as a single decimal
662       value or in dotted notation.  If the -endindex is specified, it will be
663       included as part of the query results.  If no -endindex is specified,
664       repeated SNMP requests are issued until the response no longer returns
665       entries matching any of the columns specified in the -columns array.
666
667       The -maxrepetitions argument can be used to specify the max-repetitions
668       value that is passed to the get-bulk-requests when using SNMPv2c or
669       SNMPv3.  If this argument is not present, a value is calculated based
670       on the maximum message size of the object and the number of columns
671       specified in the -columns array.  If the value is set to 1 or less,
672       get-next-requests will be used for the queries instead of get-bulk-
673       requests.
674
675       A reference to a hash is returned in blocking mode which contains the
676       contents of the VarBindList.  In non-blocking mode, a true value is
677       returned when no error has occurred.  In either mode, the undefined
678       value is returned when an error has occurred.  The "error()" method may
679       be used to determine the cause of the failure.
680
681   version() - get the SNMP version from the object
682          $rfc_version = $session->version();
683
684       This method returns the current value for the SNMP version associated
685       with the object.  The returned value is the corresponding version
686       number defined by the RFCs for the protocol version field (i.e. SNMPv1
687       == 0, SNMPv2c == 1, and SNMPv3 == 3).  The RFC versions are defined as
688       constant by the module and can be exported by request (see "EXPORTS").
689
690   error() - get the current error message from the object
691          $error_message = $session->error();
692
693       This method returns a text string explaining the reason for the last
694       error.  An empty string is returned if no error has occurred.
695
696   hostname() - get the hostname associated with the object
697          $hostname = $session->hostname();
698
699       This method returns the parsed hostname string that is associated with
700       the object.  Any port information and formatting that can be included
701       with the corresponding "session()" constructor argument will be
702       stripped and not included as part of the returned string.
703
704   error_status() - get the current SNMP error-status from the object
705          $error_status = $session->error_status();
706
707       This method returns the numeric value of the error-status contained in
708       the last SNMP message received by the object.
709
710   error_index() - get the current SNMP error-index from the object
711          $error_index = $session->error_index();
712
713       This method returns the numeric value of the error-index contained in
714       the last SNMP message received by the object.
715
716   var_bind_list() - get the hash reference for the VarBindList values
717          $values = $session->var_bind_list();
718
719       This method returns a hash reference created using the ObjectName and
720       the ObjectSyntax pairs in the VarBindList of the last SNMP message
721       received by the object.  The keys of the hash consist of the OBJECT
722       IDENTIFIERs in dotted notation corresponding to each ObjectName in the
723       VarBindList.  If any of the OBJECT IDENTIFIERs passed to the request
724       method began with a leading dot, all of the OBJECT IDENTIFIER hash keys
725       will be prefixed with a leading dot.  If duplicate OBJECT IDENTIFIERs
726       are present in the VarBindList they will be padded with spaces to make
727       them an unique hash key.  The value of each hash entry is set equal to
728       the value of the corresponding ObjectSyntax.  The undefined value is
729       returned if there has been a failure.
730
731   var_bind_names() - get the array of the ObjectNames in the VarBindList
732          @names = $session->var_bind_names();
733
734       This method returns an array containing the OBJECT IDENTIFIERs
735       corresponding to the ObjectNames in the VarBindList in the order that
736       they were received in the last SNMP message.  The entries in the array
737       will map directly to the keys in the hash reference returned by the
738       methods that perform SNMP message exchanges and by the
739       "var_bind_list()" and "var_bind_types()" methods.  The array returned
740       for the convenience methods "get_table()" and "get_entries()" will be
741       in lexicographical order.  An empty array is returned if there has been
742       a failure.
743
744   var_bind_types() - get the hash reference for the VarBindList ASN.1 types
745          $types = $session->var_bind_types();
746
747       This method returns a hash reference created using the ObjectName and
748       the ASN.1 type of the ObjectSyntax in the VarBindList of the last SNMP
749       message received by the object.  The keys of the hash consist of the
750       OBJECT IDENTIFIERs in dotted notation corresponding to each ObjectName
751       in the VarBindList.  The value of each hash entry is set equal to the
752       ASN.1 type of the corresponding ObjectSyntax.  Constants for the
753       supported ASN.1 types have been defined and are exported by the package
754       by default (see "EXPORTS").  The undefined value is returned if there
755       has been a failure.
756
757   timeout() - set or get the current timeout period for the object
758          $seconds = $session->timeout([$seconds]);
759
760       This method returns the current value for the Transport Layer timeout
761       for the Net::SNMP object.  This value is the number of seconds that the
762       object will wait for a response from the agent on the remote host.  The
763       default timeout is 5.0 seconds.
764
765       If a parameter is specified, the timeout for the object is set to the
766       provided value if it falls within the range 1.0 to 60.0 seconds.  The
767       undefined value is returned upon an error and the "error()" method may
768       be used to determine the cause.
769
770   retries() - set or get the current retry count for the object
771          $count = $session->retries([$count]);
772
773       This method returns the current value for the number of times to retry
774       sending a SNMP message to the remote host.  The default number of
775       retries is 1.
776
777       If a parameter is specified, the number of retries for the object is
778       set to the provided value if it falls within the range 0 to 20. The
779       undefined value is returned upon an error and the "error()" method may
780       be used to determine the cause.
781
782   max_msg_size() - set or get the current maxMsgSize for the object
783          $octets = $session->max_msg_size([$octets]);
784
785       This method returns the current value for the maximum message size
786       (maxMsgSize) for the Net::SNMP object.  This value is the largest
787       message size in octets that can be prepared or processed by the object.
788       The default maxMsgSize is 1472 octets for UDP/IPv4, 1452 octets for
789       UDP/IPv6, 1460 octets for TCP/IPv4, and 1440 octets for TCP/IPv6.
790
791       If a parameter is specified, the maxMsgSize is set to the provided
792       value if it falls within the range 484 to 65535 octets.  The undefined
793       value is returned upon an error and the "error()" method may be used to
794       determine the cause.
795
796       NOTE: When using SNMPv3, the maxMsgSize is actually contained in the
797       SNMP message (as msgMaxSize).  If the value received from a remote
798       device is less than the current maxMsgSize, the size is automatically
799       adjusted to be the lower value.
800
801   translate() - enable or disable the translation mode for the object
802          $mask = $session->translate([
803                               $mode |
804                               [ # Perl anonymous ARRAY reference
805                                  ['-all'            => $mode0,]
806                                  ['-octetstring'    => $mode1,]
807                                  ['-null'           => $mode2,]
808                                  ['-timeticks'      => $mode3,]
809                                  ['-opaque'         => $mode4,]
810                                  ['-nosuchobject'   => $mode5,]
811                                  ['-nosuchinstance' => $mode6,]
812                                  ['-endofmibview'   => $mode7,]
813                                  ['-unsigned'       => $mode8]
814                               ]
815                            ]);
816
817       When the object decodes the GetResponse-PDU that is returned in
818       response to a SNMP message, certain values are translated into a more
819       "human readable" form.  By default the following translations occur:
820
821       ·   OCTET STRINGs and Opaques containing any octet which is not part of
822           the character set defined as a DisplayString in RFC 2679 are
823           converted into a hexadecimal representation prefixed with "0x".
824           The control codes NUL(0x00), BEL(0x07), BS(0x08), HT(0x09),
825           LF(0x0A), VT(0x0b), FF(0x0C), and CR(0x0D) are part of the
826           character set and will not trigger translation.  The sequence 'CR
827           x' for any x other than LF or NUL is illegal and will trigger
828           translation.
829
830       ·   TimeTicks integer values are converted to a time format.
831
832       ·   NULL values return the string "NULL" instead of an empty string.
833
834       ·   noSuchObject exception values return the string "noSuchObject"
835           instead of an empty string.
836
837       ·   noSuchInstance exception values return the string "noSuchInstance"
838           instead of an empty string.
839
840       ·   endOfMibView exception values return the string "endOfMibView"
841           instead of an empty string.
842
843       ·   Counter64, Counter, Gauge, and TimeTick values that have been
844           incorrectly encoded as signed negative values are returned as
845           unsigned values.
846
847       The "translate()" method can be invoked with two different types of
848       arguments.
849
850       If the argument passed is any Perl variable type except an array
851       reference, the translation mode for all ASN.1 types is set to either
852       enabled or disabled, depending on the value of the passed parameter.
853       Any value that Perl would treat as a true value will set the mode to be
854       enabled for all types, while a false value will disable translation for
855       all types.
856
857       A reference to an array can be passed to the "translate()" method in
858       order to define the translation mode on a per ASN.1 type basis.  The
859       array is expected to contain a list of named argument pairs for each
860       ASN.1 type that is to be modified.  The arguments in the list are
861       applied in the order that they are passed in via the array.  Arguments
862       at the end of the list supercede those passed earlier in the list.  The
863       argument "-all" can be used to specify that the mode is to apply to all
864       ASN.1 types.  Only the arguments for the ASN.1 types that are to be
865       modified need to be included in the list.
866
867       The "translate()" method returns a bit mask indicating which ASN.1
868       types are to be translated.  Definitions of the bit to ASN.1 type
869       mappings can be exported using the :translate tag (see "EXPORTS").  The
870       undefined value is returned upon an error and the "error()" method may
871       be used to determine the cause.
872
873   debug() - set or get the debug mode for the module
874          $mask = $session->debug([$mask]);
875
876       This method is used to enable or disable debugging for the Net::SNMP
877       module.  Debugging can be enabled on a per component level as defined
878       by a bit mask passed to the "debug()" method.  The bit mask is broken
879       up as follows:
880
881       ·   0x02 - Message or PDU encoding and decoding
882
883       ·   0x04 - Transport Layer
884
885       ·   0x08 - Dispatcher
886
887       ·   0x10 - Message Processing
888
889       ·   0x20 - Security
890
891       Symbols representing these bit mask values are defined by the module
892       and can be exported using the :debug tag (see "EXPORTS").  If a non-
893       numeric value is passed to the "debug()" method, it is evaluated in
894       boolean context.  Debugging for all of the components is then enabled
895       or disabled based on the resulting truth value.
896
897       The current debugging mask is returned by the method.  Debugging can
898       also be enabled using the stand alone function "snmp_debug()". This
899       function can be exported by request (see "EXPORTS").
900

SUBROUTINES

902   oid_base_match() - determine if an OID has a specified OID base
903          $value = oid_base_match($base_oid, $oid);
904
905       This function takes two OBJECT IDENTIFIERs in dotted notation and
906       returns a true value (i.e. 0x1) if the second OBJECT IDENTIFIER is
907       equal to or is a child of the first OBJECT IDENTIFIER in the SNMP
908       Management Information Base (MIB).  This function can be used in
909       conjunction with the "get-next-request()" or "get-bulk-request()"
910       methods to determine when a OBJECT IDENTIFIER in the GetResponse-PDU is
911       no longer in the desired MIB tree branch.
912
913   oid_lex_cmp() - compare two OBJECT IDENTIFIERs lexicographically
914          $cmp = oid_lex_cmp($oid1, $oid2);
915
916       This function takes two OBJECT IDENTIFIERs in dotted notation and
917       returns one of the values 1, 0, -1 if $oid1 is respectively
918       lexicographically greater, equal, or less than $oid2.
919
920   oid_lex_sort() - sort a list of OBJECT IDENTIFIERs lexicographically
921          @sorted_oids = oid_lex_sort(@oids);
922
923       This function takes a list of OBJECT IDENTIFIERs in dotted notation and
924       returns the listed sorted in lexicographical order.
925
926   snmp_type_ntop() - convert an ASN.1 type to presentation format
927          $text = snmp_type_ntop($type);
928
929       This function takes an ASN.1 type octet and returns a text string
930       suitable for presentation.  Some ASN.1 type definitions map to the same
931       octet value when encoded.  This method cannot distinguish between these
932       multiple mappings and the most basic type name will be returned.
933
934   ticks_to_time() - convert TimeTicks to formatted time
935          $time = ticks_to_time($timeticks);
936
937       This function takes an ASN.1 TimeTicks value and returns a string
938       representing the time defined by the value.  The TimeTicks value is
939       expected to be a non-negative integer value representing the time in
940       hundredths of a second since some epoch.  The returned string will
941       display the time in days, hours, and seconds format according to the
942       value of the TimeTicks argument.
943

EXPORTS

945       The Net::SNMP module uses the Exporter module to export useful
946       constants and subroutines.  These exportable symbols are defined below
947       and follow the rules and conventions of the Exporter module (see
948       Exporter).
949
950       Default
951           &snmp_dispatcher, INTEGER, INTEGER32, OCTET_STRING,
952           OBJECT_IDENTIFIER, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32,
953           UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT,
954           NOSUCHINSTANCE, ENDOFMIBVIEW
955
956       Exportable
957           &snmp_debug, &snmp_dispatcher, &snmp_type_ntop, &oid_base_match,
958           &oid_lex_cmp, &oid_lex_sort,&ticks_to_time, INTEGER, INTEGER32,
959           OCTET_STRING, NULL, OBJECT_IDENTIFIER, SEQUENCE, IPADDRESS,
960           COUNTER, COUNTER32, GAUGE, GAUGE32, UNSIGNED32, TIMETICKS, OPAQUE,
961           COUNTER64, NOSUCHOBJECT, NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST,
962           GET_NEXT_REQUEST, GET_RESPONSE, SET_REQUEST, TRAP,
963           GET_BULK_REQUEST, INFORM_REQUEST, SNMPV2_TRAP, REPORT, DEBUG_ALL,
964           DEBUG_NONE, DEBUG_MESSAGE, DEBUG_TRANSPORT,
965           DEBUG_DISPATCHER,DEBUG_PROCESSING, DEBUG_SECURITY, COLD_START,
966           WARM_START, LINK_DOWN, LINK_UP, AUTHENTICATION_FAILURE,
967           EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC, SNMP_VERSION_1,
968           SNMP_VERSION_2C, SNMP_VERSION_3, SNMP_PORT, SNMP_TRAP_PORT,
969           TRANSLATE_NONE,TRANSLATE_OCTET_STRING, TRANSLATE_NULL,
970           TRANSLATE_TIMETICKS, TRANSLATE_OPAQUE,TRANSLATE_NOSUCHOBJECT,
971           TRANSLATE_NOSUCHINSTANCE, TRANSLATE_ENDOFMIBVIEW,
972           TRANSLATE_UNSIGNED, TRANSLATE_ALL
973
974       Tags
975           :asn1
976               INTEGER, INTEGER32, OCTET_STRING, NULL, OBJECT_IDENTIFIER,
977               SEQUENCE, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32,
978               UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT,
979               NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST, GET_NEXT_REQUEST,
980               GET_RESPONSE, SET_REQUEST, TRAP, GET_BULK_REQUEST,
981               INFORM_REQUEST, SNMPV2_TRAP, REPORT
982
983           :debug
984               &snmp_debug, DEBUG_ALL, DEBUG_NONE, DEBUG_MESSAGE,
985               DEBUG_TRANSPORT, DEBUG_DISPATCHER, DEBUG_PROCESSING,
986               DEBUG_SECURITY
987
988           :generictrap
989               COLD_START, WARM_START, LINK_DOWN, LINK_UP,
990               AUTHENTICATION_FAILURE, EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC
991
992           :snmp
993               &snmp_debug, &snmp_dispatcher, &snmp_type_ntop,
994               &oid_base_match, &oid_lex_cmp, &oid_lex_sort, &ticks_to_time,
995               SNMP_VERSION_1, SNMP_VERSION_2C, SNMP_VERSION_3, SNMP_PORT,
996               SNMP_TRAP_PORT
997
998           :translate
999               TRANSLATE_NONE, TRANSLATE_OCTET_STRING, TRANSLATE_NULL,
1000               TRANSLATE_TIMETICKS, TRANSLATE_OPAQUE, TRANSLATE_NOSUCHOBJECT,
1001               TRANSLATE_NOSUCHINSTANCE, TRANSLATE_ENDOFMIBVIEW,
1002               TRANSLATE_UNSIGNED, TRANSLATE_ALL
1003
1004           :ALL
1005               All of the above exportable items.
1006

EXAMPLES

1008   1. Blocking SNMPv1 get-request for sysUpTime
1009       This example gets the sysUpTime from a remote host.
1010
1011          #! /usr/local/bin/perl
1012
1013          use strict;
1014          use warnings;
1015
1016          use Net::SNMP;
1017
1018          my $OID_sysUpTime = '1.3.6.1.2.1.1.3.0';
1019
1020          my ($session, $error) = Net::SNMP->session(
1021             -hostname  => shift || 'localhost',
1022             -community => shift || 'public',
1023          );
1024
1025          if (!defined $session) {
1026             printf "ERROR: %s.\n", $error;
1027             exit 1;
1028          }
1029
1030          my $result = $session->get_request(-varbindlist => [ $OID_sysUpTime ],);
1031
1032          if (!defined $result) {
1033             printf "ERROR: %s.\n", $session->error();
1034             $session->close();
1035             exit 1;
1036          }
1037
1038          printf "The sysUpTime for host '%s' is %s.\n",
1039                 $session->hostname(), $result->{$OID_sysUpTime};
1040
1041          $session->close();
1042
1043          exit 0;
1044
1045   2. Blocking SNMPv3 set-request of sysContact
1046       This example sets the sysContact information on the remote host to
1047       "Help Desk x911".  The named arguments passed to the "session()"
1048       constructor are for the demonstration of syntax only.  These parameters
1049       will need to be set according to the SNMPv3 parameters of the remote
1050       host.  The "snmpkey" utility included with the distribution can be used
1051       to create the key values.
1052
1053          #! /usr/local/bin/perl
1054
1055          use strict;
1056          use warnings;
1057
1058          use Net::SNMP;
1059
1060          my $OID_sysContact = '1.3.6.1.2.1.1.4.0';
1061
1062          my ($session, $error) = Net::SNMP->session(
1063             -hostname     => 'myv3host.example.com',
1064             -version      => 'snmpv3',
1065             -username     => 'myv3Username',
1066             -authprotocol => 'sha1',
1067             -authkey      => '0x6695febc9288e36282235fc7151f128497b38f3f',
1068             -privprotocol => 'des',
1069             -privkey      => '0x6695febc9288e36282235fc7151f1284',
1070          );
1071
1072          if (!defined $session) {
1073             printf "ERROR: %s.\n", $error;
1074             exit 1;
1075          }
1076
1077          my $result = $session->set_request(
1078             -varbindlist => [ $OID_sysContact, OCTET_STRING, 'Help Desk x911' ],
1079          );
1080
1081          if (!defined $result) {
1082             printf "ERROR: %s.\n", $session->error();
1083             $session->close();
1084             exit 1;
1085          }
1086
1087          printf "The sysContact for host '%s' was set to '%s'.\n",
1088                 $session->hostname(), $result->{$OID_sysContact};
1089
1090          $session->close();
1091
1092          exit 0;
1093
1094   3. Non-blocking SNMPv2c get-bulk-request for ifTable
1095       This example gets the contents of the ifTable by sending get-bulk-
1096       requests until the responses are no longer part of the ifTable.  The
1097       ifTable can also be retrieved using the "get_table()" method.  The
1098       ifPhysAddress object in the table has a syntax of an OCTET STRING.  By
1099       default, translation is enabled and non-printable OCTET STRINGs are
1100       translated into a hexadecimal format.  Sometimes the OCTET STRING
1101       contains all printable characters and this produces unexpected output
1102       when it is not translated.  The example turns off translation for OCTET
1103       STRINGs and specifically formats the output for the ifPhysAddress
1104       objects.
1105
1106          #! /usr/local/bin/perl
1107
1108          use strict;
1109          use warnings;
1110
1111          use Net::SNMP qw(:snmp);
1112
1113          my $OID_ifTable = '1.3.6.1.2.1.2.2';
1114          my $OID_ifPhysAddress = '1.3.6.1.2.1.2.2.1.6';
1115
1116          my ($session, $error) = Net::SNMP->session(
1117             -hostname    => shift || 'localhost',
1118             -community   => shift || 'public',
1119             -nonblocking => 1,
1120             -translate   => [-octetstring => 0],
1121             -version     => 'snmpv2c',
1122          );
1123
1124          if (!defined $session) {
1125             printf "ERROR: %s.\n", $error;
1126             exit 1;
1127          }
1128
1129          my %table; # Hash to store the results
1130
1131          my $result = $session->get_bulk_request(
1132             -varbindlist    => [ $OID_ifTable ],
1133             -callback       => [ \&table_callback, \%table ],
1134             -maxrepetitions => 10,
1135          );
1136
1137          if (!defined $result) {
1138             printf "ERROR: %s\n", $session->error();
1139             $session->close();
1140             exit 1;
1141          }
1142
1143          # Now initiate the SNMP message exchange.
1144
1145          snmp_dispatcher();
1146
1147          $session->close();
1148
1149          # Print the results, specifically formatting ifPhysAddress.
1150
1151          for my $oid (oid_lex_sort(keys %table)) {
1152             if (!oid_base_match($OID_ifPhysAddress, $oid)) {
1153                printf "%s = %s\n", $oid, $table{$oid};
1154             } else {
1155                printf "%s = %s\n", $oid, unpack 'H*', $table{$oid};
1156             }
1157          }
1158
1159          exit 0;
1160
1161          sub table_callback
1162          {
1163             my ($session, $table) = @_;
1164
1165             my $list = $session->var_bind_list();
1166
1167             if (!defined $list) {
1168                printf "ERROR: %s\n", $session->error();
1169                return;
1170             }
1171
1172             # Loop through each of the OIDs in the response and assign
1173             # the key/value pairs to the reference that was passed with
1174             # the callback.  Make sure that we are still in the table
1175             # before assigning the key/values.
1176
1177             my @names = $session->var_bind_names();
1178             my $next  = undef;
1179
1180             while (@names) {
1181                $next = shift @names;
1182                if (!oid_base_match($OID_ifTable, $next)) {
1183                   return; # Table is done.
1184                }
1185                $table->{$next} = $list->{$next};
1186             }
1187
1188             # Table is not done, send another request, starting at the last
1189             # OBJECT IDENTIFIER in the response.  No need to include the
1190             # calback argument, the same callback that was specified for the
1191             # original request will be used.
1192
1193             my $result = $session->get_bulk_request(
1194                -varbindlist    => [ $next ],
1195                -maxrepetitions => 10,
1196             );
1197
1198             if (!defined $result) {
1199                printf "ERROR: %s.\n", $session->error();
1200             }
1201
1202             return;
1203          }
1204
1205   4. Non-blocking SNMPv1 get-request and set-request on multiple hosts
1206       This example first polls several hosts for their sysUpTime.  If the
1207       poll of the host is successful, the sysContact and sysLocation
1208       information is set on the host.  The sysContact information is
1209       hardcoded to "Help Desk x911" while the sysLocation information is
1210       passed as an argument to the callback.
1211
1212          #! /usr/local/bin/perl
1213
1214          use strict;
1215          use warnings;
1216
1217          use Net::SNMP;
1218
1219          my $OID_sysUpTime = '1.3.6.1.2.1.1.3.0';
1220          my $OID_sysContact = '1.3.6.1.2.1.1.4.0';
1221          my $OID_sysLocation = '1.3.6.1.2.1.1.6.0';
1222
1223          # Hash of hosts and location data.
1224
1225          my %host_data = (
1226             '10.1.1.2'  => 'Building 1, Second Floor',
1227             '10.2.1.1'  => 'Building 2, First Floor',
1228             'localhost' => 'Right here!',
1229          );
1230
1231          # Create a session for each host and queue a get-request for sysUpTime.
1232
1233          for my $host (keys %host_data) {
1234
1235             my ($session, $error) = Net::SNMP->session(
1236                -hostname    => $host,
1237                -community   => 'private',
1238                -nonblocking => 1,
1239             );
1240
1241             if (!defined $session) {
1242                printf "ERROR: Failed to create session for host '%s': %s.\n",
1243                       $host, $error;
1244                next;
1245             }
1246
1247             my $result = $session->get_request(
1248                -varbindlist => [ $OID_sysUpTime ],
1249                -callback    => [ \&get_callback, $host_data{$host} ],
1250             );
1251
1252             if (!defined $result) {
1253                printf "ERROR: Failed to queue get request for host '%s': %s.\n",
1254                       $session->hostname(), $session->error();
1255             }
1256
1257          }
1258
1259          # Now initiate the SNMP message exchange.
1260
1261          snmp_dispatcher();
1262
1263          exit 0;
1264
1265          sub get_callback
1266          {
1267             my ($session, $location) = @_;
1268
1269             my $result = $session->var_bind_list();
1270
1271             if (!defined $result) {
1272                printf "ERROR: Get request failed for host '%s': %s.\n",
1273                       $session->hostname(), $session->error();
1274                return;
1275             }
1276
1277             printf "The sysUpTime for host '%s' is %s.\n",
1278                     $session->hostname(), $result->{$OID_sysUpTime};
1279
1280             # Now set the sysContact and sysLocation for the host.
1281
1282             $result = $session->set_request(
1283                -varbindlist =>
1284                [
1285                   $OID_sysContact,  OCTET_STRING, 'Help Desk x911',
1286                   $OID_sysLocation, OCTET_STRING, $location,
1287                ],
1288                -callback    => \&set_callback,
1289             );
1290
1291             if (!defined $result) {
1292                printf "ERROR: Failed to queue set request for host '%s': %s.\n",
1293                       $session->hostname(), $session->error();
1294             }
1295
1296             return;
1297          }
1298
1299          sub set_callback
1300          {
1301             my ($session) = @_;
1302
1303             my $result = $session->var_bind_list();
1304
1305             if (defined $result) {
1306                printf "The sysContact for host '%s' was set to '%s'.\n",
1307                       $session->hostname(), $result->{$OID_sysContact};
1308                printf "The sysLocation for host '%s' was set to '%s'.\n",
1309                       $session->hostname(), $result->{$OID_sysLocation};
1310             } else {
1311                printf "ERROR: Set request failed for host '%s': %s.\n",
1312                       $session->hostname(), $session->error();
1313             }
1314
1315             return;
1316          }
1317

REQUIREMENTS

1319       ·   The Net::SNMP module uses syntax that is not supported in versions
1320           of Perl earlier than v5.6.0.
1321
1322       ·   The non-core modules Crypt::DES, Digest::MD5, Digest::SHA1, and
1323           Digest::HMAC are required to support SNMPv3.
1324
1325       ·   In order to support the AES Cipher Algorithm as a SNMPv3 privacy
1326           protocol, the non-core module Crypt::Rijndael is needed.
1327
1328       ·   To use UDP/IPv6 or TCP/IPv6 as a Transport Domain, the non-core
1329           module Socket6 is needed.
1330

AUTHOR

1332       David M. Town <dtown@cpan.org>
1333

ACKNOWLEDGMENTS

1335       The original concept for this module was based on SNMP_Session.pm
1336       written by Simon Leinen <simon@switch.ch>.
1337
1338       The Abstract Syntax Notation One (ASN.1) encode and decode methods were
1339       originally derived by example from the CMU SNMP package whose copyright
1340       follows: Copyright (c) 1988, 1989, 1991, 1992 by Carnegie Mellon
1341       University.  All rights reserved.
1342
1344       Copyright (c) 1998-2010 David M. Town.  All rights reserved.
1345
1346       This program is free software; you may redistribute it and/or modify it
1347       under the same terms as the Perl 5 programming language system itself.
1348
1349
1350
1351perl v5.32.0                      2020-07-28                      Net::SNMP(3)
Impressum