Net::SNMP(3)

NAME
Net::SNMP - Simple Network Management Protocol

SYNOPSIS
The module Net::SNMP implements an object oriented interface to the Simple Network Management Protocol. Perl applications can use the module to retrieve or update information on a remote host using the SNMP protocol. Net::SNMP is implemented completely in Perl, requires no compiling, and uses only standard Perl modules. Both SNMPv1 and SNMPv2c (Community-Based SNMPv2) are supported by the module. The Net::SNMP module assumes that the user has a basic understanding of the Simple Network Management Protocol and related network management concepts.

DESCRIPTION
The module Net::SNMP abstracts the intricate details of the Simple Network Management Protocol by providing a high level programming interface to the protocol. Each Net::SNMP object provides a one-to-one mapping between a Perl object and a remote SNMP agent or manager. Once an object is created, it can be used to perform all of the basic protocol exchange actions defined by SNMP.

A Net::SNMP object can be created such that it has either "blocking" or "non-blocking" properties. By default, the methods used to send SNMP messages do not return until the protocol exchange has completed successfully or a timeout period has expired. This behavior gives the object a "blocking" property because the flow of the code is stopped until the method returns.

The optional named argument "-nonblocking" can be passed to the object constructor with a true value to give the object "non-blocking" behavior. A method invoked by a non-blocking object queues the SNMP message and returns immediately allowing the flow of the code to continue. The queued SNMP messages are not sent until an event loop is entered by calling the "snmp_event_loop()" method. When the SNMP messages are sent, any response to the messages invokes the subroutine defined by the user when the message was originally queued. The event loop exits when all messages have been removed from the queue by either receiving a response or when the number of retries for the object has been exceeded.

  Blocking Objects
The default behavior of the methods associated with a Net::SNMP object is to block the code flow until the method completes. For methods that initiate a SNMP protocol exchange requiring a response, a hash reference containing the results of the query are returned. The undefined value is returned by all methods when a failure has occurred. The "error()" method can be used to determine the cause of the failure.

The hash reference returned by a SNMP protocol exchange points to a hash constructed from the VarBindList contained in the SNMP GetResponse-PDU. The hash is created using the ObjectName and the ObjectSyntax pairs in the VarBindList. The keys of the hash consist of the OBJECT IDENTIFIERs in dotted notation corresponding to each ObjectName in the VarBindList. The value of each hash entry is set equal to the value of the corresponding ObjectSyntax. This hash reference can also be retrieved using the "var_bind_list()" method.

  Non-blocking Objects
When a Net::SNMP object is created having non-blocking behavior, the invocation of a method associated with the object returns immediately, allowing the flow of the code to continue. When a method is invoked that would initiate a SNMP protocol exchange requiring a response, either a true value (i.e. 0x1) is returned immediately or the undefined value is returned if there was a failure. The "error()" method can be used to determine the cause of the failure.

Callback Argument
    Most methods associated with a non-blocking object have an optional named argument called "-callback". The -callback argument expects a reference to a subroutine or to an array whose first element must be a reference to a subroutine. The subroutine defined by the -callback option is executed when a response to a SNMP message is received, an error condition has occurred, or the number of retries for the message has been exceeded.

    When the -callback argument only contains a subroutine reference, the subroutine is evaluated passing a copy of the original Net::SNMP object as the only parameter. The copy of the object has all of the properties that the original object had when the message was queued, and will also contain the results of the SNMP protocol exchange. If the -callback argument was defined as an array reference, all elements in the array are passed to the subroutine after the copy of the Net::SNMP object. The first element, which is required to be a reference to a subroutine, is removed before the remaining arguments are passed to that subroutine.

    Once one method is invoked with the -callback argument, this argument stays with the object and is used by any further calls to methods using the -callback option if the argument is absent. The undefined value may be passed to the -callback argument to delete the callback subroutine.

    NOTE: The subroutine being passed with the -callback named argument should not cause blocking itself. This will cause all the actions in the event loop to be stopped, defeating the non-blocking property of the Net::SNMP module.

Delay Argument
    An optional argument -delay can also be passed to non-blocking objects. The -delay argument instructs the object to wait the number of seconds passed to the argument before excuting the method. The delay period starts when the event loop is entered. The -delay parameter is applied to all methods associated with the object once it is specified. The delay value must be set back to 0 seconds to disable the delay parameter.

The contents of the VarBindList contained in the SNMP GetResponse-PDU can be retrieved by calling the "var_bind_list()" method associated with the copy of the original object. The value returned by the "var_bind_list()" method is a hash reference created using the ObjectName and the ObjectSyntax pairs in the VarBindList. The keys of the hash consist of the OBJECT IDENTIFIERs in dotted notation corresponding to each ObjectName in the VarBindList. The value of each hash entry is set equal to the value of the corresponding ObjectSyntax. The undefined value is returned if there has been a failure and the "error()" method may be used to determine the reason.

METHODS
Most methods associated with a Net::SNMP object take different parameters based on the "blocking" or "non-blocking" property of the object. When named arguments are used with methods, two different styles are supported. All examples in this documentation use the dashed-option style:

       $object->method(-argument => $value);

However, the IO:: style is also allowed:

       $object->method(Argument => $value);

  session() - create a new Net::SNMP object
   ($session, $error) = Net::SNMP->session(
                           [-hostname    => $hostname,]
                           [-community   => $community,]
                           [-port        => $port,]
                           [-nonblocking => $nonblocking,]
                           [-version     => $version,]
                           [-timeout     => $seconds,]
                           [-retries     => $count,]
                           [-mtu         => $octets,]
                           [-translate   => $translate,]
                           [-debug       => $debug]
                        );

This is the constructor for Net::SNMP objects. In scalar context, a reference to a new Net::SNMP object is returned if the creation of the object is successful. In list context, a reference to a new Net::SNMP object and an empty error message string is returned. If a failure occurs, the object reference is returned as the undefined value. The error string may be used to determine the cause of the error.

The -hostname, -community, -port, and -nonblocking arguments are basic properties of a Net::SNMP object and cannot be changed after the object is created. All other arguments have methods that allow their values to be modified after the Net::SNMP object has been created. See the methods corresponding to these named arguments for their valid ranges and default values.

All arguments are optional and will take default values in the absence of a corresponding named argument.

•   The default value for the remote -hostname is "localhost". The hostname can either be a network hostname or the dotted IP address of the host.

•   The default value for the SNMP -community name is "public".

•   The default value for the destination UDP -port number is 161. This is the port on which hosts using default values expect to receive all SNMP messages except for traps. Port number 162 is the default port used by hosts expecting to receive SNMP traps.

•   The default value for the -nonblocking property is 0x0 (false).

  close() - clear the UDP socket reference, buffers, and errors
   $session->close;

This method clears the UDP socket reference, the errors, hash pointers, and buffers associated with the object. Once closed, the Net::SNMP object can no longer be used to send or received SNMP messages.

  snmp_event_loop() - enter the non-blocking object event loop
   $session->snmp_event_loop;

This method enters the event loop associated with non-blocking Net::SNMP objects. The method exits when all queued SNMP messages have been responded to or have timed out. This method is also exported as the stand alone function "snmp_event_loop()" by default (see "EXPORTS").

  get_request() - send a SNMP get-request to the remote agent
Blocking

   $response = $session->get_request(@oids);

Non-blocking

         $ok = $session->get_request(
                            [-callback   => sub {},]
                            [-delay      => $seconds,]
                            -varbindlist => \@oids
                         );

This method performs a SNMP get-request query to gather data from the remote agent on the host associated with the Net::SNMP object. The blocking form of the method takes a list of OBJECT IDENTIFIERs in dotted notation. Each OBJECT IDENTIFER is placed into a single SNMP GetRequest-PDU in the same order that it held in the original list. When the object is in non-blocking mode, the list is passed as an array reference to the -varbindlist named argument.

A reference to a hash is returned in blocking mode which contains the contents of the VarBindList. In non-blocking mode, a true value is returned when no error has occurred. In either mode the undefined value is returned when an error has occurred. The "error()" method may be used to determine the cause of the failure.

  get_next_request() - send a SNMP get-next-request to the remote agent
Blocking

   $response = $session->get_next_request(@oids);

Non-blocking

         $ok = $session->get_next_request(
                            [-callback   => sub {},]
                            [-delay      => $seconds,]
                            -varbindlist => \@oids
                         );

This method performs a SNMP get-next-request query to gather data from the remote agent on the host associated with the Net::SNMP object. The blocking form of the method takes a list of OBJECT IDENTIFIERs in dotted notation. Each OBJECT IDENTIFER is placed into a single SNMP GetNextRequest-PDU in the same order that it held in the original list. When the object is in non-blocking mode, the list is passed as an array reference to the -varbindlist named argument.

A reference to a hash is returned in blocking mode which contains the contents of the VarBindList. In non-blocking mode, a true value is returned when no error has occurred. In either mode the undefined value is returned when an error has occurred. The "error()" method may be used to determine the cause of the failure.

  set_request() - send a SNMP set-request to the remote agent
Blocking

   $response = $session->set_request(@oid_type_value);

Non-blocking

         $ok = $session->set_request(
                            [-callback   => sub {},]
                            [-delay      => $seconds,]
                            -varbindlist => \@oid_type_value
                         );

This method is used to modify data on the remote agent that is associated with the Net::SNMP object using a SNMP set-request. The blocking form of the method takes a list of values consisting of groups of an OBJECT IDENTIFIER, an object type, and the actual value to be set. The OBJECT IDENTIFIERs in each trio are to be in dotted notation. The object type is a byte corresponding to the ASN.1 type of value that is to be set. Each of the supported types have been defined and are exported by the package by default (see "EXPORTS"). When the object is in non-blocking mode, the list is passed as an array reference to the -varbindlist named argument.

A reference to a hash is returned in blocking mode which contains the contents of the VarBindList. In non-blocking mode, a true value is returned when no error has occurred. In either mode the undefined value is returned when an error has occurred. The "error()" method may be used to determine the cause of the failure.

  trap() - send a SNMP trap to the remote manager
Blocking

   $value = $session->trap(
                         [-enterprise   => $oid,]
                         [-agentaddr    => $ipaddress,]
                         [-generictrap  => $generic,]
                         [-specifictrap => $specific,]
                         [-timestamp    => $timeticks,]
                         [-varbindlist  => \@oid_type_value]
                       );

Non-blocking

   $value = $session->trap(
                         [-delay        => $seconds,]
                         [-enterprise   => $oid,]
                         [-agentaddr    => $ipaddress,]
                         [-generictrap  => $generic,]
                         [-specifictrap => $specific,]
                         [-timestamp    => $timeticks,]
                         [-varbindlist  => \@oid_type_value]
                       );

This method sends a SNMP trap to the remote manager associated with the Net::SNMP object. All arguments are optional and will be given the following defaults in the absence of a corresponding named argument:

•   The default value for the trap -enterprise is "1.3.6.1.4.1", which corresponds to "iso.org.dod.internet.private.enterprises". The enterprise value is expected to be an OBJECT IDENTIFER in dotted notation.

•   The default value for the trap -agentaddr is the local IP address from the host on which the script is running. The agent-addr is expected to be an IpAddress in dotted notation.

•   The default value for the -generictrap type is 6 which corresponds to "enterpriseSpecific". The generic-trap types are defined and can be exported upon request (see "EXPORTS").

•   The default value for the -specifictrap type is 0. No pre-defined values are available for specific-trap types.

•   The default value for the trap -timestamp is the "uptime" of the script. The "uptime" of the script is the number of hundredths of seconds that have elapsed since the script began running. The time-stamp is expected to be a TimeTicks number in hundredths of seconds.

•   The default value for the trap -varbindlist is an empty array reference. The variable-bindings are expected to be in an array format consisting of groups of an OBJECT IDENTIFIER, an object type, and the actual value of the object. This is identical to the list expected by the "set_request()" method. The OBJECT IDENTIFIERs in each trio are to be in dotted notation. The object type is a byte corresponding to the ASN.1 type for the value. Each of the supported types have been defined and are exported by default (see "EXPORTS").

Upon success, the number of bytes transmitted is returned when the object is in blocking mode. A true value is returned when successful in non-blocking mode. The undefined value is returned when a failure has occurred. The "error()" method can be used to determine the cause of the failure. Since there are no acknowledgements for Trap-PDUs, there is no way to determine if the remote host actually received the trap.

NOTE: When the object is in non-blocking mode, the trap is not sent until the event loop is entered.

  get_bulk_request() - send a SNMPv2 get-bulk-request to the remote agent
Blocking

   $response = $session->get_bulk_request(
                            [-nonrepeaters   => $nonrepeaters,]
                            [-maxrepetitions => $maxrepetitions,]
                            -varbindlist     => \@oids
                         );

Non-blocking

         $ok = $session->get_bulk_request(
                            [-callback       => sub {},]
                            [-delay          => $seconds,]
                            [-nonrepeaters   => $nonrepeaters,]
                            [-maxrepetitions => $maxrepetitions,]
                            -varbindlist     => \@oids
                         );

This method performs a SNMP get-bulk-request query to gather data from the remote agent on the host associated with the Net::SNMP object. All arguments are optional except -varbindlist and will be given the following defaults in the absence of a corresponding named argument:

•   The default value for the get-bulk-request -nonrepeaters is 0. The non-repeaters value specifies the number of variables in the variable-bindings list for which a single successor is to be returned.

•   The default value for the get-bulk-request -maxrepetitions is 0. The max-repetitions value specifies the number of successors to be returned for the remaining variables in the variable-bindings list.

•   The -varbindlist argument expects an array reference consisting of a list of OBJECT IDENTIFIERs in dotted notation. Each OBJECT IDENTIFER is placed into a single SNMP GetBulkRequest-PDU in the same order that it held in the original list.

A reference to a hash is returned in blocking mode which contains the contents of the VarBindList. In non-blocking mode, a true value is returned when no error has occurred. In either mode the undefined value is returned when an error has occurred. The "error()" method may be used to determine the cause of the failure.

NOTE: This method can only be used when the version of the object is set to SNMPv2c.

  inform_request() - send a SNMPv2 inform-request to the remote manager
Blocking

   $response = $session->inform_request(@oid_type_value);

Non-blocking

         $ok = $session->inform_request(
                            [-callback   => sub {},]
                            [-delay      => $seconds,]
                            -varbindlist => \@oid_type_value
                         );

This method is used to provide management information to the remote manager associated with the Net::SNMP object using a SNMPv2 inform-request. In blocking mode, the method takes a list of values consisting of groups of an OBJECT IDENTIFIER, an object type, and the actual value to be defined. The OBJECT IDENTIFIERs in each trio are to be in dotted notation. The object type is a byte corresponding to the ASN.1 type of value that is identified. Each of the supported types have been defined and are exported by the package by default (see "EXPORTS"). When the object is in non-blocking mode, the list is passed as an array reference to the -varbindlist named argument.

The first two variable-bindings fields in the inform-request are specified by SNMPv2 and should be:

•   sysUpTime.0 - ['1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks]

•   snmpTrapOID.0 - ['1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid]

A reference to a hash is returned in blocking mode which contains the contents of the VarBindList. In non-blocking mode, a true value is returned when no error has occurred. In either mode the undefined value is returned when an error has occurred. The "error()" method may be used to determine the cause of the failure.

NOTE: This method can only be used when the version of the object is set to SNMPv2c.

  snmpv2_trap() - send a SNMPv2 snmpV2-trap to the remote manager
Blocking

   $response = $session->snmpv2_trap(@oid_type_value);

Non-blocking

         $ok = $session->snmpv2_trap(
                            [-delay      => $seconds,]
                            -varbindlist => \@oid_type_value
                         );

This method sends a SNMPv2 snmpV2-trap to the remote manager associated with the Net::SNMP object. In blocking mode, the method takes a list of values consisting of groups of an OBJECT IDENTIFIER, an object type, and the actual value to be defined. The OBJECT IDENTIFIERs in each trio are to be in dotted notation. The object type is a byte corresponding to the ASN.1 type of value that is identified. Each of the supported types have been defined and are exported by the package by default (see "EXPORTS"). When the object is in non-blocking mode, the list is passed as an array reference to the -varbindlist named argument.

The first two variable-bindings fields in the snmpV2-trap are specified by SNMPv2 and should be:

•   sysUpTime.0 - ['1.3.6.1.2.1.1.3.0', TIMETICKS, $timeticks]

•   snmpTrapOID.0 - ['1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $oid]

Upon success, the number of bytes transmitted is returned when the object is in blocking mode. A true value is returned when in successful in non-blocking mode. The undefined value is returned when a failure has occurred. The "error()" method can be used to determine the cause of the failure. Since there are no acknowledgements for SNMPv2-Trap-PDUs, there is no way to determine if the remote host actually received the snmpV2-trap.

NOTE: This method can only be used when the version of the object is set to SNMPv2c.

NOTE: When the object is in non-blocking mode, the snmpV2-trap is not sent until the event loop is entered.

  get_table() - retrieve a table from the remote agent
Blocking

   $response = $session->get_table($oid);

Non-blocking

         $ok = $session->get_table(
                            -baseoid   => $oid,
                            [-callback => sub {},]
                            [-delay    => $seconds]
                         );

This method performs repeated SNMP get-next-request or get-bulk-request (when using SNMPv2c) queries to gather data from the remote agent on the host associated with the Net::SNMP object. In blocking mode, the method takes a single OBJECT IDENTIFIER which is used as the base object for the SNMP requests. Repeated SNMP requests are issued until the OBJECT IDENTIFER in the response is no longer a subtree of the base OBJECT IDENTIFIER. When the object is in non-blocking mode, the OBJECT IDENTIFIER must be passed to the -baseoid named argument.

A reference to a hash is returned in blocking mode which contains the contents of the VarBindList. In non-blocking mode, a true value is returned when no error has occurred. In either mode the undefined value is returned when an error has occurred. The "error()" method may be used to determine the cause of the failure.

WARNING: Results from this method can become very large if the base OBJECT IDENTIFIER is close to the root of the SNMP MIB tree.

  version() - set or get the SNMP version for the object
   $rfc_version = $session->version([$version]);

This method is used to set or get the current SNMP version associated with the Net::SNMP object. The module supports SNMP version-1 (SNMPv1) and SNMP version-2c (SNMPv2c). The default version used by the module is SNMP version-1.

The method accepts the digit '1' or the string 'SNMPv1' for SNMP version-1 and the digit '2', or the strings '2c', 'SNMPv2', or 'SNMPv2c' for SNMP version-2c. The undefined value is returned upon an error and the "error()" method may be used to determine the cause.

The method returns the current value for the SNMP version. The returned value is the corresponding version number defined by the RFCs for the protocol version field (i.e. SNMPv1 == 0 and SNMPv2c == 1).

  error() - get the current error message from the object
   $error_message = $session->error;

This method returns a text string explaining the reason for the last error. An empty string is returned if no error has occurred.

  hostname() - get the associated hostname from the object
   $hostname = $session->hostname;

This method returns the hostname string that is associated with the object.

  error_status() - get the current SNMP error-status from the object
   $error_status = $session->error_status;

This method returns the numeric value of the error-status contained in the last SNMP GetResponse-PDU.

  error_index() - get the current SNMP error-index from the object
   $error_index = $session->error_index;

This method returns the numeric value of the error-index contained in the last SNMP GetResponse-PDU.

  var_bind_list() - get the hash reference to the last SNMP response
   $response = $session->var_bind_list;

This method returns a hash reference created using the ObjectName and the ObjectSyntax pairs in the VarBindList of the last SNMP GetResponse-PDU received by the object. The keys of the hash consist of the OBJECT IDENTIFIERs in dotted notation corresponding to each ObjectName in the VarBindList. If any OBJECT IDENTIFIERs passed to the method began with a leading dot, all of the OBJECT IDENTIFIER hash keys will be prefixed with a leading dot. The value of each hash entry is set equal to the value of the corresponding ObjectSyntax. The undefined value is returned if there has been a failure and the "error()" method may be used to determine the reason.

  timeout() - set or get the current timeout period for the object
   $seconds = $session->timeout([$seconds]);

This method returns the current value for the UDP timeout for the Net::SNMP object. This value is the number of seconds that the object will wait for a response from the agent on the remote host. The default timeout is 5.0 seconds.

If a parameter is specified, the timeout for the object is set to the provided value if it falls within the range 1.0 to 60.0 seconds. The undefined value is returned upon an error and the "error()" method may be used to determine the cause.

  retries() - set or get the current retry count for the object
   $count = $session->retries([$count]);

This method returns the current value for the number of times to retry sending a SNMP message to the remote host. The default number of retries is 1.

If a parameter is specified, the number of retries for the object is set to the provided value if it falls within the range 0 to 20. The undefined value is returned upon an error and the "error()" method may be used to determine the cause.

  mtu() - set or get the current MTU for the object
   $octets = $session->mtu([$octets]);

This method returns the current value for the Maximum Transport Unit for the Net::SNMP object. This value is the largest value in octets for an SNMP message that can be transmitted or received by the object. The default MTU is 1500 octets.

If a parameter is specified, the Maximum Transport Unit is set to the provided value if it falls within the range 484 to 65535 octets. The undefined value is returned upon an error and the "error()" method may be used to determine the cause.

  translate() - enable or disable the translation mode for the object
   $mask = $session->translate([$mode]);

   or

   $mask = $session->translate([
                        [ # Perl anonymous ARRAY reference
                           ['-all'            => $mode1,]
                           ['-octetstring     => $mode2,]
                           ['-null'           => $mode3,]
                           ['-timeticks'      => $mode4,]
                           ['-opaque'         => $mode5,]
                           ['-nosuchobject'   => $mode6,]
                           ['-nosuchinstance' => $mode7,]
                           ['-endofmibview'   => $mode8,]
                           ['-unsigned'       => $mode9]
                        ]
                     ]);

When the object decodes the GetResponse-PDU that is returned in response to a SNMP message, certain values are translated into a more "human readable" form. By default the following translations occur:

•   OCTET STRINGs and Opaques containing non-printable characters are converted into a hexadecimal representation prefixed with "0x".

•   TimeTicks integer values are converted to a time format.

•   NULL values return the string "NULL" instead of an empty string.

•   noSuchObject exception values return the string "noSuchObject" instead of an empty string. If translation is not enabled, the SNMP error-status field is set to 128 which is equal to the exported definition NOSUCHOBJECT (see "EXPORTS").

•   noSuchInstance exception values return the string "noSuchInstance" instead of an empty string. If translation is not enabled, the SNMP error-status field is set to 129 which is equal to the exported definition NOSUCHINSTANCE (see "EXPORTS").

•   endOfMibView exception values return the string "endOfMibView" instead of an empty string. If translation is not enabled, the SNMP error-status field is set to 130 which is equal to the exported definition ENDOFMIBVIEW (see "EXPORTS").

•   Counter, Gauges, and TimeTick values that have been incorrectly encoded as signed negative values are returned as unsigned values.

The "translate()" method can be invoked with two different types of arguments.

If the argument passed is any Perl variable type except an array reference, the translation mode for all ASN.1 type is set to either enabled or disabled depending on the value of the passed parameter. Any value that Perl would treat as a true value will set the mode to be enabled for all types, while a false value will disable translation for all types.

A reference to an array can be passed to the "translate()" method in order to defined the translation mode on a per ASN.1 type basis. The array is expected to contain a list of named argument pairs for each ASN.1 type that is to be modified. The arguments in the list are applied in the order that they are passed in via the array. Arguments at the end of the list supercede those passed earlier in the list. The argument "-all" can be used to specify that the mode is to apply to all ASN.1 types. Only the arguments for the ASN.1 types that are to be modified need to be included in the list.

The "translate()" method returns a bit mask indicating which ASN.1 types are to be translated. Definitions of the bit to ASN.1 type mappings can be exported using the ":translate" tag (see "EXPORTS"). The undefined value is returned upon an error and the "error()" method may be used to determine the cause.

  debug() - set or get the debug mode for the module
   $mode = $session->debug([$mode]);

This method is used to enable or disable debugging for the Net::SNMP module. By default, debugging is off. If a parameter is specified, the debug mode is set to either enabled or disabled depending on the value of the passed parameter. Any value that Perl would treat as a true value will set the mode to be enabled, while a false value will disable debugging. The current state of the debugging mode is returned by the method. Debugging can also be enabled using the stand alone function "snmp_debug()". This function can be exported by request (see "EXPORTS").

FUNCTIONS

  oid_context_match() - determine if an OID has a specified MIB context
   $value = oid_context_match($base_oid, $oid);

This function takes two OBJECT IDENTIFIERs in dotted notation and returns a true value (i.e. 0x1) if the second OBJECT IDENTIFIER is equal to or is a subtree of the first OBJECT IDENTIFIER in the SNMP Management Information Base (MIB). This function can be used in conjunction with the "get-next-request()" or "get-bulk-request()" methods to determine when a OBJECT IDENTIFIER in the GetResponse-PDU is no longer in the desired MIB context.

  oid_lex_sort() - sort a list of OBJECT IDENTIFIERs lexicographically
   @sorted_oids = oid_lex_sort(@oids);

This function takes a list of OBJECT IDENTIFIERs in dotted notation and returns the listed sorted in lexicographical order.

  ticks_to_time() - convert TimeTicks to formatted time
   $time = ticks_to_time($timeticks);

This function takes an ASN.1 TimeTicks value and returns a string representing the time defined by the value. The TimeTicks value is expected to be a non-negative integer value representing the time in hundredths of a second since some epoch. The returned string will display the time in days, hours, and seconds format according to the value of the TimeTicks argument.

EXPORTS

Default
    INTEGER, INTEGER32, OCTET_STRING, NULL, OBJECT_IDENTIFIER, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32, UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT, NOSUCHINSTANCE, ENDOFMIBVIEW, snmp_event_loop

Exportable
    INTEGER, INTEGER32, OCTET_STRING, NULL, OBJECT_IDENTIFIER, SEQUENCE, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32, UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT, NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST, GET_NEXT_REQUEST, GET_RESPONSE, SET_REQUEST, TRAP, GET_BULK_REQUEST, INFORM_REQUEST, SNMPV2_TRAP, COLD_START, WARM_START, LINK_DOWN, LINK_UP, AUTHENTICATION_FAILURE, EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC, SNMP_VERSION_1, SNMP_VERSION_2C, SNMP_PORT, SNMP_TRAP_PORT, snmp_debug, snmp_event_loop, oid_context_match, oid_lex_sort, ticks_to_time, TRANSLATE_NONE, TRANSLATE_OCTET_STRING, TRANSLATE_NULL, TRANSLATE_TIMETICKS, TRANSLATE_OPAQUE, TRANSLATE_NOSUCHOBJECT, TRANSLATE_NOSUCHINSTANCE, TRANSLATE_ENDOFMIBVIEW, TRANSLATE_UNSIGNED, TRANSLATE_ALL

Tags
    :asn1
        INTEGER, INTEGER32, OCTET_STRING, NULL, OBJECT_IDENTIFIER, SEQUENCE, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32, UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT, NOSUCHINSTANCE, ENDOFMIBVIEW, GET_REQUEST, GET_NEXT_REQUEST, GET_RESPONSE, SET_REQUEST, TRAP, GET_BULK_REQUEST, INFORM_REQUEST, SNMPV2_TRAP

    :generictrap
        COLD_START, WARM_START, LINK_DOWN, LINK_UP, AUTHENTICATION_FAILURE, EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC

    :snmp
        SNMP_VERSION_1, SNMP_VERSION_2C, SNMP_PORT, SNMP_TRAP_PORT, snmp_debug, snmp_event_loop, oid_context_match, oid_lex_sort, ticks_to_time

    :translate
        TRANSLATE_NONE, TRANSLATE_OCTET_STRING, TRANSLATE_NULL, TRANSLATE_TIMETICKS, TRANSLATE_OPAQUE, TRANSLATE_NOSUCHOBJECT, TRANSLATE_NOSUCHINSTANCE, TRANSLATE_ENDOFMIBVIEW, TRANSLATE_UNSIGNED, TRANSLATE_ALL

    :ALL
        All of the above exportable items.

EXAMPLES

  Blocking get-request for sysUpTime
This example gets the sysUpTime from a remote host:

   #! /usr/local/bin/perl

   use strict;
   use vars qw($session $error $response);

   use Net::SNMP;

   ($session, $error) = Net::SNMP->session(
      -hostname  => shift || 'localhost',
      -community => shift || 'public',
      -port      => shift || 161
   );

   if (!defined($session)) {
      printf("ERROR: %s.\n", $error);
      exit 1;
   }

   my $sysUpTime = '1.3.6.1.2.1.1.3.0';

   if (!defined($response = $session->get_request($sysUpTime))) {
      printf("ERROR: %s.\n", $session->error());
      $session->close();
      exit 1;
   }

   printf("sysUpTime for host '%s' is %s\n",
      $session->hostname(),
      $response->{$sysUpTime}
   );

   $session->close();

   exit 0;

  Blocking set-request of sysContact
This example sets the sysContact information on the remote host to "Help Desk":

   #! /usr/local/bin/perl

   use strict;
   use vars qw($session $error $response);

   use Net::SNMP;

   ($session, $error) = Net::SNMP->session(
      -hostname  => shift || 'localhost',
      -community => shift || 'private',
      -port      => shift || 161
   );

   if (!defined($session)) {
      printf("ERROR: %s.\n", $error);
      exit 1;
   }

   my $sysContact = '1.3.6.1.2.1.1.4.0';
   my $contact    = 'Help Desk';

   $response = $session->set_request($sysContact, OCTET_STRING, $contact);

   if (!defined($response)) {
      printf("ERROR: %s.\n", $session->error());
      $session->close();
      exit 1;
   }

   printf("sysContact for host '%s' set to '%s'\n",
      $session->hostname(),
      $response->{$sysContact}
   );

   $session->close();

   exit 0;

  Non-blocking get-request for sysUpTime on multiple hosts
This example polls several hosts for their sysUpTime using non-blocking objects and reports a warning if this value is less than the value from the last poll:

   #! /usr/local/bin/perl

   use strict;
   use vars qw(@hosts @sessions $MAX_POLLS $INTERVAL $EPOC);

   use Net::SNMP qw(snmp_event_loop ticks_to_time);

   # List of hosts to poll

   @hosts = qw(.1.1.1 1.1.1.2 localhost);

   # Poll interval (in seconds).  This value should be greater than
   # the number of retries times the timeout value.

   $INTERVAL = 60;

   # Maximum number of polls after initial poll

   $MAX_POLLS = 10;

   # Create a session for each host
   foreach (@hosts) {
      my ($session, $error) = Net::SNMP->session(
         -hostname    => $_,
         -nonblocking => 0x1,   # Create non-blocking objects
         -translate   => [
            -timeticks => 0x0   # Turn off so sysUpTime is numeric
         ]
      );
      if (!defined($session)) {
         printf("ERROR: %s.\n", $error);
         foreach (@sessions) { $_->[0]->close(); }
         exit 1;
      }

      # Create an array of arrays which contains the new object,
      # the last sysUpTime, and the total number of polls.

      push(@sessions, [$session, 0, 0]);
   }

   my $sysUpTime = '1.3.6.1.2.1.1.3.0';

   # Queue each of the queries for sysUpTime
   foreach (@sessions) {
      $_->[0]->get_request(
          -varbindlist => [$sysUpTime],
          -callback    => [\&validate_sysUpTime_cb, \$_->[1], \$_->[2]]
      );
   }

   # Define a reference point for all of the polls
   $EPOC = time();

   # Enter the event loop
   snmp_event_loop();

   # Not necessary, but it is nice to clean up after yourself
   foreach (@sessions) { $_->[0]->close(); }

   exit 0;

   sub validate_sysUpTime_cb
   {
      my ($this, $last_uptime, $num_polls) = @_;

      if (!defined($this->var_bind_list())) {

         printf("%-15s  ERROR: %s\n", $this->hostname(), $this->error());

      } else {

         # Validate the sysUpTime

         my $uptime = $this->var_bind_list()->{$sysUpTime};
         if ($uptime < ${$last_uptime}) {
            printf("%-15s  WARNING: %s is less than %s\n",
               $this->hostname(),
               ticks_to_time($uptime),
               ticks_to_time(${$last_uptime})
            );
         } else {
            printf("%-15s  Ok (%s)\n",
               $this->hostname(),
               ticks_to_time($uptime)
            );
         }

         # Store the new sysUpTime
         ${$last_uptime} = $uptime;

      }

      # Queue the next message if we have not reach MAX_POLLS

      if (++${$num_polls} <= $MAX_POLLS) {
         my $delay = (($INTERVAL * ${$num_polls}) + $EPOC) - time();
         $this->get_request(
            -delay       => ($delay >= 0) ? $delay : 0,
            -varbindlist => [$sysUpTime],
            -callback    => [\&validate_sysUpTime_cb, $last_uptime, $num_polls]
         );
      }

      $this->error_status();
   }

AUTHOR
David M. Town <david.town@marconi.com>

ACKNOWLEDGMENTS
The original concept for this module was based on SNMP_Session.pm written by Simon Leinen <simon@switch.ch>.

The Abstract Syntax Notation One (ASN.1) encode and decode methods were derived by example from the CMU SNMP package whose copyright follows: Copyright (c) 1988, 1989, 1991, 1992 by Carnegie Mellon University. All rights reserved.

COPYRIGHT
Copyright (c) 1998-2001 David M. Town. All rights reserved. This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.