1Net::SNMP(3) User Contributed Perl Documentation Net::SNMP(3)
2
3
4
6 Net::SNMP - Object oriented interface to SNMP
7
9 The Net::SNMP module implements an object oriented interface to the
10 Simple Network Management Protocol. Perl applications can use the mod‐
11 ule to retrieve or update information on a remote host using the SNMP
12 protocol. The module supports SNMP version-1, SNMP version-2c (Commu‐
13 nity-Based SNMPv2), and SNMP version-3. The Net::SNMP module assumes
14 that the user has a basic understanding of the Simple Network Manage‐
15 ment Protocol and related network management concepts.
16
18 The Net::SNMP module abstracts the intricate details of the Simple Net‐
19 work Management Protocol by providing a high level programming inter‐
20 face to the protocol. Each Net::SNMP object provides a one-to-one map‐
21 ping between a Perl object and a remote SNMP agent or manager. Once an
22 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 suc‐
28 cessfully 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" behav‐
34 ior. A method invoked by a non-blocking object queues the SNMP message
35 and returns immediately, allowing the flow of the code to continue. The
36 queued SNMP messages are not sent until an event loop is entered by
37 calling the "snmp_dispatcher()" method. When the SNMP messages are
38 sent, any response to the messages invokes the subroutine defined by
39 the user when the message was originally queued. The event loop exits
40 when all messages have been removed from the queue by either receiving
41 a response, or by exceeding the number of retries at the Transport
42 Layer.
43
44 Blocking Objects
45
46 The default behavior of the methods associated with a Net::SNMP object
47 is to block the code flow until the method completes. For methods that
48 initiate a SNMP protocol exchange requiring a response, a hash refer‐
49 ence containing the results of the query is returned. The undefined
50 value is returned by all methods when a failure has occurred. The
51 "error()" method can be used to determine the cause of the failure.
52
53 The hash reference returned by a SNMP protocol exchange points to a
54 hash constructed from the VarBindList contained in the SNMP response
55 message. The hash is created using the ObjectName and the ObjectSyntax
56 pairs in the VarBindList. The keys of the hash consist of the OBJECT
57 IDENTIFIERs in dotted notation corresponding to each ObjectName in the
58 VarBindList. The value of each hash entry is set equal to the value of
59 the corresponding ObjectSyntax. This hash reference can also be
60 retrieved using the "var_bind_list()" method.
61
62 Non-blocking Objects
63
64 When a Net::SNMP object is created having non-blocking behavior, the
65 invocation of a method associated with the object returns immediately,
66 allowing the flow of the code to continue. When a method is invoked
67 that would initiate a SNMP protocol exchange requiring a response,
68 either a true value (i.e. 0x1) is returned immediately or the undefined
69 value is returned if there was a failure. The "error()" method can be
70 used to determine the cause of the failure.
71
72 The contents of the VarBindList contained in the SNMP response message
73 can be retrieved by calling the "var_bind_list()" method using the
74 object reference passed as the first argument to the callback. The
75 value returned by the "var_bind_list()" method is a hash reference cre‐
76 ated using the ObjectName and the ObjectSyntax pairs in the
77 VarBindList. The keys of the hash consist of the OBJECT IDENTIFIERs in
78 dotted notation corresponding to each ObjectName in the VarBindList.
79 The value of each hash entry is set equal to the value of the corre‐
80 sponding ObjectSyntax. The undefined value is returned if there has
81 been a failure and the "error()" method may be used to determine the
82 reason.
83
85 When named arguments are expected by the methods, two different styles
86 are supported. All examples in this documentation use the dashed-
87 option style:
88
89 $object->method(-argument => $value);
90
91 However, the IO:: style is also allowed:
92
93 $object->method(Argument => $value);
94
95 Non-blocking Objects Arguments
96 When a Net::SNMP object has been created with a "non-blocking"
97 property, most methods that generate a SNMP message take additional
98 arguments to support this property.
99
100 Callback
101 Most methods associated with a non-blocking object have an
102 optional named argument called -callback. The -callback argu‐
103 ment expects a reference to a subroutine or to an array whose
104 first element must be a reference to a subroutine. The subrou‐
105 tine defined by the -callback option is executed when a
106 response to a SNMP message is received, an error condition has
107 occurred, or the number of retries for the message has been
108 exceeded.
109
110 When the -callback argument only contains a subroutine refer‐
111 ence, the subroutine is evaluated passing a reference to the
112 original Net::SNMP object as the only parameter. If the -call‐
113 back argument was defined as an array reference, all elements
114 in the array are passed to subroutine after the reference to
115 the Net::SNMP object. The first element, which is required to
116 be a reference to a subroutine, is removed before the remaining
117 arguments are passed to that subroutine.
118
119 Once one method is invoked with the -callback argument, this
120 argument stays with the object and is used by any further calls
121 to methods using the -callback option if the argument is
122 absent. The undefined value may be passed to the -callback
123 argument to delete the callback.
124
125 NOTE: The subroutine being passed with the -callback named
126 argument should not cause blocking itself. This will cause all
127 the actions in the event loop to be stopped, defeating the non-
128 blocking property of the Net::SNMP module.
129
130 Delay
131 An optional argument -delay can also be passed to non-blocking
132 objects. The -delay argument instructs the object to wait the
133 number of seconds passed to the argument before executing the
134 SNMP protocol exchange. The delay period starts when the event
135 loop is entered. The -delay parameter is applied to all meth‐
136 ods associated with the object once it is specified. The delay
137 value must be set back to 0 seconds to disable the delay param‐
138 eter.
139
140 SNMPv3 Arguments
141 A SNMP context is a collection of management information accessible
142 by a SNMP entity. An item of management information may exist in
143 more than one context and a SNMP entity potentially has access to
144 many contexts. The combination of a contextEngineID and a con‐
145 textName unambiguously identifies a context within an administra‐
146 tive domain. In a SNMPv3 message, the contextEngineID and con‐
147 textName are included as part of the scopedPDU. All methods that
148 generate a SNMP message optionally take a -contextengineid and
149 -contextname argument to configure these fields.
150
151 Context Engine ID
152 The -contextengineid argument expects a hexadecimal string rep‐
153 resenting the desired contextEngineID. The string must be 10
154 to 64 characters (5 to 32 octets) long and can be prefixed with
155 an optional "0x". Once the -contextengineid is specified it
156 stays with the object until it is changed again or reset to
157 default by passing in the undefined value. By default, the
158 contextEngineID is set to match the authoritativeEngineID of
159 the authoritative SNMP engine.
160
161 Context Name
162 The contextName is passed as a string which must be 0 to 32
163 octets in length using the -contextname argument. The con‐
164 textName stays with the object until it is changed. The con‐
165 textName defaults to an empty string which represents the
166 "default" context.
167
168 session() - create a new Net::SNMP object
169
170 ($session, $error) = Net::SNMP->session(
171 [-hostname => $hostname,]
172 [-port => $port,]
173 [-localaddr => $localaddr,]
174 [-localport => $localport,]
175 [-nonblocking => $boolean,]
176 [-version => $version,]
177 [-domain => $domain,]
178 [-timeout => $seconds,]
179 [-retries => $count,]
180 [-maxmsgsize => $octets,]
181 [-translate => $translate,]
182 [-debug => $bitmask,]
183 [-community => $community,] # v1/v2c
184 [-username => $username,] # v3
185 [-authkey => $authkey,] # v3
186 [-authpassword => $authpasswd,] # v3
187 [-authprotocol => $authproto,] # v3
188 [-privkey => $privkey,] # v3
189 [-privpassword => $privpasswd,] # v3
190 [-privprotocol => $privproto,] # v3
191 );
192
193 This is the constructor for Net::SNMP objects. In scalar context, a
194 reference to a new Net::SNMP object is returned if the creation of the
195 object is successful. In list context, a reference to a new Net::SNMP
196 object and an empty error message string is returned. If a failure
197 occurs, the object reference is returned as the undefined value. The
198 error string may be used to determine the cause of the error.
199
200 Most of the named arguments passed to the constructor define basic
201 attributes for the object and are not modifiable after the object has
202 been created. The -timeout, -retries, -maxmsgsize, -translate, and
203 -debug arguments are modifiable using an accessor method. See their
204 corresponding method definitions for a complete description of their
205 usage, default values, and valid ranges.
206
207 Transport Domain Arguments
208 The Net::SNMP module uses UDP/IPv4 as the default Transport Domain
209 to exchange SNMP messages between the local and remote devices.
210 The module also supports UDP/IPv6, TCP/IPv4, and TCP/IPv6 as alter‐
211 native Transport Domains. The -domain argument can be used to
212 change the Transport Domain by setting the value to one of the fol‐
213 lowing strings: 'udp6', 'udp/ipv6'; 'tcp', 'tcp4', 'tcp/ipv4';
214 'tcp6', or 'tcp/ipv6'. The -domain argument also accepts the
215 strings 'udp', 'udp4', or 'udp/ipv4' which correspond to the
216 default Transport Domain of UDP/IPv4.
217
218 The transport address of the destination SNMP device can be speci‐
219 fied using the -hostname argument. This argument is optional and
220 defaults to "localhost". The destination port number can be speci‐
221 fied as part of the transport address or by using the -port argu‐
222 ment. Either a numeric port number or a textual service name can
223 be specified. A numeric port number in parentheses can optionally
224 follow the service name. This port number will be used if the ser‐
225 vice name cannot be resolved. If the destination port number is
226 not specified, the well-known SNMP port number 161 is used.
227
228 By default the source transport address and port number are
229 assigned dynamically by the local device on which the Net::SNMP
230 module is being used. This dynamic assignment can be overridden by
231 using the -localaddr and -localport arguments. These arguments
232 accept the same values as the -hostname and -port arguments respec‐
233 tively. The resolved address must correspond to a valid address of
234 an interface on the local device.
235
236 When using an IPv4 Transport Domain, the transport address can be
237 specified as either an IP network hostname or an IPv4 address in
238 standard dotted notation. The port information can be optionally
239 appended to the hostname or address delimited by a colon. The
240 accepted IPv4 transport address formats are "address",
241 "address:port", "hostname", and "hostname:port".
242
243 When using an IPv6 Transport Domain, the transport address can be
244 specified as an IP hostname (which will be looked up as a DNS quad-
245 A record) or an IPv6 address in presentation format. The port
246 information can optionally be included following a colon after the
247 hostname or address. When including this information after an IPv6
248 address, the address must be enclosed in square brackets. The
249 scope zone index (described in RFC 4007) can be specified after the
250 address as a decimal value delimited by a percent sign. The
251 accepted transport address formats for IPv6 are "address",
252 "address%zone", "[address]:port", "[address%zone]:port", "host‐
253 name", and "hostname:port".
254
255 Security Model Arguments
256 The -version argument controls which other arguments are expected
257 or required by the "session()" constructor. The Net::SNMP module
258 supports SNMPv1, SNMPv2c, and SNMPv3. The module defaults to
259 SNMPv1 if no -version argument is specified. The -version argument
260 expects either a digit (i.e. '1', '2', or '3') or a string speci‐
261 fying the version (i.e. 'snmpv1', 'snmpv2c', or 'snmpv3') to define
262 the SNMP version.
263
264 The Security Model used by the Net::SNMP object is based on the
265 SNMP version associated with the object. If the SNMP version is
266 SNMPv1 or SNMPv2c a Community-based Security Model will be used,
267 while the User-based Security Model (USM) will be used if the ver‐
268 sion is SNMPv3.
269
270 Community-based Security Model Argument
271 If the Security Model is Community-based, the only argument
272 available is the -community argument. This argument expects a
273 string that is to be used as the SNMP community name. By
274 default the community name is set to 'public' if the argument
275 is not present.
276
277 User-based Security Model Arguments
278 The User-based Security Model (USM) used by SNMPv3 requires
279 that a securityName be specified using the -username argument.
280 The creation of a Net::SNMP object with the version set to
281 SNMPv3 will fail if the -username argument is not present. The
282 -username argument expects a string 1 to 32 octets in length.
283
284 Different levels of security are allowed by the User-based
285 Security Model which address authentication and privacy con‐
286 cerns. A SNMPv3 Net::SNMP object will derive the security
287 level (securityLevel) based on which of the following arguments
288 are specified.
289
290 By default a securityLevel of 'noAuthNoPriv' is assumed. If
291 the -authkey or -authpassword arguments are specified, the
292 securityLevel becomes 'authNoPriv'. The -authpassword argument
293 expects a string which is at least 1 octet in length. Option‐
294 ally, the -authkey argument can be used so that a plain text
295 password does not have to be specified in a script. The
296 -authkey argument expects a hexadecimal string produced by
297 localizing the password with the authoritativeEngineID for the
298 specific destination device. The "snmpkey" utility included
299 with the distribution can be used to create the hexadecimal
300 string (see snmpkey).
301
302 Two different hash algorithms are defined by SNMPv3 which can
303 be used by the Security Model for authentication. These algo‐
304 rithms are HMAC-MD5-96 "MD5" (RFC 1321) and HMAC-SHA-96 "SHA-1"
305 (NIST FIPS PUB 180-1). The default algorithm used by the mod‐
306 ule is HMAC-MD5-96. This behavior can be changed by using the
307 -authprotocol argument. This argument expects either the
308 string 'md5' or 'sha' to be passed to modify the hash algo‐
309 rithm.
310
311 By specifying the arguments -privkey or -privpassword the secu‐
312 rityLevel associated with the object becomes 'authPriv'.
313 According to SNMPv3, privacy requires the use of authentica‐
314 tion. Therefore, if either of these two arguments are present
315 and the -authkey or -authpassword arguments are missing, the
316 creation of the object fails. The -privkey and -privpassword
317 arguments expect the same input as the -authkey and -authpass‐
318 word arguments respectively.
319
320 The User-based Security Model described in RFC 3414 defines a
321 single encryption protocol to be used for privacy. This proto‐
322 col, CBC-DES "DES" (NIST FIPS PUB 46-1), is used by default or
323 if the string 'des' is passed to the -privprotocol argument.
324 The module also supports RFC 3826 which describes the use of
325 CFB128-AES-128 "AES" (NIST FIPS PUB 197) in the USM. The AES
326 encryption protocol can be selected by passing 'aes' or
327 'aes128' to the -privprotocol argument. By working with the
328 Extended Security Options Consortium
329 <http://www.snmp.com/eso/>, the module also supports
330 CBC-3DES-EDE "Triple-DES" (NIST FIPS 46-3) in the User-based
331 Security Model. This is defined in the draft
332 <http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt>.
333 The Triple-DES encryption protocol can be selected using the
334 -privprotocol argument with the string '3des' or '3desede'.
335
336 close() - clear the Transport Domain associated with the object
337
338 $session->close;
339
340 This method clears the Transport Domain and any errors associated with
341 the object. Once closed, the Net::SNMP object can no longer be used to
342 send or receive SNMP messages.
343
344 snmp_dispatcher() - enter the non-blocking object event loop
345
346 $session->snmp_dispatcher();
347
348 This method enters the event loop associated with non-blocking
349 Net::SNMP objects. The method exits when all queued SNMP messages have
350 received a response or have timed out at the Transport Layer. This
351 method is also exported as the stand alone function "snmp_dispatcher()"
352 by default (see "EXPORTS").
353
354 get_request() - send a SNMP get-request to the remote agent
355
356 $result = $session->get_request(
357 [-callback => sub {},] # non-blocking
358 [-delay => $seconds,] # non-blocking
359 [-contextengineid => $engine_id,] # v3
360 [-contextname => $name,] # v3
361 -varbindlist => \@oids,
362 );
363
364 This method performs a SNMP get-request query to gather data from the
365 remote agent on the host associated with the Net::SNMP object. The
366 message is built using the list of OBJECT IDENTIFIERs in dotted nota‐
367 tion passed to the method as an array reference using the -varbindlist
368 argument. Each OBJECT IDENTIFER is placed into a single SNMP GetRe‐
369 quest-PDU in the same order that it held in the original list.
370
371 A reference to a hash is returned in blocking mode which contains the
372 contents of the VarBindList. In non-blocking mode, a true value is
373 returned when no error has occurred. In either mode, the undefined
374 value is returned when an error has occurred. The "error()" method may
375 be used to determine the cause of the failure.
376
377 get_next_request() - send a SNMP get-next-request to the remote agent
378
379 $result = $session->get_next_request(
380 [-callback => sub {},] # non-blocking
381 [-delay => $seconds,] # non-blocking
382 [-contextengineid => $engine_id,] # v3
383 [-contextname => $name,] # v3
384 -varbindlist => \@oids,
385 );
386
387 This method performs a SNMP get-next-request query to gather data from
388 the remote agent on the host associated with the Net::SNMP object. The
389 message is built using the list of OBJECT IDENTIFIERs in dotted nota‐
390 tion passed to the method as an array reference using the -varbindlist
391 argument. Each OBJECT IDENTIFER is placed into a single SNMP GetNex‐
392 tRequest-PDU in the same order that it held in the original list.
393
394 A reference to a hash is returned in blocking mode which contains the
395 contents of the VarBindList. In non-blocking mode, a true value is
396 returned when no error has occurred. In either mode, the undefined
397 value is returned when an error has occurred. The "error()" method may
398 be used to determine the cause of the failure.
399
400 set_request() - send a SNMP set-request to the remote agent
401
402 $result = $session->set_request(
403 [-callback => sub {},] # non-blocking
404 [-delay => $seconds,] # non-blocking
405 [-contextengineid => $engine_id,] # v3
406 [-contextname => $name,] # v3
407 -varbindlist => \@oid_value,
408 );
409
410 This method is used to modify data on the remote agent that is associ‐
411 ated with the Net::SNMP object using a SNMP set-request. The message
412 is built using a list of values consisting of groups of an OBJECT IDEN‐
413 TIFIER, an object type, and the actual value to be set. This list is
414 passed to the method as an array reference using the -varbindlist argu‐
415 ment. The OBJECT IDENTIFIERs in each trio are to be in dotted nota‐
416 tion. The object type is an octet corresponding to the ASN.1 type of
417 value that is to be set. Each of the supported ASN.1 types have been
418 defined and are exported by the package by default (see "EXPORTS").
419
420 A reference to a hash is returned in blocking mode which contains the
421 contents of the VarBindList. In non-blocking mode, a true value is
422 returned when no error has occurred. In either mode, the undefined
423 value is returned when an error has occurred. The "error()" method may
424 be used to determine the cause of the failure.
425
426 trap() - send a SNMP trap to the remote manager
427
428 $result = $session->trap(
429 [-delay => $seconds,] # non-blocking
430 [-enterprise => $oid,]
431 [-agentaddr => $ipaddress,]
432 [-generictrap => $generic,]
433 [-specifictrap => $specific,]
434 [-timestamp => $timeticks,]
435 -varbindlist => \@oid_value,
436 );
437
438 This method sends a SNMP trap to the remote manager associated with the
439 Net::SNMP object. All arguments are optional and will be given the
440 following defaults in the absence of a corresponding named argument:
441
442 · The default value for the trap -enterprise is "1.3.6.1.4.1", which
443 corresponds to "iso.org.dod.internet.private.enterprises". The
444 enterprise value is expected to be an OBJECT IDENTIFER in dotted
445 notation.
446
447 · When the Transport Domain is UDP/IPv4 or TCP/IPv4, the default
448 value for the trap -agentaddr is the IP address associated with the
449 interface on which the trap will be transmitted. For other Trans‐
450 port Domains the -agentaddr is defaulted to "0.0.0.0". When speci‐
451 fied, the agent-addr is expected to be an IpAddress in dotted nota‐
452 tion.
453
454 · The default value for the -generictrap type is 6 which corresponds
455 to "enterpriseSpecific". The generic-trap types are defined and
456 can be exported upon request (see "EXPORTS").
457
458 · The default value for the -specifictrap type is 0. No pre-defined
459 values are available for specific-trap types.
460
461 · The default value for the trap -timestamp is the "uptime" of the
462 script. The "uptime" of the script is the number of hundredths of
463 seconds that have elapsed since the script began running. The
464 time-stamp is expected to be a TimeTicks number in hundredths of
465 seconds.
466
467 · The default value for the trap -varbindlist is an empty array ref‐
468 erence. The variable-bindings are expected to be in an array for‐
469 mat consisting of groups of an OBJECT IDENTIFIER, an object type,
470 and the actual value of the object. This is identical to the list
471 expected by the "set_request()" method. The OBJECT IDENTIFIERs in
472 each trio are to be in dotted notation. The object type is an
473 octet corresponding to the ASN.1 type for the value. Each of the
474 supported types have been defined and are exported by default (see
475 "EXPORTS").
476
477 A true value is returned when the method is successful. The undefined
478 value is returned when a failure has occurred. The "error()" method
479 can be used to determine the cause of the failure. Since there are no
480 acknowledgements for Trap-PDUs, there is no way to determine if the
481 remote host actually received the trap.
482
483 NOTE: When the object is in non-blocking mode, the trap is not sent
484 until the event loop is entered and no callback is ever executed.
485
486 NOTE: This method can only be used when the version of the object is
487 set to SNMPv1.
488
489 get_bulk_request() - send a SNMP get-bulk-request to the remote agent
490
491 $result = $session->get_bulk_request(
492 [-callback => sub {},] # non-blocking
493 [-delay => $seconds,] # non-blocking
494 [-contextengineid => $engine_id,] # v3
495 [-contextname => $name,] # v3
496 [-nonrepeaters => $non_reps,]
497 [-maxrepetitions => $max_reps,]
498 -varbindlist => \@oids,
499 );
500
501 This method performs a SNMP get-bulk-request query to gather data from
502 the remote agent on the host associated with the Net::SNMP object. All
503 arguments are optional except -varbindlist and will be given the fol‐
504 lowing defaults in the absence of a corresponding named argument:
505
506 · The default value for the get-bulk-request -nonrepeaters is 0. The
507 non-repeaters value specifies the number of variables in the vari‐
508 able-bindings list for which a single successor is to be returned.
509
510 · The default value for the get-bulk-request -maxrepetitions is 0.
511 The max-repetitions value specifies the number of successors to be
512 returned for the remaining variables in the variable-bindings list.
513
514 · The -varbindlist argument expects an array reference consisting of
515 a list of OBJECT IDENTIFIERs in dotted notation. Each OBJECT IDEN‐
516 TIFER is placed into a single SNMP GetBulkRequest-PDU in the same
517 order that it held in the original list.
518
519 A reference to a hash is returned in blocking mode which contains the
520 contents of the VarBindList. In non-blocking mode, a true value is
521 returned when no error has occurred. In either mode, the undefined
522 value is returned when an error has occurred. The "error()" method may
523 be used to determine the cause of the failure.
524
525 NOTE: This method can only be used when the version of the object is
526 set to SNMPv2c or SNMPv3.
527
528 inform_request() - send a SNMP inform-request to the remote manager
529
530 $result = $session->inform_request(
531 [-callback => sub {},] # non-blocking
532 [-delay => $seconds,] # non-blocking
533 [-contextengineid => $engine_id,] # v3
534 [-contextname => $name,] # v3
535 -varbindlist => \@oid_value,
536 );
537
538 This method is used to provide management information to the remote
539 manager associated with the Net::SNMP object using an inform-request.
540 The message is built using a list of values consisting of groups of an
541 OBJECT IDENTIFIER, an object type, and the actual value to be identi‐
542 fied. This list is passed to the method as an array reference using
543 the -varbindlist argument. The OBJECT IDENTIFIERs in each trio are to
544 be in dotted notation. The object type is an octet corresponding to
545 the ASN.1 type of value that is to be identified. Each of the sup‐
546 ported ASN.1 types have been defined and are exported by the package by
547 default (see "EXPORTS").
548
549 The first two variable-bindings fields in the inform-request are speci‐
550 fied by SNMPv2 and should be:
551
552 · sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
553
554 · snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
555
556 A reference to a hash is returned in blocking mode which contains the
557 contents of the VarBindList. In non-blocking mode, a true value is
558 returned when no error has occurred. In either mode, the undefined
559 value is returned when an error has occurred. The "error()" method may
560 be used to determine the cause of the failure.
561
562 NOTE: This method can only be used when the version of the object is
563 set to SNMPv2c or SNMPv3.
564
565 snmpv2_trap() - send a SNMP snmpV2-trap to the remote manager
566
567 $result = $session->snmpv2_trap(
568 [-delay => $seconds,] # non-blocking
569 -varbindlist => \@oid_value,
570 );
571
572 This method sends a snmpV2-trap to the remote manager associated with
573 the Net::SNMP object. The message is built using a list of values con‐
574 sisting of groups of an OBJECT IDENTIFIER, an object type, and the
575 actual value to be identified. This list is passed to the method as an
576 array reference using the -varbindlist argument. The OBJECT IDENTI‐
577 FIERs in each trio are to be in dotted notation. The object type is an
578 octet corresponding to the ASN.1 type of value that is to be identi‐
579 fied. Each of the supported ASN.1 types have been defined and are
580 exported by the package by default (see "EXPORTS").
581
582 The first two variable-bindings fields in the snmpV2-trap are specified
583 by SNMPv2 and should be:
584
585 · sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
586
587 · snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
588
589 A true value is returned when the method is successful. The undefined
590 value is returned when a failure has occurred. The "error()" method
591 can be used to determine the cause of the failure. Since there are no
592 acknowledgements for SNMPv2-Trap-PDUs, there is no way to determine if
593 the remote host actually received the snmpV2-trap.
594
595 NOTE: When the object is in non-blocking mode, the snmpV2-trap is not
596 sent until the event loop is entered and no callback is ever executed.
597
598 NOTE: This method can only be used when the version of the object is
599 set to SNMPv2c. SNMPv2-Trap-PDUs are supported by SNMPv3, but require
600 the sender of the message to be an authoritative SNMP engine which is
601 not currently supported by the Net::SNMP module.
602
603 get_table() - retrieve a table from the remote agent
604
605 $result = $session->get_table(
606 [-callback => sub {},] # non-blocking
607 [-delay => $seconds,] # non-blocking
608 [-contextengineid => $engine_id,] # v3
609 [-contextname => $name,] # v3
610 -baseoid => $oid,
611 [-maxrepetitions => $max_reps,] # v2c/v3
612 );
613
614 This method performs repeated SNMP get-next-request or get-bulk-request
615 (when using SNMPv2c or SNMPv3) queries to gather data from the remote
616 agent on the host associated with the Net::SNMP object. The first mes‐
617 sage sent is built using the OBJECT IDENTIFIER in dotted notation
618 passed to the method by the -baseoid argument. Repeated SNMP requests
619 are issued until the OBJECT IDENTIFIER in the response is no longer a
620 child of the base OBJECT IDENTIFIER.
621
622 The -maxrepetitions argument can be used to specify the max-repetitions
623 value that is passed to the get-bulk-requests when using SNMPv2c or
624 SNMPv3. If this argument is not present, a value is calculated based
625 on the maximum message size for the Net::SNMP object. If the value is
626 set to 1 or less, get-next-requests will be used for the queries
627 instead of get-bulk-requests.
628
629 A reference to a hash is returned in blocking mode which contains the
630 contents of the VarBindList. In non-blocking mode, a true value is
631 returned when no error has occurred. In either mode, the undefined
632 value is returned when an error has occurred. The "error()" method may
633 be used to determine the cause of the failure.
634
635 WARNING: Results from this method can become very large if the base
636 OBJECT IDENTIFIER is close to the root of the SNMP MIB tree.
637
638 get_entries() - retrieve table entries from the remote agent
639
640 $result = $session->get_entries(
641 [-callback => sub {},] # non-blocking
642 [-delay => $seconds,] # non-blocking
643 [-contextengineid => $engine_id,] # v3
644 [-contextname => $name,] # v3
645 -columns => \@columns,
646 [-startindex => $start,]
647 [-endindex => $end,]
648 [-maxrepetitions => $max_reps,] # v2c/v3
649 );
650
651 This method performs repeated SNMP get-next-request or get-bulk-request
652 (when using SNMPv2c or SNMPv3) queries to gather data from the remote
653 agent on the host associated with the Net::SNMP object. Each message
654 specifically requests data for each OBJECT IDENTIFIER specified in the
655 -columns array. The OBJECT IDENTIFIERs must correspond to column
656 entries for a conceptual row in a table. They may however be columns
657 in different tables as long as each table is indexed the same way. The
658 optional -startindex and -endindex arguments may be specified to limit
659 the query to specific rows in the table(s).
660
661 The -startindex can be specified as a single decimal value or in dotted
662 notation if the index associated with the entry so requires. If the
663 -startindex is specified, it will be include as part of the query
664 results. If no -startindex is specified, the first request message
665 will be sent without an index. To insure that the -startindex is
666 included, the last subidentifier in the index is decremented by one.
667 If the last subidentifier has a value of zero, the subidentifier is
668 removed from the index.
669
670 The optional -endindex argument can be specified as a single decimal
671 value or in dotted notation. If the -endindex is specified, it will be
672 included as part of the query results. If no -endindex is specified,
673 repeated SNMP requests are issued until the response no longer returns
674 entries matching any of the columns specified in the -columns array.
675
676 The -maxrepetitions argument can be used to specify the max-repetitions
677 value that is passed to the get-bulk-requests when using SNMPv2c or
678 SNMPv3. If this argument is not present, a value is calculated based
679 on the maximum message size of the object and the number of columns
680 specified in the -columns array. If the value is set to 1 or less,
681 get-next-requests will be used for the queries instead of
682 get-bulk-requests.
683
684 A reference to a hash is returned in blocking mode which contains the
685 contents of the VarBindList. In non-blocking mode, a true value is
686 returned when no error has occurred. In either mode, the undefined
687 value is returned when an error has occurred. The "error()" method may
688 be used to determine the cause of the failure.
689
690 version() - get the SNMP version from the object
691
692 $rfc_version = $session->version;
693
694 This method returns the current value for the SNMP version associated
695 with the object. The returned value is the corresponding version num‐
696 ber defined by the RFCs for the protocol version field (i.e. SNMPv1 ==
697 0, SNMPv2c == 1, and SNMPv3 == 3). The RFC versions are defined as
698 constant by the module and can be exported by request (see "EXPORTS").
699
700 error() - get the current error message from the object
701
702 $error_message = $session->error;
703
704 This method returns a text string explaining the reason for the last
705 error. An empty string is returned if no error has occurred.
706
707 hostname() - get the hostname associated with the object
708
709 $hostname = $session->hostname;
710
711 This method returns the hostname string that is associated with the
712 object as it was passed to the "session()" constructor.
713
714 error_status() - get the current SNMP error-status from the object
715
716 $error_status = $session->error_status;
717
718 This method returns the numeric value of the error-status contained in
719 the last SNMP message received by the object.
720
721 error_index() - get the current SNMP error-index from the object
722
723 $error_index = $session->error_index;
724
725 This method returns the numeric value of the error-index contained in
726 the last SNMP message received by the object.
727
728 var_bind_list() - get the hash reference for the VarBindList values
729
730 $values = $session->var_bind_list;
731
732 This method returns a hash reference created using the ObjectName and
733 the ObjectSyntax pairs in the VarBindList of the last SNMP message
734 received by the object. The keys of the hash consist of the OBJECT
735 IDENTIFIERs in dotted notation corresponding to each ObjectName in the
736 VarBindList. If any of the OBJECT IDENTIFIERs passed to the request
737 method began with a leading dot, all of the OBJECT IDENTIFIER hash keys
738 will be prefixed with a leading dot. If duplicate OBJECT IDENTIFIERs
739 are present in the VarBindList they will be padded with spaces to make
740 them an uniq hash key. The value of each hash entry is set equal to
741 the value of the corresponding ObjectSyntax. The undefined value is
742 returned if there has been a failure.
743
744 var_bind_names() - get the array of the ObjectNames in the VarBindList
745
746 @names = $session->var_bind_names;
747
748 This method returns an array containing the OBJECT IDENTIFIERs corre‐
749 sponding to the ObjectNames in the VarBindList in the order that they
750 were received in the last SNMP message. The entries in the array will
751 map directly to the keys in the hash reference returned by the methods
752 that perform SNMP message exchanges and by the "var_bind_list()" and
753 "var_bind_types()" methods. The array returned for the convenience
754 methods "get_table()" and "get_entries()" will be in lexicographical
755 order. An empty array is returned if there has been a failure.
756
757 var_bind_types() - get the hash reference for the VarBindList ASN.1
758 types
759
760 $types = $session->var_bind_types;
761
762 This method returns a hash reference created using the ObjectName and
763 the ASN.1 type of the ObjectSyntax in the VarBindList of the last SNMP
764 message received by the object. The keys of the hash consist of the
765 OBJECT IDENTIFIERs in dotted notation corresponding to each ObjectName
766 in the VarBindList. The value of each hash entry is set equal to the
767 ASN.1 type of the corresponding ObjectSyntax. Constants for the sup‐
768 ported ASN.1 types have been defined and are exported by the package by
769 default (see "EXPORTS"). The undefined value is returned if there has
770 been a failure.
771
772 timeout() - set or get the current timeout period for the object
773
774 $seconds = $session->timeout([$seconds]);
775
776 This method returns the current value for the Transport Layer timeout
777 for the Net::SNMP object. This value is the number of seconds that the
778 object will wait for a response from the agent on the remote host. The
779 default timeout is 5.0 seconds.
780
781 If a parameter is specified, the timeout for the object is set to the
782 provided value if it falls within the range 1.0 to 60.0 seconds. The
783 undefined value is returned upon an error and the "error()" method may
784 be used to determine the cause.
785
786 retries() - set or get the current retry count for the object
787
788 $count = $session->retries([$count]);
789
790 This method returns the current value for the number of times to retry
791 sending a SNMP message to the remote host. The default number of
792 retries is 1.
793
794 If a parameter is specified, the number of retries for the object is
795 set to the provided value if it falls within the range 0 to 20. The
796 undefined value is returned upon an error and the "error()" method may
797 be used to determine the cause.
798
799 max_msg_size() - set or get the current maxMsgSize for the object
800
801 $octets = $session->max_msg_size([$octets]);
802
803 This method returns the current value for the maximum message size
804 (maxMsgSize) for the Net::SNMP object. This value is the largest mes‐
805 sage size in octets that can be prepared or processed by the object.
806 The default maxMsgSize is 1472 octets for UDP/IPv4, 1452 octets for
807 UDP/IPv6, 1460 octets for TCP/IPv4, and 1440 octets for TCP/IPv6.
808
809 If a parameter is specified, the maxMsgSize is set to the provided
810 value if it falls within the range 484 to 65535 octets. The undefined
811 value is returned upon an error and the "error()" method may be used to
812 determine the cause.
813
814 NOTE: When using SNMPv3, the maxMsgSize is actually contained in the
815 SNMP message (as msgMaxSize). If the value received from a remote
816 device is less than the current maxMsgSize, the size is automatically
817 adjusted to be the lower value.
818
819 translate() - enable or disable the translation mode for the object
820
821 $mask = $session->translate([
822 $mode ⎪
823 [ # Perl anonymous ARRAY reference
824 ['-all' => $mode0,]
825 ['-octetstring => $mode1,]
826 ['-null' => $mode2,]
827 ['-timeticks' => $mode3,]
828 ['-opaque' => $mode4,]
829 ['-nosuchobject' => $mode5,]
830 ['-nosuchinstance' => $mode6,]
831 ['-endofmibview' => $mode7,]
832 ['-unsigned' => $mode8]
833 ]
834 ]);
835
836 When the object decodes the GetResponse-PDU that is returned in
837 response to a SNMP message, certain values are translated into a more
838 "human readable" form. By default the following translations occur:
839
840 · OCTET STRINGs and Opaques containing non-printable ASCII characters
841 are converted into a hexadecimal representation prefixed with "0x".
842 NOTE: The following ASCII control characters are considered to be
843 printable by the module: NUL(0x00), HT(0x09), LF(0x0A), FF(0x0C),
844 and CR(0x0D).
845
846 · TimeTicks integer values are converted to a time format.
847
848 · NULL values return the string "NULL" instead of an empty string.
849
850 · noSuchObject exception values return the string "noSuchObject"
851 instead of an empty string. If translation is not enabled, the
852 SNMP error-status field is set to 128 which is equal to the
853 exported definition NOSUCHOBJECT (see "EXPORTS").
854
855 · noSuchInstance exception values return the string "noSuchInstance"
856 instead of an empty string. If translation is not enabled, the
857 SNMP error-status field is set to 129 which is equal to the
858 exported definition NOSUCHINSTANCE (see "EXPORTS").
859
860 · endOfMibView exception values return the string "endOfMibView"
861 instead of an empty string. If translation is not enabled, the
862 SNMP error-status field is set to 130 which is equal to the
863 exported definition ENDOFMIBVIEW (see "EXPORTS").
864
865 · Counter64, Counter, Gauge, and TimeTick values that have been
866 incorrectly encoded as signed negative values are returned as
867 unsigned values.
868
869 The "translate()" method can be invoked with two different types of
870 arguments.
871
872 If the argument passed is any Perl variable type except an array refer‐
873 ence, the translation mode for all ASN.1 types is set to either enabled
874 or disabled, depending on the value of the passed parameter. Any value
875 that Perl would treat as a true value will set the mode to be enabled
876 for all types, while a false value will disable translation for all
877 types.
878
879 A reference to an array can be passed to the "translate()" method in
880 order to define the translation mode on a per ASN.1 type basis. The
881 array is expected to contain a list of named argument pairs for each
882 ASN.1 type that is to be modified. The arguments in the list are
883 applied in the order that they are passed in via the array. Arguments
884 at the end of the list supercede those passed earlier in the list. The
885 argument "-all" can be used to specify that the mode is to apply to all
886 ASN.1 types. Only the arguments for the ASN.1 types that are to be
887 modified need to be included in the list.
888
889 The "translate()" method returns a bit mask indicating which ASN.1
890 types are to be translated. Definitions of the bit to ASN.1 type map‐
891 pings can be exported using the :translate tag (see "EXPORTS"). The
892 undefined value is returned upon an error and the "error()" method may
893 be used to determine the cause.
894
895 debug() - set or get the debug mode for the module
896
897 $mask = $session->debug([$mask]);
898
899 This method is used to enable or disable debugging for the Net::SNMP
900 module. Debugging can be enabled on a per component level as defined
901 by a bit mask passed to the "debug()" method. The bit mask is broken
902 up as follows:
903
904 · 0x02 - Message or PDU encoding and decoding
905
906 · 0x04 - Transport Layer
907
908 · 0x08 - Dispatcher
909
910 · 0x10 - Message Processing
911
912 · 0x20 - Security
913
914 Symbols representing these bit mask values are defined by the module
915 and can be exported using the :debug tag (see "EXPORTS"). If a non-
916 numeric value is passed to the "debug()" method, it is evaluated in
917 boolean context. Debugging for all of the components is then enabled
918 or disabled based on the resulting truth value.
919
920 The current debugging mask is returned by the method. Debugging can
921 also be enabled using the stand alone function "snmp_debug()". This
922 function can be exported by request (see "EXPORTS").
923
925 oid_base_match() - determine if an OID has a specified OID base
926
927 $value = oid_base_match($base_oid, $oid);
928
929 This function takes two OBJECT IDENTIFIERs in dotted notation and
930 returns a true value (i.e. 0x1) if the second OBJECT IDENTIFIER is
931 equal to or is a child of the first OBJECT IDENTIFIER in the SNMP Man‐
932 agement Information Base (MIB). This function can be used in conjunc‐
933 tion with the "get-next-request()" or "get-bulk-request()" methods to
934 determine when a OBJECT IDENTIFIER in the GetResponse-PDU is no longer
935 in the desired MIB tree branch.
936
937 oid_lex_sort() - sort a list of OBJECT IDENTIFIERs lexicographically
938
939 @sorted_oids = oid_lex_sort(@oids);
940
941 This function takes a list of OBJECT IDENTIFIERs in dotted notation and
942 returns the listed sorted in lexicographical order.
943
944 snmp_type_ntop() - convert an ASN.1 type to presentation format
945
946 $text = snmp_type_ntop($type);
947
948 This function takes an ASN.1 type octet and returns a text string suit‐
949 able for presentation. Some ASN.1 type definitions map to the same
950 octet value when encoded. This method cannot distinquish between these
951 multiple mappings and the most basic type name will be returned.
952
953 ticks_to_time() - convert TimeTicks to formatted time
954
955 $time = ticks_to_time($timeticks);
956
957 This function takes an ASN.1 TimeTicks value and returns a string rep‐
958 resenting the time defined by the value. The TimeTicks value is
959 expected to be a non-negative integer value representing the time in
960 hundredths of a second since some epoch. The returned string will dis‐
961 play the time in days, hours, and seconds format according to the value
962 of the TimeTicks argument.
963
965 The Net::SNMP module uses the Exporter module to export useful con‐
966 stants and subroutines. These exportable symbols are defined below and
967 follow the rules and conventions of the Exporter module (see Exporter).
968
969 Default
970 &snmp_dispatcher, INTEGER, INTEGER32, OCTET_STRING, OBJECT_IDENTI‐
971 FIER, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32, UNSIGNED32,
972 TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT, NOSUCHINSTANCE, END‐
973 OFMIBVIEW
974
975 Exportable
976 &snmp_debug, &snmp_dispatcher, &snmp_type_ntop, &oid_base_match,
977 &oid_lex_sort, &ticks_to_time, INTEGER, INTEGER32, OCTET_STRING,
978 NULL, OBJECT_IDENTIFIER, SEQUENCE, IPADDRESS, COUNTER, COUNTER32,
979 GAUGE, GAUGE32, UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOB‐
980 JECT, NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST, GET_NEXT_REQUEST,
981 GET_RESPONSE, SET_REQUEST, TRAP, GET_BULK_REQUEST, INFORM_REQUEST,
982 SNMPV2_TRAP, REPORT, DEBUG_ALL, DEBUG_NONE, DEBUG_MESSAGE,
983 DEBUG_TRANSPORT, DEBUG_DISPATCHER,DEBUG_PROCESSING, DEBUG_SECURITY,
984 COLD_START, WARM_START, LINK_DOWN, LINK_UP,AUTHENTICATION_FAILURE,
985 EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC, SNMP_VERSION_1,SNMP_VER‐
986 SION_2C, SNMP_VERSION_3, SNMP_PORT, SNMP_TRAP_PORT, TRANS‐
987 LATE_NONE,TRANSLATE_OCTET_STRING, TRANSLATE_NULL, TRANSLATE_TIMET‐
988 ICKS, TRANSLATE_OPAQUE,TRANSLATE_NOSUCHOBJECT, TRANSLATE_NOSUCHIN‐
989 STANCE, TRANSLATE_ENDOFMIBVIEW, TRANSLATE_UNSIGNED, TRANSLATE_ALL
990
991 Tags
992 :asn1
993 INTEGER, INTEGER32, OCTET_STRING, NULL, OBJECT_IDENTIFIER,
994 SEQUENCE, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32,
995 UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT,
996 NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST, GET_NEXT_REQUEST,
997 GET_RESPONSE, SET_REQUEST, TRAP, GET_BULK_REQUEST,
998 INFORM_REQUEST, SNMPV2_TRAP, REPORT
999
1000 :debug
1001 &snmp_debug, DEBUG_ALL, DEBUG_NONE, DEBUG_MESSAGE, DEBUG_TRANS‐
1002 PORT, DEBUG_DISPATCHER, DEBUG_PROCESSING, DEBUG_SECURITY
1003
1004 :generictrap
1005 COLD_START, WARM_START, LINK_DOWN, LINK_UP, AUTHENTICA‐
1006 TION_FAILURE, EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC
1007
1008 :snmp
1009 &snmp_debug, &snmp_dispatcher, &snmp_type_ntop,
1010 &oid_base_match, &oid_lex_sort, &ticks_to_time, SNMP_VERSION_1,
1011 SNMP_VERSION_2C, SNMP_VERSION_3, SNMP_PORT, SNMP_TRAP_PORT
1012
1013 :translate
1014 TRANSLATE_NONE, TRANSLATE_OCTET_STRING, TRANSLATE_NULL, TRANS‐
1015 LATE_TIMETICKS, TRANSLATE_OPAQUE, TRANSLATE_NOSUCHOBJECT,
1016 TRANSLATE_NOSUCHINSTANCE, TRANSLATE_ENDOFMIBVIEW, TRANS‐
1017 LATE_UNSIGNED, TRANSLATE_ALL
1018
1019 :ALL
1020 All of the above exportable items.
1021
1023 1. Blocking SNMPv1 get-request for sysUpTime
1024
1025 This example gets the sysUpTime from a remote host.
1026
1027 #! /usr/local/bin/perl
1028
1029 use strict;
1030
1031 use Net::SNMP;
1032
1033 my ($session, $error) = Net::SNMP->session(
1034 -hostname => shift ⎪⎪ 'localhost',
1035 -community => shift ⎪⎪ 'public',
1036 -port => shift ⎪⎪ 161
1037 );
1038
1039 if (!defined($session)) {
1040 printf("ERROR: %s.\n", $error);
1041 exit 1;
1042 }
1043
1044 my $sysUpTime = '1.3.6.1.2.1.1.3.0';
1045
1046 my $result = $session->get_request(
1047 -varbindlist => [$sysUpTime]
1048 );
1049
1050 if (!defined($result)) {
1051 printf("ERROR: %s.\n", $session->error);
1052 $session->close;
1053 exit 1;
1054 }
1055
1056 printf("sysUpTime for host '%s' is %s\n",
1057 $session->hostname, $result->{$sysUpTime}
1058 );
1059
1060 $session->close;
1061
1062 exit 0;
1063
1064 2. Blocking SNMPv3 set-request of sysContact
1065
1066 This example sets the sysContact information on the remote host to
1067 "Help Desk x911". The named arguments passed to the "session()" con‐
1068 structor are for the demonstration of syntax only. These parameters
1069 will need to be set according to the SNMPv3 parameters of the remote
1070 host used by the script.
1071
1072 #! /usr/local/bin/perl
1073
1074 use strict;
1075
1076 use Net::SNMP;
1077
1078 my ($session, $error) = Net::SNMP->session(
1079 -hostname => 'myv3host.company.com',
1080 -version => 'snmpv3',
1081 -username => 'myv3Username',
1082 -authkey => '0x05c7fbde31916f64da4d5b77156bdfa7',
1083 -authprotocol => 'md5',
1084 -privkey => '0x93725fd3a02a48ce02df4e065a1c1746'
1085 );
1086
1087 if (!defined($session)) {
1088 printf("ERROR: %s.\n", $error);
1089 exit 1;
1090 }
1091
1092 my $sysContact = '1.3.6.1.2.1.1.4.0';
1093
1094 my $result = $session->set_request(
1095 -varbindlist => [$sysContact, OCTET_STRING, 'Help Desk x911']
1096 );
1097
1098 if (!defined($result)) {
1099 printf("ERROR: %s.\n", $session->error);
1100 $session->close;
1101 exit 1;
1102 }
1103
1104 printf("sysContact for host '%s' set to '%s'\n",
1105 $session->hostname, $result->{$sysContact}
1106 );
1107
1108 $session->close;
1109
1110 exit 0;
1111
1112 3. Non-blocking SNMPv2c get-bulk-request for ifTable
1113
1114 This example gets the contents of the ifTable by sending get-bulk-
1115 requests until the responses are no longer part of the ifTable. The
1116 ifTable can also be retrieved using the "get_table()" method.
1117
1118 #! /usr/local/bin/perl
1119
1120 use strict;
1121
1122 use Net::SNMP qw(:snmp);
1123
1124 my ($session, $error) = Net::SNMP->session(
1125 -version => 'snmpv2c',
1126 -nonblocking => 1,
1127 -hostname => shift ⎪⎪ 'localhost',
1128 -community => shift ⎪⎪ 'public',
1129 -port => shift ⎪⎪ 161
1130 );
1131
1132 if (!defined($session)) {
1133 printf("ERROR: %s.\n", $error);
1134 exit 1;
1135 }
1136
1137 my $ifTable = '1.3.6.1.2.1.2.2';
1138
1139 my $result = $session->get_bulk_request(
1140 -callback => [\&table_cb, {}],
1141 -maxrepetitions => 10,
1142 -varbindlist => [$ifTable]
1143 );
1144
1145 if (!defined($result)) {
1146 printf("ERROR: %s.\n", $session->error);
1147 $session->close;
1148 exit 1;
1149 }
1150
1151 snmp_dispatcher();
1152
1153 $session->close;
1154
1155 exit 0;
1156
1157 sub table_cb
1158 {
1159 my ($session, $table) = @_;
1160
1161 if (!defined($session->var_bind_list)) {
1162
1163 printf("ERROR: %s\n", $session->error);
1164
1165 } else {
1166
1167 # Loop through each of the OIDs in the response and assign
1168 # the key/value pairs to the anonymous hash that is passed
1169 # to the callback. Make sure that we are still in the table
1170 # before assigning the key/values.
1171
1172 my $next;
1173
1174 foreach my $oid (oid_lex_sort(keys(%{$session->var_bind_list}))) {
1175 if (!oid_base_match($ifTable, $oid)) {
1176 $next = undef;
1177 last;
1178 }
1179 $next = $oid;
1180 $table->{$oid} = $session->var_bind_list->{$oid};
1181 }
1182
1183 # If $next is defined we need to send another request
1184 # to get more of the table.
1185
1186 if (defined($next)) {
1187
1188 $result = $session->get_bulk_request(
1189 -callback => [\&table_cb, $table],
1190 -maxrepetitions => 10,
1191 -varbindlist => [$next]
1192 );
1193
1194 if (!defined($result)) {
1195 printf("ERROR: %s\n", $session->error);
1196 }
1197
1198 } else {
1199
1200 # We are no longer in the table, so print the results.
1201
1202 foreach my $oid (oid_lex_sort(keys(%{$table}))) {
1203 printf("%s => %s\n", $oid, $table->{$oid});
1204 }
1205
1206 }
1207 }
1208 }
1209
1210 4. Non-blocking SNMPv1 get-request for sysUpTime on multiple hosts
1211
1212 This example polls several hosts for their sysUpTime using non-blocking
1213 objects and reports a warning if this value is less than the value from
1214 the last poll.
1215
1216 #! /usr/local/bin/perl
1217
1218 use strict;
1219
1220 use Net::SNMP qw(snmp_dispatcher ticks_to_time);
1221
1222 # List of hosts to poll
1223
1224 my @HOSTS = qw(1.1.1.1 1.1.1.2 localhost);
1225
1226 # Poll interval (in seconds). This value should be greater
1227 # than the number of retries plus one, times the timeout value.
1228
1229 my $INTERVAL = 60;
1230
1231 # Maximum number of polls, including the initial poll.
1232
1233 my $MAX_POLLS = 10;
1234
1235 my $sysUpTime = '1.3.6.1.2.1.1.3.0';
1236
1237 # Create a session for each host and queue the first get-request.
1238
1239 foreach my $host (@HOSTS) {
1240
1241 my ($session, $error) = Net::SNMP->session(
1242 -hostname => $host,
1243 -nonblocking => 0x1, # Create non-blocking objects
1244 -translate => [
1245 -timeticks => 0x0 # Turn off so sysUpTime is numeric
1246 ]
1247 );
1248 if (!defined($session)) {
1249 printf("ERROR: %s.\n", $error);
1250 exit 1;
1251 }
1252
1253 # Queue the get-request, passing references to variables that
1254 # will be used to store the last sysUpTime and the number of
1255 # polls that this session has performed.
1256
1257 my ($last_uptime, $num_polls) = (0, 0);
1258
1259 $session->get_request(
1260 -varbindlist => [$sysUpTime],
1261 -callback => [
1262 \&validate_sysUpTime_cb, \$last_uptime, \$num_polls
1263 ]
1264 );
1265
1266 }
1267
1268 # Define a reference point for all of the polls
1269 my $EPOC = time();
1270
1271 # Enter the event loop
1272 snmp_dispatcher();
1273
1274 exit 0;
1275
1276 sub validate_sysUpTime_cb
1277 {
1278 my ($session, $last_uptime, $num_polls) = @_;
1279
1280 if (!defined($session->var_bind_list)) {
1281
1282 printf("%-15s ERROR: %s\n", $session->hostname, $session->error);
1283
1284 } else {
1285
1286 # Validate the sysUpTime
1287
1288 my $uptime = $session->var_bind_list->{$sysUpTime};
1289
1290 if ($uptime < ${$last_uptime}) {
1291 printf("%-15s WARNING: %s is less than %s\n",
1292 $session->hostname,
1293 ticks_to_time($uptime),
1294 ticks_to_time(${$last_uptime})
1295 );
1296 } else {
1297 printf("%-15s Ok (%s)\n",
1298 $session->hostname, ticks_to_time($uptime)
1299 );
1300 }
1301
1302 # Store the new sysUpTime
1303 ${$last_uptime} = $uptime;
1304
1305 }
1306
1307 # Queue the next message if we have not reached $MAX_POLLS.
1308 # Since we do not provide a -callback argument, the same
1309 # callback and it's original arguments will be used.
1310
1311 if (++${$num_polls} < $MAX_POLLS) {
1312 my $delay = (($INTERVAL * ${$num_polls}) + $EPOC) - time();
1313 $session->get_request(
1314 -delay => ($delay >= 0) ? $delay : 0,
1315 -varbindlist => [$sysUpTime]
1316 );
1317 }
1318
1319 $session->error_status;
1320 }
1321
1323 · The Net::SNMP module uses syntax that is not supported in versions
1324 of Perl earlier than v5.6.0.
1325
1326 · The non-core modules Crypt::DES, Digest::MD5, Digest::SHA1, and
1327 Digest::HMAC are required to support SNMPv3.
1328
1329 · In order to support the AES Cipher Algorithm as a SNMPv3 privacy
1330 protocol, the non-core module Crypt::Rijndael is needed.
1331
1332 · To use UDP/IPv6 or TCP/IPv6 as a Transport Domain, the non-core
1333 module Socket6 is needed.
1334
1336 David M. Town <dtown@cpan.org>
1337
1339 The original concept for this module was based on SNMP_Session.pm writ‐
1340 ten by Simon Leinen <simon@switch.ch>.
1341
1342 The Abstract Syntax Notation One (ASN.1) encode and decode methods were
1343 originally derived by example from the CMU SNMP package whose copyright
1344 follows: Copyright (c) 1988, 1989, 1991, 1992 by Carnegie Mellon Uni‐
1345 versity. All rights reserved.
1346
1348 Copyright (c) 1998-2005 David M. Town. All rights reserved. This pro‐
1349 gram is free software; you may redistribute it and/or modify it under
1350 the same terms as Perl itself.
1351
1352
1353
1354perl v5.8.8 2005-10-20 Net::SNMP(3)