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
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
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
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 <http://www.snmp.com/eso/draft-reeder-
332 snmpv3-usm-3desede-00.txt>. The Triple-DES encryption protocol
333 can be selected using the -privprotocol argument with the
334 string '3des' or '3desede'.
335
336 close() - clear the Transport Domain associated with the object
337 $session->close();
338
339 This method clears the Transport Domain and any errors associated with
340 the object. Once closed, the Net::SNMP object can no longer be used to
341 send or receive SNMP messages.
342
343 snmp_dispatcher() - enter the non-blocking object event loop
344 $session->snmp_dispatcher();
345
346 This method enters the event loop associated with non-blocking
347 Net::SNMP objects. The method exits when all queued SNMP messages have
348 received a response or have timed out at the Transport Layer. This
349 method is also exported as the stand alone function "snmp_dispatcher()"
350 by default (see "EXPORTS").
351
352 get_request() - send a SNMP get-request to the remote agent
353 $result = $session->get_request(
354 [-callback => sub {},] # non-blocking
355 [-delay => $seconds,] # non-blocking
356 [-contextengineid => $engine_id,] # v3
357 [-contextname => $name,] # v3
358 -varbindlist => \@oids,
359 );
360
361 This method performs a SNMP get-request query to gather data from the
362 remote agent on the host associated with the Net::SNMP object. The
363 message is built using the list of OBJECT IDENTIFIERs in dotted
364 notation passed to the method as an array reference using the
365 -varbindlist argument. Each OBJECT IDENTIFIER is placed into a single
366 SNMP GetRequest-PDU in the same order that it held in the original
367 list.
368
369 A reference to a hash is returned in blocking mode which contains the
370 contents of the VarBindList. In non-blocking mode, a true value is
371 returned when no error has occurred. In either mode, the undefined
372 value is returned when an error has occurred. The "error()" method may
373 be used to determine the cause of the failure.
374
375 get_next_request() - send a SNMP get-next-request to the remote agent
376 $result = $session->get_next_request(
377 [-callback => sub {},] # non-blocking
378 [-delay => $seconds,] # non-blocking
379 [-contextengineid => $engine_id,] # v3
380 [-contextname => $name,] # v3
381 -varbindlist => \@oids,
382 );
383
384 This method performs a SNMP get-next-request query to gather data from
385 the remote agent on the host associated with the Net::SNMP object. The
386 message is built using the list of OBJECT IDENTIFIERs in dotted
387 notation passed to the method as an array reference using the
388 -varbindlist argument. Each OBJECT IDENTIFER is placed into a single
389 SNMP GetNextRequest-PDU in the same order that it held in the original
390 list.
391
392 A reference to a hash is returned in blocking mode which contains the
393 contents of the VarBindList. In non-blocking mode, a true value is
394 returned when no error has occurred. In either mode, the undefined
395 value is returned when an error has occurred. The "error()" method may
396 be used to determine the cause of the failure.
397
398 set_request() - send a SNMP set-request to the remote agent
399 $result = $session->set_request(
400 [-callback => sub {},] # non-blocking
401 [-delay => $seconds,] # non-blocking
402 [-contextengineid => $engine_id,] # v3
403 [-contextname => $name,] # v3
404 -varbindlist => \@oid_value,
405 );
406
407 This method is used to modify data on the remote agent that is
408 associated with the Net::SNMP object using a SNMP set-request. The
409 message is built using a list of values consisting of groups of an
410 OBJECT IDENTIFIER, an object type, and the actual value to be set.
411 This list is passed to the method as an array reference using the
412 -varbindlist argument. The OBJECT IDENTIFIERs in each trio are to be
413 in dotted notation. The object type is an octet corresponding to the
414 ASN.1 type of value that is to be set. Each of the supported ASN.1
415 types have been defined and are exported by the package by default (see
416 "EXPORTS").
417
418 A reference to a hash is returned in blocking mode which contains the
419 contents of the VarBindList. In non-blocking mode, a true value is
420 returned when no error has occurred. In either mode, the undefined
421 value is returned when an error has occurred. The "error()" method may
422 be used to determine the cause of the failure.
423
424 trap() - send a SNMP trap to the remote manager
425 $result = $session->trap(
426 [-delay => $seconds,] # non-blocking
427 [-enterprise => $oid,]
428 [-agentaddr => $ipaddress,]
429 [-generictrap => $generic,]
430 [-specifictrap => $specific,]
431 [-timestamp => $timeticks,]
432 -varbindlist => \@oid_value,
433 );
434
435 This method sends a SNMP trap to the remote manager associated with the
436 Net::SNMP object. All arguments are optional and will be given the
437 following defaults in the absence of a corresponding named argument:
438
439 · The default value for the trap -enterprise is "1.3.6.1.4.1", which
440 corresponds to "iso.org.dod.internet.private.enterprises". The
441 enterprise value is expected to be an OBJECT IDENTIFER in dotted
442 notation.
443
444 · When the Transport Domain is UDP/IPv4 or TCP/IPv4, the default
445 value for the trap -agentaddr is the IP address associated with the
446 interface on which the trap will be transmitted. For other
447 Transport Domains the -agentaddr is defaulted to "0.0.0.0". When
448 specified, the agent-addr is expected to be an IpAddress in dotted
449 notation.
450
451 · The default value for the -generictrap type is 6 which corresponds
452 to "enterpriseSpecific". The generic-trap types are defined and
453 can be exported upon request (see "EXPORTS").
454
455 · The default value for the -specifictrap type is 0. No pre-defined
456 values are available for specific-trap types.
457
458 · The default value for the trap -timestamp is the "uptime" of the
459 script. The "uptime" of the script is the number of hundredths of
460 seconds that have elapsed since the script began running. The
461 time-stamp is expected to be a TimeTicks number in hundredths of
462 seconds.
463
464 · The default value for the trap -varbindlist is an empty array
465 reference. The variable-bindings are expected to be in an array
466 format consisting of groups of an OBJECT IDENTIFIER, an object
467 type, and the actual value of the object. This is identical to the
468 list expected by the "set_request()" method. The OBJECT
469 IDENTIFIERs in each trio are to be in dotted notation. The object
470 type is an octet corresponding to the ASN.1 type for the value.
471 Each of the supported types have been defined and are exported by
472 default (see "EXPORTS").
473
474 A true value is returned when the method is successful. The undefined
475 value is returned when a failure has occurred. The "error()" method
476 can be used to determine the cause of the failure. Since there are no
477 acknowledgements for Trap-PDUs, there is no way to determine if the
478 remote host actually received the trap.
479
480 NOTE: When the object is in non-blocking mode, the trap is not sent
481 until the event loop is entered and no callback is ever executed.
482
483 NOTE: This method can only be used when the version of the object is
484 set to SNMPv1.
485
486 get_bulk_request() - send a SNMP get-bulk-request to the remote agent
487 $result = $session->get_bulk_request(
488 [-callback => sub {},] # non-blocking
489 [-delay => $seconds,] # non-blocking
490 [-contextengineid => $engine_id,] # v3
491 [-contextname => $name,] # v3
492 [-nonrepeaters => $non_reps,]
493 [-maxrepetitions => $max_reps,]
494 -varbindlist => \@oids,
495 );
496
497 This method performs a SNMP get-bulk-request query to gather data from
498 the remote agent on the host associated with the Net::SNMP object. All
499 arguments are optional except -varbindlist and will be given the
500 following defaults in the absence of a corresponding named argument:
501
502 · The default value for the get-bulk-request -nonrepeaters is 0. The
503 non-repeaters value specifies the number of variables in the
504 variable-bindings list for which a single successor is to be
505 returned.
506
507 · The default value for the get-bulk-request -maxrepetitions is 0.
508 The max-repetitions value specifies the number of successors to be
509 returned for the remaining variables in the variable-bindings list.
510
511 · The -varbindlist argument expects an array reference consisting of
512 a list of OBJECT IDENTIFIERs in dotted notation. Each OBJECT
513 IDENTIFER is placed into a single SNMP GetBulkRequest-PDU in the
514 same order that it held in the original list.
515
516 A reference to a hash is returned in blocking mode which contains the
517 contents of the VarBindList. In non-blocking mode, a true value is
518 returned when no error has occurred. In either mode, the undefined
519 value is returned when an error has occurred. The "error()" method may
520 be used to determine the cause of the failure.
521
522 NOTE: This method can only be used when the version of the object is
523 set to SNMPv2c or SNMPv3.
524
525 inform_request() - send a SNMP inform-request to the remote manager
526 $result = $session->inform_request(
527 [-callback => sub {},] # non-blocking
528 [-delay => $seconds,] # non-blocking
529 [-contextengineid => $engine_id,] # v3
530 [-contextname => $name,] # v3
531 -varbindlist => \@oid_value,
532 );
533
534 This method is used to provide management information to the remote
535 manager associated with the Net::SNMP object using an inform-request.
536 The message is built using a list of values consisting of groups of an
537 OBJECT IDENTIFIER, an object type, and the actual value to be
538 identified. This list is passed to the method as an array reference
539 using the -varbindlist argument. The OBJECT IDENTIFIERs in each trio
540 are to be in dotted notation. The object type is an octet
541 corresponding to the ASN.1 type of value that is to be identified.
542 Each of the supported ASN.1 types have been defined and are exported by
543 the package by default (see "EXPORTS").
544
545 The first two variable-bindings fields in the inform-request are
546 specified by SNMPv2 and should be:
547
548 · sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
549
550 · snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
551
552 A reference to a hash is returned in blocking mode which contains the
553 contents of the VarBindList. In non-blocking mode, a true value is
554 returned when no error has occurred. In either mode, the undefined
555 value is returned when an error has occurred. The "error()" method may
556 be used to determine the cause of the failure.
557
558 NOTE: This method can only be used when the version of the object is
559 set to SNMPv2c or SNMPv3.
560
561 snmpv2_trap() - send a SNMP snmpV2-trap to the remote manager
562 $result = $session->snmpv2_trap(
563 [-delay => $seconds,] # non-blocking
564 -varbindlist => \@oid_value,
565 );
566
567 This method sends a snmpV2-trap to the remote manager associated with
568 the Net::SNMP object. The message is built using a list of values
569 consisting of groups of an OBJECT IDENTIFIER, an object type, and the
570 actual value to be identified. This list is passed to the method as an
571 array reference using the -varbindlist argument. The OBJECT
572 IDENTIFIERs in each trio are to be in dotted notation. The object type
573 is an octet corresponding to the ASN.1 type of value that is to be
574 identified. Each of the supported ASN.1 types have been defined and
575 are exported by the package by default (see "EXPORTS").
576
577 The first two variable-bindings fields in the snmpV2-trap are specified
578 by SNMPv2 and should be:
579
580 · sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks)
581
582 · snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid)
583
584 A true value is returned when the method is successful. The undefined
585 value is returned when a failure has occurred. The "error()" method
586 can be used to determine the cause of the failure. Since there are no
587 acknowledgements for SNMPv2-Trap-PDUs, there is no way to determine if
588 the remote host actually received the snmpV2-trap.
589
590 NOTE: When the object is in non-blocking mode, the snmpV2-trap is not
591 sent until the event loop is entered and no callback is ever executed.
592
593 NOTE: This method can only be used when the version of the object is
594 set to SNMPv2c. SNMPv2-Trap-PDUs are supported by SNMPv3, but require
595 the sender of the message to be an authoritative SNMP engine which is
596 not currently supported by the Net::SNMP module.
597
598 get_table() - retrieve a table from the remote agent
599 $result = $session->get_table(
600 [-callback => sub {},] # non-blocking
601 [-delay => $seconds,] # non-blocking
602 [-contextengineid => $engine_id,] # v3
603 [-contextname => $name,] # v3
604 -baseoid => $oid,
605 [-maxrepetitions => $max_reps,] # v2c/v3
606 );
607
608 This method performs repeated SNMP get-next-request or get-bulk-request
609 (when using SNMPv2c or SNMPv3) queries to gather data from the remote
610 agent on the host associated with the Net::SNMP object. The first
611 message sent is built using the OBJECT IDENTIFIER in dotted notation
612 passed to the method by the -baseoid argument. Repeated SNMP requests
613 are issued until the OBJECT IDENTIFIER in the response is no longer a
614 child of the base OBJECT IDENTIFIER.
615
616 The -maxrepetitions argument can be used to specify the max-repetitions
617 value that is passed to the get-bulk-requests when using SNMPv2c or
618 SNMPv3. If this argument is not present, a value is calculated based
619 on the maximum message size for the Net::SNMP object. If the value is
620 set to 1 or less, get-next-requests will be used for the queries
621 instead of get-bulk-requests.
622
623 A reference to a hash is returned in blocking mode which contains the
624 contents of the VarBindList. In non-blocking mode, a true value is
625 returned when no error has occurred. In either mode, the undefined
626 value is returned when an error has occurred. The "error()" method may
627 be used to determine the cause of the failure.
628
629 WARNING: Results from this method can become very large if the base
630 OBJECT IDENTIFIER is close to the root of the SNMP MIB tree.
631
632 get_entries() - retrieve table entries from the remote agent
633 $result = $session->get_entries(
634 [-callback => sub {},] # non-blocking
635 [-delay => $seconds,] # non-blocking
636 [-contextengineid => $engine_id,] # v3
637 [-contextname => $name,] # v3
638 -columns => \@columns,
639 [-startindex => $start,]
640 [-endindex => $end,]
641 [-maxrepetitions => $max_reps,] # v2c/v3
642 );
643
644 This method performs repeated SNMP get-next-request or get-bulk-request
645 (when using SNMPv2c or SNMPv3) queries to gather data from the remote
646 agent on the host associated with the Net::SNMP object. Each message
647 specifically requests data for each OBJECT IDENTIFIER specified in the
648 -columns array. The OBJECT IDENTIFIERs must correspond to column
649 entries for a conceptual row in a table. They may however be columns
650 in different tables as long as each table is indexed the same way. The
651 optional -startindex and -endindex arguments may be specified to limit
652 the query to specific rows in the table(s).
653
654 The -startindex can be specified as a single decimal value or in dotted
655 notation if the index associated with the entry so requires. If the
656 -startindex is specified, it will be include as part of the query
657 results. If no -startindex is specified, the first request message
658 will be sent without an index. To insure that the -startindex is
659 included, the last sub-identifier in the index is decremented by one.
660 If the last sub-identifier has a value of zero, the sub-identifier is
661 removed from the index.
662
663 The optional -endindex argument can be specified as a single decimal
664 value or in dotted notation. If the -endindex is specified, it will be
665 included as part of the query results. If no -endindex is specified,
666 repeated SNMP requests are issued until the response no longer returns
667 entries matching any of the columns specified in the -columns array.
668
669 The -maxrepetitions argument can be used to specify the max-repetitions
670 value that is passed to the get-bulk-requests when using SNMPv2c or
671 SNMPv3. If this argument is not present, a value is calculated based
672 on the maximum message size of the object and the number of columns
673 specified in the -columns array. If the value is set to 1 or less,
674 get-next-requests will be used for the queries instead of get-bulk-
675 requests.
676
677 A reference to a hash is returned in blocking mode which contains the
678 contents of the VarBindList. In non-blocking mode, a true value is
679 returned when no error has occurred. In either mode, the undefined
680 value is returned when an error has occurred. The "error()" method may
681 be used to determine the cause of the failure.
682
683 version() - get the SNMP version from the object
684 $rfc_version = $session->version();
685
686 This method returns the current value for the SNMP version associated
687 with the object. The returned value is the corresponding version
688 number defined by the RFCs for the protocol version field (i.e. SNMPv1
689 == 0, SNMPv2c == 1, and SNMPv3 == 3). The RFC versions are defined as
690 constant by the module and can be exported by request (see "EXPORTS").
691
692 error() - get the current error message from the object
693 $error_message = $session->error();
694
695 This method returns a text string explaining the reason for the last
696 error. An empty string is returned if no error has occurred.
697
698 hostname() - get the hostname associated with the object
699 $hostname = $session->hostname();
700
701 This method returns the parsed hostname string that is associated with
702 the object. Any port information and formatting that can be included
703 with the corresponding "session()" constructor argument will be
704 stripped and not included as part of the returned string.
705
706 error_status() - get the current SNMP error-status from the object
707 $error_status = $session->error_status();
708
709 This method returns the numeric value of the error-status contained in
710 the last SNMP message received by the object.
711
712 error_index() - get the current SNMP error-index from the object
713 $error_index = $session->error_index();
714
715 This method returns the numeric value of the error-index contained in
716 the last SNMP message received by the object.
717
718 var_bind_list() - get the hash reference for the VarBindList values
719 $values = $session->var_bind_list();
720
721 This method returns a hash reference created using the ObjectName and
722 the ObjectSyntax pairs in the VarBindList of the last SNMP message
723 received by the object. The keys of the hash consist of the OBJECT
724 IDENTIFIERs in dotted notation corresponding to each ObjectName in the
725 VarBindList. If any of the OBJECT IDENTIFIERs passed to the request
726 method began with a leading dot, all of the OBJECT IDENTIFIER hash keys
727 will be prefixed with a leading dot. If duplicate OBJECT IDENTIFIERs
728 are present in the VarBindList they will be padded with spaces to make
729 them an unique hash key. The value of each hash entry is set equal to
730 the value of the corresponding ObjectSyntax. The undefined value is
731 returned if there has been a failure.
732
733 var_bind_names() - get the array of the ObjectNames in the VarBindList
734 @names = $session->var_bind_names();
735
736 This method returns an array containing the OBJECT IDENTIFIERs
737 corresponding to the ObjectNames in the VarBindList in the order that
738 they were received in the last SNMP message. The entries in the array
739 will map directly to the keys in the hash reference returned by the
740 methods that perform SNMP message exchanges and by the
741 "var_bind_list()" and "var_bind_types()" methods. The array returned
742 for the convenience methods "get_table()" and "get_entries()" will be
743 in lexicographical order. An empty array is returned if there has been
744 a failure.
745
746 var_bind_types() - get the hash reference for the VarBindList ASN.1 types
747 $types = $session->var_bind_types();
748
749 This method returns a hash reference created using the ObjectName and
750 the ASN.1 type of the ObjectSyntax in the VarBindList of the last SNMP
751 message received by the object. The keys of the hash consist of the
752 OBJECT IDENTIFIERs in dotted notation corresponding to each ObjectName
753 in the VarBindList. The value of each hash entry is set equal to the
754 ASN.1 type of the corresponding ObjectSyntax. Constants for the
755 supported ASN.1 types have been defined and are exported by the package
756 by default (see "EXPORTS"). The undefined value is returned if there
757 has been a failure.
758
759 timeout() - set or get the current timeout period for the object
760 $seconds = $session->timeout([$seconds]);
761
762 This method returns the current value for the Transport Layer timeout
763 for the Net::SNMP object. This value is the number of seconds that the
764 object will wait for a response from the agent on the remote host. The
765 default timeout is 5.0 seconds.
766
767 If a parameter is specified, the timeout for the object is set to the
768 provided value if it falls within the range 1.0 to 60.0 seconds. The
769 undefined value is returned upon an error and the "error()" method may
770 be used to determine the cause.
771
772 retries() - set or get the current retry count for the object
773 $count = $session->retries([$count]);
774
775 This method returns the current value for the number of times to retry
776 sending a SNMP message to the remote host. The default number of
777 retries is 1.
778
779 If a parameter is specified, the number of retries for the object is
780 set to the provided value if it falls within the range 0 to 20. The
781 undefined value is returned upon an error and the "error()" method may
782 be used to determine the cause.
783
784 max_msg_size() - set or get the current maxMsgSize for the object
785 $octets = $session->max_msg_size([$octets]);
786
787 This method returns the current value for the maximum message size
788 (maxMsgSize) for the Net::SNMP object. This value is the largest
789 message size in octets that can be prepared or processed by the object.
790 The default maxMsgSize is 1472 octets for UDP/IPv4, 1452 octets for
791 UDP/IPv6, 1460 octets for TCP/IPv4, and 1440 octets for TCP/IPv6.
792
793 If a parameter is specified, the maxMsgSize is set to the provided
794 value if it falls within the range 484 to 65535 octets. The undefined
795 value is returned upon an error and the "error()" method may be used to
796 determine the cause.
797
798 NOTE: When using SNMPv3, the maxMsgSize is actually contained in the
799 SNMP message (as msgMaxSize). If the value received from a remote
800 device is less than the current maxMsgSize, the size is automatically
801 adjusted to be the lower value.
802
803 translate() - enable or disable the translation mode for the object
804 $mask = $session->translate([
805 $mode |
806 [ # Perl anonymous ARRAY reference
807 ['-all' => $mode0,]
808 ['-octetstring' => $mode1,]
809 ['-null' => $mode2,]
810 ['-timeticks' => $mode3,]
811 ['-opaque' => $mode4,]
812 ['-nosuchobject' => $mode5,]
813 ['-nosuchinstance' => $mode6,]
814 ['-endofmibview' => $mode7,]
815 ['-unsigned' => $mode8]
816 ]
817 ]);
818
819 When the object decodes the GetResponse-PDU that is returned in
820 response to a SNMP message, certain values are translated into a more
821 "human readable" form. By default the following translations occur:
822
823 · OCTET STRINGs and Opaques containing any octet which is not part of
824 the character set defined as a DisplayString in RFC 2679 are
825 converted into a hexadecimal representation prefixed with "0x".
826 The control codes NUL(0x00), BEL(0x07), BS(0x08), HT(0x09),
827 LF(0x0A), VT(0x0b), FF(0x0C), and CR(0x0D) are part of the
828 character set and will not trigger translation. The sequence 'CR
829 x' for any x other than LF or NUL is illegal and will trigger
830 translation.
831
832 · TimeTicks integer values are converted to a time format.
833
834 · NULL values return the string "NULL" instead of an empty string.
835
836 · noSuchObject exception values return the string "noSuchObject"
837 instead of an empty string.
838
839 · noSuchInstance exception values return the string "noSuchInstance"
840 instead of an empty string.
841
842 · endOfMibView exception values return the string "endOfMibView"
843 instead of an empty string.
844
845 · Counter64, Counter, Gauge, and TimeTick values that have been
846 incorrectly encoded as signed negative values are returned as
847 unsigned values.
848
849 The "translate()" method can be invoked with two different types of
850 arguments.
851
852 If the argument passed is any Perl variable type except an array
853 reference, the translation mode for all ASN.1 types is set to either
854 enabled or disabled, depending on the value of the passed parameter.
855 Any value that Perl would treat as a true value will set the mode to be
856 enabled for all types, while a false value will disable translation for
857 all types.
858
859 A reference to an array can be passed to the "translate()" method in
860 order to define the translation mode on a per ASN.1 type basis. The
861 array is expected to contain a list of named argument pairs for each
862 ASN.1 type that is to be modified. The arguments in the list are
863 applied in the order that they are passed in via the array. Arguments
864 at the end of the list supercede those passed earlier in the list. The
865 argument "-all" can be used to specify that the mode is to apply to all
866 ASN.1 types. Only the arguments for the ASN.1 types that are to be
867 modified need to be included in the list.
868
869 The "translate()" method returns a bit mask indicating which ASN.1
870 types are to be translated. Definitions of the bit to ASN.1 type
871 mappings can be exported using the :translate tag (see "EXPORTS"). The
872 undefined value is returned upon an error and the "error()" method may
873 be used to determine the cause.
874
875 debug() - set or get the debug mode for the module
876 $mask = $session->debug([$mask]);
877
878 This method is used to enable or disable debugging for the Net::SNMP
879 module. Debugging can be enabled on a per component level as defined
880 by a bit mask passed to the "debug()" method. The bit mask is broken
881 up as follows:
882
883 · 0x02 - Message or PDU encoding and decoding
884
885 · 0x04 - Transport Layer
886
887 · 0x08 - Dispatcher
888
889 · 0x10 - Message Processing
890
891 · 0x20 - Security
892
893 Symbols representing these bit mask values are defined by the module
894 and can be exported using the :debug tag (see "EXPORTS"). If a non-
895 numeric value is passed to the "debug()" method, it is evaluated in
896 boolean context. Debugging for all of the components is then enabled
897 or disabled based on the resulting truth value.
898
899 The current debugging mask is returned by the method. Debugging can
900 also be enabled using the stand alone function "snmp_debug()". This
901 function can be exported by request (see "EXPORTS").
902
904 oid_base_match() - determine if an OID has a specified OID base
905 $value = oid_base_match($base_oid, $oid);
906
907 This function takes two OBJECT IDENTIFIERs in dotted notation and
908 returns a true value (i.e. 0x1) if the second OBJECT IDENTIFIER is
909 equal to or is a child of the first OBJECT IDENTIFIER in the SNMP
910 Management Information Base (MIB). This function can be used in
911 conjunction with the "get-next-request()" or "get-bulk-request()"
912 methods to determine when a OBJECT IDENTIFIER in the GetResponse-PDU is
913 no longer in the desired MIB tree branch.
914
915 oid_lex_cmp() - compare two OBJECT IDENTIFIERs lexicographically
916 $cmp = oid_lex_cmp($oid1, $oid2);
917
918 This function takes two OBJECT IDENTIFIERs in dotted notation and
919 returns one of the values 1, 0, -1 if $oid1 is respectively
920 lexicographically greater, equal, or less than $oid2.
921
922 oid_lex_sort() - sort a list of OBJECT IDENTIFIERs lexicographically
923 @sorted_oids = oid_lex_sort(@oids);
924
925 This function takes a list of OBJECT IDENTIFIERs in dotted notation and
926 returns the listed sorted in lexicographical order.
927
928 snmp_type_ntop() - convert an ASN.1 type to presentation format
929 $text = snmp_type_ntop($type);
930
931 This function takes an ASN.1 type octet and returns a text string
932 suitable for presentation. Some ASN.1 type definitions map to the same
933 octet value when encoded. This method cannot distinguish between these
934 multiple mappings and the most basic type name will be returned.
935
936 ticks_to_time() - convert TimeTicks to formatted time
937 $time = ticks_to_time($timeticks);
938
939 This function takes an ASN.1 TimeTicks value and returns a string
940 representing the time defined by the value. The TimeTicks value is
941 expected to be a non-negative integer value representing the time in
942 hundredths of a second since some epoch. The returned string will
943 display the time in days, hours, and seconds format according to the
944 value of the TimeTicks argument.
945
947 The Net::SNMP module uses the Exporter module to export useful
948 constants and subroutines. These exportable symbols are defined below
949 and follow the rules and conventions of the Exporter module (see
950 Exporter).
951
952 Default
953 &snmp_dispatcher, INTEGER, INTEGER32, OCTET_STRING,
954 OBJECT_IDENTIFIER, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32,
955 UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT,
956 NOSUCHINSTANCE, ENDOFMIBVIEW
957
958 Exportable
959 &snmp_debug, &snmp_dispatcher, &snmp_type_ntop, &oid_base_match,
960 &oid_lex_cmp, &oid_lex_sort,&ticks_to_time, INTEGER, INTEGER32,
961 OCTET_STRING, NULL, OBJECT_IDENTIFIER, SEQUENCE, IPADDRESS,
962 COUNTER, COUNTER32, GAUGE, GAUGE32, UNSIGNED32, TIMETICKS, OPAQUE,
963 COUNTER64, NOSUCHOBJECT, NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST,
964 GET_NEXT_REQUEST, GET_RESPONSE, SET_REQUEST, TRAP,
965 GET_BULK_REQUEST, INFORM_REQUEST, SNMPV2_TRAP, REPORT, DEBUG_ALL,
966 DEBUG_NONE, DEBUG_MESSAGE, DEBUG_TRANSPORT,
967 DEBUG_DISPATCHER,DEBUG_PROCESSING, DEBUG_SECURITY, COLD_START,
968 WARM_START, LINK_DOWN, LINK_UP, AUTHENTICATION_FAILURE,
969 EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC, SNMP_VERSION_1,
970 SNMP_VERSION_2C, SNMP_VERSION_3, SNMP_PORT, SNMP_TRAP_PORT,
971 TRANSLATE_NONE,TRANSLATE_OCTET_STRING, TRANSLATE_NULL,
972 TRANSLATE_TIMETICKS, TRANSLATE_OPAQUE,TRANSLATE_NOSUCHOBJECT,
973 TRANSLATE_NOSUCHINSTANCE, TRANSLATE_ENDOFMIBVIEW,
974 TRANSLATE_UNSIGNED, TRANSLATE_ALL
975
976 Tags
977 :asn1
978 INTEGER, INTEGER32, OCTET_STRING, NULL, OBJECT_IDENTIFIER,
979 SEQUENCE, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32,
980 UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT,
981 NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST, GET_NEXT_REQUEST,
982 GET_RESPONSE, SET_REQUEST, TRAP, GET_BULK_REQUEST,
983 INFORM_REQUEST, SNMPV2_TRAP, REPORT
984
985 :debug
986 &snmp_debug, DEBUG_ALL, DEBUG_NONE, DEBUG_MESSAGE,
987 DEBUG_TRANSPORT, DEBUG_DISPATCHER, DEBUG_PROCESSING,
988 DEBUG_SECURITY
989
990 :generictrap
991 COLD_START, WARM_START, LINK_DOWN, LINK_UP,
992 AUTHENTICATION_FAILURE, EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC
993
994 :snmp
995 &snmp_debug, &snmp_dispatcher, &snmp_type_ntop,
996 &oid_base_match, &oid_lex_cmp, &oid_lex_sort, &ticks_to_time,
997 SNMP_VERSION_1, SNMP_VERSION_2C, SNMP_VERSION_3, SNMP_PORT,
998 SNMP_TRAP_PORT
999
1000 :translate
1001 TRANSLATE_NONE, TRANSLATE_OCTET_STRING, TRANSLATE_NULL,
1002 TRANSLATE_TIMETICKS, TRANSLATE_OPAQUE, TRANSLATE_NOSUCHOBJECT,
1003 TRANSLATE_NOSUCHINSTANCE, TRANSLATE_ENDOFMIBVIEW,
1004 TRANSLATE_UNSIGNED, TRANSLATE_ALL
1005
1006 :ALL
1007 All of the above exportable items.
1008
1010 1. Blocking SNMPv1 get-request for sysUpTime
1011 This example gets the sysUpTime from a remote host.
1012
1013 #! /usr/local/bin/perl
1014
1015 use strict;
1016 use warnings;
1017
1018 use Net::SNMP;
1019
1020 my $OID_sysUpTime = '1.3.6.1.2.1.1.3.0';
1021
1022 my ($session, $error) = Net::SNMP->session(
1023 -hostname => shift || 'localhost',
1024 -community => shift || 'public',
1025 );
1026
1027 if (!defined $session) {
1028 printf "ERROR: %s.\n", $error;
1029 exit 1;
1030 }
1031
1032 my $result = $session->get_request(-varbindlist => [ $OID_sysUpTime ],);
1033
1034 if (!defined $result) {
1035 printf "ERROR: %s.\n", $session->error();
1036 $session->close();
1037 exit 1;
1038 }
1039
1040 printf "The sysUpTime for host '%s' is %s.\n",
1041 $session->hostname(), $result->{$OID_sysUpTime};
1042
1043 $session->close();
1044
1045 exit 0;
1046
1047 2. Blocking SNMPv3 set-request of sysContact
1048 This example sets the sysContact information on the remote host to
1049 "Help Desk x911". The named arguments passed to the "session()"
1050 constructor are for the demonstration of syntax only. These parameters
1051 will need to be set according to the SNMPv3 parameters of the remote
1052 host. The "snmpkey" utility included with the distribution can be used
1053 to create the key values.
1054
1055 #! /usr/local/bin/perl
1056
1057 use strict;
1058 use warnings;
1059
1060 use Net::SNMP;
1061
1062 my $OID_sysContact = '1.3.6.1.2.1.1.4.0';
1063
1064 my ($session, $error) = Net::SNMP->session(
1065 -hostname => 'myv3host.example.com',
1066 -version => 'snmpv3',
1067 -username => 'myv3Username',
1068 -authprotocol => 'sha1',
1069 -authkey => '0x6695febc9288e36282235fc7151f128497b38f3f',
1070 -privprotocol => 'des',
1071 -privkey => '0x6695febc9288e36282235fc7151f1284',
1072 );
1073
1074 if (!defined $session) {
1075 printf "ERROR: %s.\n", $error;
1076 exit 1;
1077 }
1078
1079 my $result = $session->set_request(
1080 -varbindlist => [ $OID_sysContact, OCTET_STRING, 'Help Desk x911' ],
1081 );
1082
1083 if (!defined $result) {
1084 printf "ERROR: %s.\n", $session->error();
1085 $session->close();
1086 exit 1;
1087 }
1088
1089 printf "The sysContact for host '%s' was set to '%s'.\n",
1090 $session->hostname(), $result->{$OID_sysContact};
1091
1092 $session->close();
1093
1094 exit 0;
1095
1096 3. Non-blocking SNMPv2c get-bulk-request for ifTable
1097 This example gets the contents of the ifTable by sending get-bulk-
1098 requests until the responses are no longer part of the ifTable. The
1099 ifTable can also be retrieved using the "get_table()" method. The
1100 ifPhysAddress object in the table has a syntax of an OCTET STRING. By
1101 default, translation is enabled and non-printable OCTET STRINGs are
1102 translated into a hexadecimal format. Sometimes the OCTET STRING
1103 contains all printable characters and this produces unexpected output
1104 when it is not translated. The example turns off translation for OCTET
1105 STRINGs and specifically formats the output for the ifPhysAddress
1106 objects.
1107
1108 #! /usr/local/bin/perl
1109
1110 use strict;
1111 use warnings;
1112
1113 use Net::SNMP qw(:snmp);
1114
1115 my $OID_ifTable = '1.3.6.1.2.1.2.2';
1116 my $OID_ifPhysAddress = '1.3.6.1.2.1.2.2.1.6';
1117
1118 my ($session, $error) = Net::SNMP->session(
1119 -hostname => shift || 'localhost',
1120 -community => shift || 'public',
1121 -nonblocking => 1,
1122 -translate => [-octetstring => 0],
1123 -version => 'snmpv2c',
1124 );
1125
1126 if (!defined $session) {
1127 printf "ERROR: %s.\n", $error;
1128 exit 1;
1129 }
1130
1131 my %table; # Hash to store the results
1132
1133 my $result = $session->get_bulk_request(
1134 -varbindlist => [ $OID_ifTable ],
1135 -callback => [ \&table_callback, \%table ],
1136 -maxrepetitions => 10,
1137 );
1138
1139 if (!defined $result) {
1140 printf "ERROR: %s\n", $session->error();
1141 $session->close();
1142 exit 1;
1143 }
1144
1145 # Now initiate the SNMP message exchange.
1146
1147 snmp_dispatcher();
1148
1149 $session->close();
1150
1151 # Print the results, specifically formatting ifPhysAddress.
1152
1153 for my $oid (oid_lex_sort(keys %table)) {
1154 if (!oid_base_match($OID_ifPhysAddress, $oid)) {
1155 printf "%s = %s\n", $oid, $table{$oid};
1156 } else {
1157 printf "%s = %s\n", $oid, unpack 'H*', $table{$oid};
1158 }
1159 }
1160
1161 exit 0;
1162
1163 sub table_callback
1164 {
1165 my ($session, $table) = @_;
1166
1167 my $list = $session->var_bind_list();
1168
1169 if (!defined $list) {
1170 printf "ERROR: %s\n", $session->error();
1171 return;
1172 }
1173
1174 # Loop through each of the OIDs in the response and assign
1175 # the key/value pairs to the reference that was passed with
1176 # the callback. Make sure that we are still in the table
1177 # before assigning the key/values.
1178
1179 my @names = $session->var_bind_names();
1180 my $next = undef;
1181
1182 while (@names) {
1183 $next = shift @names;
1184 if (!oid_base_match($OID_ifTable, $next)) {
1185 return; # Table is done.
1186 }
1187 $table->{$next} = $list->{$next};
1188 }
1189
1190 # Table is not done, send another request, starting at the last
1191 # OBJECT IDENTIFIER in the response. No need to include the
1192 # calback argument, the same callback that was specified for the
1193 # original request will be used.
1194
1195 my $result = $session->get_bulk_request(
1196 -varbindlist => [ $next ],
1197 -maxrepetitions => 10,
1198 );
1199
1200 if (!defined $result) {
1201 printf "ERROR: %s.\n", $session->error();
1202 }
1203
1204 return;
1205 }
1206
1207 4. Non-blocking SNMPv1 get-request and set-request on multiple hosts
1208 This example first polls several hosts for their sysUpTime. If the
1209 poll of the host is successful, the sysContact and sysLocation
1210 information is set on the host. The sysContact information is
1211 hardcoded to "Help Desk x911" while the sysLocation information is
1212 passed as an argument to the callback.
1213
1214 #! /usr/local/bin/perl
1215
1216 use strict;
1217 use warnings;
1218
1219 use Net::SNMP;
1220
1221 my $OID_sysUpTime = '1.3.6.1.2.1.1.3.0';
1222 my $OID_sysContact = '1.3.6.1.2.1.1.4.0';
1223 my $OID_sysLocation = '1.3.6.1.2.1.1.6.0';
1224
1225 # Hash of hosts and location data.
1226
1227 my %host_data = (
1228 '10.1.1.2' => 'Building 1, Second Floor',
1229 '10.2.1.1' => 'Building 2, First Floor',
1230 'localhost' => 'Right here!',
1231 );
1232
1233 # Create a session for each host and queue a get-request for sysUpTime.
1234
1235 for my $host (keys %host_data) {
1236
1237 my ($session, $error) = Net::SNMP->session(
1238 -hostname => $host,
1239 -community => 'private',
1240 -nonblocking => 1,
1241 );
1242
1243 if (!defined $session) {
1244 printf "ERROR: Failed to create session for host '%s': %s.\n",
1245 $host, $error;
1246 next;
1247 }
1248
1249 my $result = $session->get_request(
1250 -varbindlist => [ $OID_sysUpTime ],
1251 -callback => [ \&get_callback, $host_data{$host} ],
1252 );
1253
1254 if (!defined $result) {
1255 printf "ERROR: Failed to queue get request for host '%s': %s.\n",
1256 $session->hostname(), $session->error();
1257 }
1258
1259 }
1260
1261 # Now initiate the SNMP message exchange.
1262
1263 snmp_dispatcher();
1264
1265 exit 0;
1266
1267 sub get_callback
1268 {
1269 my ($session, $location) = @_;
1270
1271 my $result = $session->var_bind_list();
1272
1273 if (!defined $result) {
1274 printf "ERROR: Get request failed for host '%s': %s.\n",
1275 $session->hostname(), $session->error();
1276 return;
1277 }
1278
1279 printf "The sysUpTime for host '%s' is %s.\n",
1280 $session->hostname(), $result->{$OID_sysUpTime};
1281
1282 # Now set the sysContact and sysLocation for the host.
1283
1284 $result = $session->set_request(
1285 -varbindlist =>
1286 [
1287 $OID_sysContact, OCTET_STRING, 'Help Desk x911',
1288 $OID_sysLocation, OCTET_STRING, $location,
1289 ],
1290 -callback => \&set_callback,
1291 );
1292
1293 if (!defined $result) {
1294 printf "ERROR: Failed to queue set request for host '%s': %s.\n",
1295 $session->hostname(), $session->error();
1296 }
1297
1298 return;
1299 }
1300
1301 sub set_callback
1302 {
1303 my ($session) = @_;
1304
1305 my $result = $session->var_bind_list();
1306
1307 if (defined $result) {
1308 printf "The sysContact for host '%s' was set to '%s'.\n",
1309 $session->hostname(), $result->{$OID_sysContact};
1310 printf "The sysLocation for host '%s' was set to '%s'.\n",
1311 $session->hostname(), $result->{$OID_sysLocation};
1312 } else {
1313 printf "ERROR: Set request failed for host '%s': %s.\n",
1314 $session->hostname(), $session->error();
1315 }
1316
1317 return;
1318 }
1319
1321 · The Net::SNMP module uses syntax that is not supported in versions
1322 of Perl earlier than v5.6.0.
1323
1324 · The non-core modules Crypt::DES, Digest::MD5, Digest::SHA1, and
1325 Digest::HMAC are required to support SNMPv3.
1326
1327 · In order to support the AES Cipher Algorithm as a SNMPv3 privacy
1328 protocol, the non-core module Crypt::Rijndael is needed.
1329
1330 · To use UDP/IPv6 or TCP/IPv6 as a Transport Domain, the non-core
1331 module Socket6 is needed.
1332
1334 David M. Town <dtown@cpan.org>
1335
1337 The original concept for this module was based on SNMP_Session.pm
1338 written by Simon Leinen <simon@switch.ch>.
1339
1340 The Abstract Syntax Notation One (ASN.1) encode and decode methods were
1341 originally derived by example from the CMU SNMP package whose copyright
1342 follows: Copyright (c) 1988, 1989, 1991, 1992 by Carnegie Mellon
1343 University. All rights reserved.
1344
1346 Copyright (c) 1998-2010 David M. Town. All rights reserved.
1347
1348 This program is free software; you may redistribute it and/or modify it
1349 under the same terms as the Perl 5 programming language system itself.
1350
1351
1352
1353perl v5.12.2 2010-09-10 Net::SNMP(3)