Module Version: 5.2.0   Source  

NAME ^

Net::SNMP - SNMP의 객체 지향 적인 인터페이스이다.
Object oriented interface to SNMP

SYNOPSIS ^

Net::SNMP 모듈은 SNMP(단순 네트워크 관리 프로토콜)에 대한 객체지향적인 모듈이다. Perl 어플리케이션은 SNMP 프로토콜을 이용해서 원격 호스트의 정보를 가져오거나 업데이트 할 수 있다. SNMP version-1, SNMP version-2c (Community-Based SNMPv2)와 SNMP version-3 를 지원한다. 이 모듈을 사용하기 위해서는 SNMP에 대한 기본적인 지식과 관계된 네트워크 관리에 대한 이해가 필요하다.
The Net::SNMP module implements an object oriented interface to theSimple Network Management Protocol.Perl applications can use the module to retrieve or update informationon a remote host using the SNMP protocol.The module supports SNMP version-1,SNMP version-2c (Community-Based SNMPv2),and SNMP version-3.The Net::SNMP module assumes that the user has a basic understanding ofthe Simple Network Management Protocol and related network managementconcepts.

DESCRIPTION ^

Net::SNMP 모듈은 SNMP 에 대해서 고 수준 프로그래밍의 인터페이스를 제공하여 SNMP의 복잡한 내용을 추상화 한다. 각각의 Net::SNMP 객체들은 Perl의 객체와 원격 SNMP 에이전트, 매니저와 일대일로 대응된다. 객체가 생성된 후에는 SNMP에 정의된 통신을 할 수 있다.
The Net::SNMP module abstracts the intricate details of the SimpleNetwork Management Protocol by providing a high level programminginterface to the protocol.Each Net::SNMP object provides a one-to-one mapping between a Perlobject and a remote SNMP agent or manager.Once an object is created,it can be used to perform the basic protocol exchange actions definedby SNMP.

각각의 Net::SNMP 객체는 "blocking"이나 "non-blocking"의 속성으로 생성된다. 기본적으로는 프로토콜에서 SNMP 메시지를 보내서 정보 교환이 성공적으로 완료되거나 제한시간(timeout period)가 만료되기 전 까지는 return 되지 않는다. 이러한 방식으로 통신을 하게되면 method가 return 될 때 까지 코드의 흐름이 멈추게 되므로 "blocking"이라고 한다.
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 protocolexchange has completed successfully or a timeout period has expired.This behavior gives the object a "blocking" property because the flowof the code is stopped until the method returns.

추가적인 옵션으로 사용할 수 있는 -nonblocking은 객체 생성자에 전달되어 "non-blocking" 하게 작동되도록 한다. non-blocking한 방법으로 생성된 객체는 SNMP 메시지를 대기열에 넣어두고 바로 return 하여 코드가 계속 수행되게 한다. 대기열에 들어간 SNMP 메시지들은 이벤트 루프가 snmp_dispatcher()메소드를 호출하면 보내지게 된다. SNMP 메시지가 보내질 때, 처음 메시지가 대기열에 들어 가는 순간 사용자에 의해서 정의된 서브루틴을 호출하게 된다. 반응을 받거나 전송계층의 재시도 회수를 초과하여 대기열에서 모든 메시지가 없어지게 되면 이벤트 루프가 끝나게 된다.
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_dispatcher() 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 by exceeding the number of retries at the Transport Layer.

Blocking Objects

Net::SNMP 객체가 작동하는 기본적인 방식은 해당 메소드가 완료될 때 까지 코드의 흐름을 블럭시키는 것이다. 예를 들어 SNMP 프로토콜을 초기화 하는 메소드에서는 결과 값들의 해쉬 레퍼런스가 반환된다.(?) 실패하였을 경우에는 정의되지 않은 값(undef)이 반환된다. error() 메소드를 이용하면 실패의 원인을 알 수 있다.
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 is 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.

SNMP 프로토콜에서 교환된 해쉬 레퍼런스는 VarBindList에서 만들어진 해쉬을 가르키고 있고, 거기에는 결과 메시지가 담겨있다. 해쉬는 VarBindList의 ObjectName과 ObjectSyntax 결합으로 이루어져있다.(?) 해쉬의 키는 각각의 VarBindList의 ObjectName에 해당하는 OBJECT IDENTIFIER가 'dotted notation'으로 되어있다. 해쉬의 값은 ObjectSyntax에 해당하는 값으로 설정 된다. 해쉬 레퍼런스는 var_bind_list() 메소드를 이용해서 가져올 수 있다.
The hash reference returned by a SNMP protocol exchange points to ahash constructed from the VarBindList contained in the SNMP responsemessage.The hash is created using the ObjectName and the ObjectSyntax pairs inthe VarBindList.The keys of the hash consist of the OBJECT IDENTIFIERs in dottednotation corresponding to each ObjectName in the VarBindList.The value of each hash entry is set equal to the value of thecorresponding ObjectSyntax.This hash reference can also be retrieved using the var_bind_list() method.

Non-blocking Objects

non-blocking 행동을 하는 Net::SNMP 객체가 생성될 때, 객체에 지정된 함수는 결과 값을 바로 반환하여 코드의 흐름이 끊기지 않게 한다. 메소드가 호출되었을 때 SNMP 프로토콜에서 결과를 받아야 하는 경우에는, 참의 값(예를 들면 0x1)을 반환하고, 실패하였을 경우에는 정의되지 않은 값(undef)을 반환한다. error() 메소드를 이용하면 실패의 원인을 알 수 있다.
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.

SNMP의 결과 메시지를 담고 있는 VarBindList은 var_bind_list() 메소드에 콜백 함수의 첫 번째 인자로 객체의 레퍼런스를 입력해서 값을 얻을 수 있다. 메소드에서 반환된 값은 VarBindList에 있는 ObjectName과 ObjectSyntax의 쌍으로 이루어진 해쉬의 레퍼런스이다. 해쉬의 각각의 값은 해당하는 ObjectSyntax의 값으로 설정되어 있다. 실패하게 되면 정의되지 않은 값(undef)가 반환되고 error() 메소드를 통해서 원인을 분석할 수 있다.
The contents of the VarBindList contained in the SNMP response message can be retrieved by calling the var_bind_list() method using the object reference passed as the first argument to the callback.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 ^

인수를 받는 경우에는 아래의 두 종류의 방법이 모두 지원된다. 이 문서의 예시에는 대쉬를 사용한 방법을 이용한다.
When named arguments are expected by the methods,two different styles are supported.All examples in this documentation use the dashed-option style:

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

IO:: 형식도 사용 가능하다.
However, the IO:: style is also allowed:

       $object->method(Argument => $value);
Non-blocking 객체 인수
Non-blocking Objects Arguments

Net::SNMP 객체가 "non-blocking" 속성으로 생성되었을 때, SNMP 메시지를 생성하는 대부분의 메소드는 이 속성을 위해서 추가적인 인수를 사용한다.
When a Net::SNMP object has been created with a "non-blocking"property, most methods that generate a SNMP message take additionalarguments to support this property.

콜백
Callback

non-blocking 객체에 해당하는 대부분의 메소드들은 -callback 이름의 인수를 추가적으로 사용한다. -callback 인자에는 서브루틴의 레퍼런스나 첫 번째 요소가 서브루틴의 레퍼런스를 가지는 배열을 사용한다. SNMP 메시지가 도착하거나, 에러가 발생하거나, 아니면 재시도 한계를 초과하면 -callback 값으로 설정 된 서브루틴이 실행된다.
Most methods associated with a non-blocking object have an optional named argument called -callback. The -callbackargument expects a reference to a subroutine or to an array whose firstelement must be a reference to a subroutine. The subroutine defined bythe -callback option is executed when a response to a SNMPmessage is received, an error condition has occurred, or the number ofretries for the message has been exceeded.

만약 -callback 인자가 서브루틴의 레퍼런스만 가지고 있다면, 서브루틴은 파라메터로 Net::SNMP객채의 레퍼런스만 받게 된다. 인자가 배열의 레퍼런스라면 서브루틴의 파라메터로 Net::SNMP객체의 레퍼런스 뒤에 같이 포함된다. 서브루틴의 레퍼런스를 받는 첫 번째 인자는 남은 인자들이 서브루틴으로 넘어가기전에 없어진다.(? : 뭔소리?)
When the -callback argument only contains a subroutinereference, the subroutine is evaluated passing a reference to theoriginal Net::SNMP object as the only parameter. If the -callbackargument was defined as an array reference, all elements in the arrayare passed to subroutine after the reference to 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.


일단 -callback 인자의 메소드가 실행되면, 객체에 인자는 저장되어 있다가 이후에 -callback 옵션없이 사용될 때 해다아 옵션으로 사용된다. -callback 인자에 정의되지 않은 값(undef)을 넣으면 해당 콜백은 없어진다.
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.

주의: -callback 인자로 넘어가는 서브루틴은 자기 자신을 blocking 해서는 안된다. blocking 할 경우 이벤트 루프에 있는 모든 동작(액션?)은 멈추고, Net::SNMP 모듈의 'non-blocking성'을 망치게 된다.
NOTE: The subroutine being passed with the -callbacknamed argument should not cause blocking itself. This will cause allthe actions in the event loop to be stopped, defeating the non-blockingproperty of the Net::SNMP module.

지연
Delay

non-blocking 객체에 추가적으로 사용되는 -delay 라는 인자는 SNMP 프로토콜에서 통신을 해당 초 동안 지연시킬 수 있다. 이벤트 루프가 시작될 때 부터 지연 시간이 계산된다. -delay 파라메터는 한번 지정하면 다른 값을 지정하기 전 까지 해당 객체의 모든 메소드에 영향을 준다. 지연을 없에기 위해서는 해당 파라메터에 0을 입력하면 된다.
An optional argument -delay can also be passed to non-blocking objects. The -delayargument instructs the object to wait the number of seconds passed tothe argument before executing the SNMP protocol exchange. The delayperiod starts when the event loop is entered. The -delayparameter is applied to all methods associated with the object once itis specified. The delay value must be set back to 0 seconds to disablethe delay parameter.

SNMPv3 Arguments

A SNMP context is a collection of management information accessibleby a SNMP entity. An item of management information may exist in morethan one context and a SNMP entity potentially has access to manycontexts. The combination of a contextEngineID and a contextNameunambiguously identifies a context within an administrative domain. Ina SNMPv3 message, the contextEngineID and contextName are included aspart of the scopedPDU. All methods that generate a SNMP messageoptionally take a -contextengineid and -contextname argument to configure these fields.

Context Engine ID

The -contextengineid argument expects a hexadecimal stringrepresenting the desired contextEngineID. The string must be 10 to 64characters (5 to 32 octets) long and can be prefixed with an optional"0x". Once the -contextengineid is specified it stays with theobject until it is changed again or reset to default by passing in theundefined value. By default, the contextEngineID is set to match theauthoritativeEngineID of the authoritative SNMP engine.

Context Name

The contextName is passed as a string which must be 0 to 32 octets in length using the -contextnameargument. The contextName stays with the object until it is changed.The contextName defaults to an empty string which represents the"default" context.

session() - create a new Net::SNMP object

   ($session, $error) = Net::SNMP->session(
[-hostname => $hostname,]
[-port => $port,]
[-localaddr => $localaddr,]
[-localport => $localport,]
[-nonblocking => $boolean,]
[-version => $version,]
[-domain => $domain,]
[-timeout => $seconds,]
[-retries => $count,]
[-maxmsgsize => $octets,]
[-translate => $translate,]
[-debug => $bitmask,]
[-community => $community,] # v1/v2c
[-username => $username,] # v3
[-authkey => $authkey,] # v3
[-authpassword => $authpasswd,] # v3
[-authprotocol => $authproto,] # v3
[-privkey => $privkey,] # v3
[-privpassword => $privpasswd,] # v3
[-privprotocol => $privproto,] # v3
);

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

Most of the named arguments passed to the constructor define basicattributes for the object and are not modifiable after the object hasbeen created. The -timeout, -retries, -maxmsgsize, -translate, and -debugarguments are modifiable using an accessor method. See theircorresponding method definitions for a complete description of theirusage, default values, and valid ranges.

Transport Domain Arguments

The Net::SNMP module uses UDP/IPv4 as the default Transport Domainto exchange SNMP messages between the local and remote devices. Themodule also supports UDP/IPv6, TCP/IPv4, and TCP/IPv6 as alternativeTransport Domains. The -domain argument can be used to changethe Transport Domain by setting the value to one of the followingstrings: 'udp6', 'udp/ipv6'; 'tcp', 'tcp4', 'tcp/ipv4'; 'tcp6', or'tcp/ipv6'. The -domain argument also accepts the strings 'udp', 'udp4', or 'udp/ipv4' which correspond to the default Transport Domain of UDP/IPv4.

The transport address of the destination SNMP device can be specified using the -hostnameargument. This argument is optional and defaults to "localhost". Thedestination port number can be specified as part of the transportaddress or by using the -port argument. Either a numeric portnumber or a textual service name can be specified. A numeric portnumber in parentheses can optionally follow the service name. This portnumber will be used if the service name cannot be resolved. If thedestination port number is not specified, the well-known SNMP portnumber 161 is used.

By default the source transport address and port number are assigneddynamically by the local device on which the Net::SNMP module is beingused. This dynamic assignment can be overridden by using the -localaddr and -localport arguments. These arguments accept the same values as the -hostname and -port arguments respectively. The resolved address must correspond to a valid address of an interface on the local device.

When using an IPv4 Transport Domain, the transport address can bespecified as either an IP network hostname or an IPv4 address instandard dotted notation. The port information can be optionallyappended to the hostname or address delimited by a colon. The acceptedIPv4 transport address formats are address, address:port, hostname, and hostname:port.

When using an IPv6 Transport Domain, the transport address can bespecified as an IP hostname (which will be looked up as a DNS quad-Arecord) or an IPv6 address in presentation format. The port informationcan optionally be included following a colon after the hostname oraddress. When including this information after an IPv6 address, theaddress must be enclosed in square brackets. The scope zone index(described in RFC 4007) can be specified after the address as a decimalvalue delimited by a percent sign. The accepted transport addressformats for IPv6 are address, address%zone, [address]:port, [address%zone]:port, hostname, and hostname:port.

Security Model Arguments

The -version argument controls which other arguments are expected or required by the session() constructor. The Net::SNMP module supports SNMPv1, SNMPv2c, and SNMPv3. The module defaults to SNMPv1 if no -version argument is specified. The -versionargument expects either a digit (i.e. '1', '2', or '3') or a stringspecifying the version (i.e. 'snmpv1', 'snmpv2c', or 'snmpv3') todefine the SNMP version.

The Security Model used by the Net::SNMP object is based on the SNMPversion associated with the object. If the SNMP version is SNMPv1 orSNMPv2c a Community-based Security Model will be used, while theUser-based Security Model (USM) will be used if the version is SNMPv3.

Community-based Security Model Argument

If the Security Model is Community-based, the only argument available is the -communityargument. This argument expects a string that is to be used as the SNMPcommunity name. By default the community name is set to 'public' if theargument is not present.

User-based Security Model Arguments

The User-based Security Model (USM) used by SNMPv3 requires that a securityName be specified using the -username argument. The creation of a Net::SNMP object with the version set to SNMPv3 will fail if the -username argument is not present. The -username argument expects a string 1 to 32 octets in length.

Different levels of security are allowed by the User-based SecurityModel which address authentication and privacy concerns. A SNMPv3Net::SNMP object will derive the security level (securityLevel) basedon which of the following arguments are specified.

By default a securityLevel of 'noAuthNoPriv' is assumed. If the -authkey or -authpassword arguments are specified, the securityLevel becomes 'authNoPriv'. The -authpassword argument expects a string which is at least 1 octet in length. Optionally, the -authkey argument can be used so that a plain text password does not have to be specified in a script. The -authkeyargument expects a hexadecimal string produced by localizing thepassword with the authoritativeEngineID for the specific destinationdevice. The snmpkey utility included with the distribution can be used to create the hexadecimal string (see snmpkey).

Two different hash algorithms are defined by SNMPv3 which can beused by the Security Model for authentication. These algorithms areHMAC-MD5-96 "MD5" (RFC 1321) and HMAC-SHA-96 "SHA-1" (NIST FIPS PUB180-1). The default algorithm used by the module is HMAC-MD5-96. Thisbehavior can be changed by using the -authprotocol argument. This argument expects either the string 'md5' or 'sha' to be passed to modify the hash algorithm.

By specifying the arguments -privkey or -privpasswordthe securityLevel associated with the object becomes 'authPriv'.According to SNMPv3, privacy requires the use of authentication.Therefore, if either of these two arguments are present and the -authkey or -authpassword arguments are missing, the creation of the object fails. The -privkey and -privpassword arguments expect the same input as the -authkey and -authpassword arguments respectively.

The User-based Security Model described in RFC 3414 defines a singleencryption protocol to be used for privacy. This protocol, CBC-DES"DES" (NIST FIPS PUB 46-1), is used by default or if the string 'des'is passed to the -privprotocol argument. The module alsosupports RFC 3826 which describes the use of CFB128-AES-128 "AES" (NISTFIPS PUB 197) in the USM. The AES encryption protocol can be selectedby passing 'aes' or 'aes128' to the -privprotocol argument. By working with the Extended Security Options Consortium http://www.snmp.com/eso/,the module also supports CBC-3DES-EDE "Triple-DES" (NIST FIPS 46-3) inthe User-based Security Model. This is defined in the draft http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt. The Triple-DES encryption protocol can be selected using the -privprotocol argument with the string '3des' or '3desede'.

close() - clear the Transport Domain associated with the object

   $session->close; 

This method clears the Transport Domain and any errors associatedwith the object. Once closed, the Net::SNMP object can no longer beused to send or receive SNMP messages.

snmp_dispatcher() - enter the non-blocking object event loop

   $session->snmp_dispatcher();

This method enters the event loop associated with non-blockingNet::SNMP objects. The method exits when all queued SNMP messages havereceived a response or have timed out at the Transport Layer. Thismethod is also exported as the stand alone function snmp_dispatcher() by default (see "EXPORTS").

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

   $result = $session->get_request(
[-callback => sub {},] # non-blocking
[-delay => $seconds,] # non-blocking
[-contextengineid => $engine_id,] # v3
[-contextname => $name,] # v3
-varbindlist => \@oids,
);

This method performs a SNMP get-request query to gather data fromthe remote agent on the host associated with the Net::SNMP object. Themessage is built using the list of OBJECT IDENTIFIERs in dottednotation passed to the method as an array reference using the -varbindlistargument. Each OBJECT IDENTIFER is placed into a single SNMPGetRequest-PDU in the same order that it held in the original list.

A reference to a hash is returned in blocking mode which containsthe contents of the VarBindList. In non-blocking mode, a true value isreturned when no error has occurred. In either mode, the undefinedvalue 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

   $result = $session->get_next_request(
[-callback => sub {},] # non-blocking
[-delay => $seconds,] # non-blocking
[-contextengineid => $engine_id,] # v3
[-contextname => $name,] # v3
-varbindlist => \@oids,
);

This method performs a SNMP get-next-request query to gather datafrom the remote agent on the host associated with the Net::SNMP object.The message is built using the list of OBJECT IDENTIFIERs in dottednotation passed to the method as an array reference using the -varbindlistargument. Each OBJECT IDENTIFER is placed into a single SNMPGetNextRequest-PDU in the same order that it held in the original list.

A reference to a hash is returned in blocking mode which containsthe contents of the VarBindList. In non-blocking mode, a true value isreturned when no error has occurred. In either mode, the undefinedvalue 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

   $result = $session->set_request(
[-callback => sub {},] # non-blocking
[-delay => $seconds,] # non-blocking
[-contextengineid => $engine_id,] # v3
[-contextname => $name,] # v3
-varbindlist => \@oid_value,
);

This method is used to modify data on the remote agent that isassociated with the Net::SNMP object using a SNMP set-request. Themessage is built using a list of values consisting of groups of anOBJECT IDENTIFIER, an object type, and the actual value to be set. Thislist is passed to the method as an array reference using the -varbindlistargument. The OBJECT IDENTIFIERs in each trio are to be in dottednotation. The object type is an octet corresponding to the ASN.1 typeof value that is to be set. Each of the supported ASN.1 types have beendefined and are exported by the package by default (see "EXPORTS").

A reference to a hash is returned in blocking mode which containsthe contents of the VarBindList. In non-blocking mode, a true value isreturned when no error has occurred. In either mode, the undefinedvalue 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

   $result = $session->trap(
[-delay => $seconds,] # non-blocking
[-enterprise => $oid,]
[-agentaddr => $ipaddress,]
[-generictrap => $generic,]
[-specifictrap => $specific,]
[-timestamp => $timeticks,]
-varbindlist => \@oid_value,
);

This method sends a SNMP trap to the remote manager associated withthe Net::SNMP object. All arguments are optional and will be given thefollowing 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". Theenterprise value is expected to be an OBJECT IDENTIFER in dottednotation.
  • When the Transport Domain is UDP/IPv4 or TCP/IPv4, the default value for the trap -agentaddr is the IP address associated with the interface on which the trap will be transmitted. For other Transport Domains the -agentaddr is defaulted to "0.0.0.0". When specified, 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" ofthe script. The "uptime" of the script is the number of hundredths ofseconds that have elapsed since the script began running. Thetime-stamp is expected to be a TimeTicks number in hundredths ofseconds.
  • The default value for the trap -varbindlist is an emptyarray reference. The variable-bindings are expected to be in an arrayformat consisting of groups of an OBJECT IDENTIFIER, an object type,and the actual value of the object. This is identical to the listexpected by the set_request() method. The OBJECTIDENTIFIERs in each trio are to be in dotted notation. The object typeis an octet corresponding to the ASN.1 type for the value. Each of thesupported types have been defined and are exported by default (see "EXPORTS").

A true value is returned when the method is successful. The undefined value is returned when a failure has occurred. The error()method can be used to determine the cause of the failure. Since thereare no acknowledgements for Trap-PDUs, there is no way to determine ifthe 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 and no callback is ever executed.

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

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

   $result = $session->get_bulk_request(
[-callback => sub {},] # non-blocking
[-delay => $seconds,] # non-blocking
[-contextengineid => $engine_id,] # v3
[-contextname => $name,] # v3
[-nonrepeaters => $non_reps,]
[-maxrepetitions => $max_reps,]
-varbindlist => \@oids,
);

This method performs a SNMP get-bulk-request query to gather datafrom 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 is0. The non-repeaters value specifies the number of variables in thevariable-bindings list for which a single successor is to be returned.
  • The default value for the get-bulk-request -maxrepetitionsis 0. The max-repetitions value specifies the number of successors tobe returned for the remaining variables in the variable-bindings list.
  • The -varbindlist argument expects an array referenceconsisting of a list of OBJECT IDENTIFIERs in dotted notation. EachOBJECT IDENTIFER is placed into a single SNMP GetBulkRequest-PDU in thesame order that it held in the original list.

A reference to a hash is returned in blocking mode which containsthe contents of the VarBindList. In non-blocking mode, a true value isreturned when no error has occurred. In either mode, the undefinedvalue 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 or SNMPv3.

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

   $result = $session->inform_request(
[-callback => sub {},] # non-blocking
[-delay => $seconds,] # non-blocking
[-contextengineid => $engine_id,] # v3
[-contextname => $name,] # v3
-varbindlist => \@oid_value,
);

This method is used to provide management information to the remotemanager associated with the Net::SNMP object using an inform-request.The message is built using a list of values consisting of groups of anOBJECT IDENTIFIER, an object type, and the actual value to beidentified. This list is passed to the method as an array referenceusing the -varbindlist argument. The OBJECT IDENTIFIERs in eachtrio are to be in dotted notation. The object type is an octetcorresponding to the ASN.1 type of value that is to be identified. Eachof the supported ASN.1 types have been defined and are exported by thepackage by default (see "EXPORTS").

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 containsthe contents of the VarBindList. In non-blocking mode, a true value isreturned when no error has occurred. In either mode, the undefinedvalue 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 or SNMPv3.

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

   $result = $session->snmpv2_trap(
[-delay => $seconds,] # non-blocking
-varbindlist => \@oid_value,
);

This method sends a snmpV2-trap to the remote manager associatedwith the Net::SNMP object. The message is built using a list of valuesconsisting of groups of an OBJECT IDENTIFIER, an object type, and theactual value to be identified. This list is passed to the method as anarray reference using the -varbindlist argument. The OBJECTIDENTIFIERs in each trio are to be in dotted notation. The object typeis an octet corresponding to the ASN.1 type of value that is to beidentified. Each of the supported ASN.1 types have been defined and areexported by the package by default (see "EXPORTS").

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)

A true value is returned when the method is successful. The undefined value is returned when a failure has occurred. The error()method can be used to determine the cause of the failure. Since thereare no acknowledgements for SNMPv2-Trap-PDUs, there is no way todetermine if the remote host actually received the snmpV2-trap.

NOTE: When the object is in non-blocking mode, thesnmpV2-trap is not sent until the event loop is entered and no callbackis ever executed.

NOTE: This method can only be used when the version of theobject is set to SNMPv2c. SNMPv2-Trap-PDUs are supported by SNMPv3, butrequire the sender of the message to be an authoritative SNMP enginewhich is not currently supported by the Net::SNMP module.

get_table() - retrieve a table from the remote agent

   $result = $session->get_table(
[-callback => sub {},] # non-blocking
[-delay => $seconds,] # non-blocking
[-contextengineid => $engine_id,] # v3
[-contextname => $name,] # v3
-baseoid => $oid,
[-maxrepetitions => $max_reps,] # v2c/v3
);

This method performs repeated SNMP get-next-request orget-bulk-request (when using SNMPv2c or SNMPv3) queries to gather datafrom the remote agent on the host associated with the Net::SNMP object.The first message sent is built using the OBJECT IDENTIFIER in dottednotation passed to the method by the -baseoid argument.Repeated SNMP requests are issued until the OBJECT IDENTIFIER in theresponse is no longer a child of the base OBJECT IDENTIFIER.

The -maxrepetitions argument can be used to specify themax-repetitions value that is passed to the get-bulk-requests whenusing SNMPv2c or SNMPv3. If this argument is not present, a value iscalculated based on the maximum message size for the Net::SNMP object.If the value is set to 1 or less, get-next-requests will be used forthe queries instead of get-bulk-requests.

A reference to a hash is returned in blocking mode which containsthe contents of the VarBindList. In non-blocking mode, a true value isreturned when no error has occurred. In either mode, the undefinedvalue 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.

get_entries() - retrieve table entries from the remote agent

   $result = $session->get_entries(
[-callback => sub {},] # non-blocking
[-delay => $seconds,] # non-blocking
[-contextengineid => $engine_id,] # v3
[-contextname => $name,] # v3
-columns => \@columns,
[-startindex => $start,]
[-endindex => $end,]
[-maxrepetitions => $max_reps,] # v2c/v3
);

This method performs repeated SNMP get-next-request orget-bulk-request (when using SNMPv2c or SNMPv3) queries to gather datafrom the remote agent on the host associated with the Net::SNMP object.Each message specifically requests data for each OBJECT IDENTIFIERspecified in the -columns array. The OBJECT IDENTIFIERs mustcorrespond to column entries for a conceptual row in a table. They mayhowever be columns in different tables as long as each table is indexedthe same way. The optional -startindex and -endindex arguments may be specified to limit the query to specific rows in the table(s).

The -startindex can be specified as a single decimal value or in dotted notation if the index associated with the entry so requires. If the -startindex is specified, it will be include as part of the query results. If no -startindex is specified, the first request message will be sent without an index. To insure that the -startindexis included, the last subidentifier in the index is decremented by one.If the last subidentifier has a value of zero, the subidentifier isremoved from the index.

The optional -endindex argument can be specified as a single decimal value or in dotted notation. If the -endindex is specified, it will be included as part of the query results. If no -endindexis specified, repeated SNMP requests are issued until the response nolonger returns entries matching any of the columns specified in the -columns array.

The -maxrepetitions argument can be used to specify themax-repetitions value that is passed to the get-bulk-requests whenusing SNMPv2c or SNMPv3. If this argument is not present, a value iscalculated based on the maximum message size of the object and thenumber of columns specified in the -columns array. If the value is set to 1 or less, get-next-requests will be used for the queries instead of get-bulk-requests.

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

version() - get the SNMP version from the object

   $rfc_version = $session->version;

This method returns the current value for the SNMP versionassociated with the object. The returned value is the correspondingversion number defined by the RFCs for the protocol version field (i.e.SNMPv1 == 0, SNMPv2c == 1, and SNMPv3 == 3). The RFC versions aredefined as constant by the module and can be exported by request (see "EXPORTS").

error() - get the current error message from the object

   $error_message = $session->error;

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

hostname() - get the hostname associated with the object

   $hostname = $session->hostname;

This method returns the hostname string that is associated with the object as it was passed to the session() constructor.

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 message received by the object.

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 message received by the object.

var_bind_list() - get the hash reference for the VarBindList values

   $values = $session->var_bind_list;

This method returns a hash reference created using the ObjectNameand the ObjectSyntax pairs in the VarBindList of the last SNMP messagereceived by the object. The keys of the hash consist of the OBJECTIDENTIFIERs in dotted notation corresponding to each ObjectName in theVarBindList. If any of the OBJECT IDENTIFIERs passed to the requestmethod began with a leading dot, all of the OBJECT IDENTIFIER hash keyswill be prefixed with a leading dot. If duplicate OBJECT IDENTIFIERsare present in the VarBindList they will be padded with spaces to makethem an uniq hash key. The value of each hash entry is set equal to thevalue of the corresponding ObjectSyntax. The undefined value isreturned if there has been a failure.

var_bind_names() - get the array of the ObjectNames in the VarBindList

   @names = $session->var_bind_names;

This method returns an array containing the OBJECT IDENTIFIERscorresponding to the ObjectNames in the VarBindList in the order thatthey were received in the last SNMP message. The entries in the arraywill map directly to the keys in the hash reference returned by themethods that perform SNMP message exchanges and by the var_bind_list() and var_bind_types() methods. The array returned for the convenience methods get_table() and get_entries() will be in lexicographical order. An empty array is returned if there has been a failure.

var_bind_types() - get the hash reference for the VarBindList ASN.1 types

   $types = $session->var_bind_types;

This method returns a hash reference created using the ObjectNameand the ASN.1 type of the ObjectSyntax in the VarBindList of the lastSNMP message received by the object. The keys of the hash consist ofthe OBJECT IDENTIFIERs in dotted notation corresponding to eachObjectName in the VarBindList. The value of each hash entry is setequal to the ASN.1 type of the corresponding ObjectSyntax. Constantsfor the supported ASN.1 types have been defined and are exported by thepackage by default (see "EXPORTS"). The undefined value is returned if there has been a failure.

timeout() - set or get the current timeout period for the object

   $seconds = $session->timeout([$seconds]);

This method returns the current value for the Transport Layertimeout for the Net::SNMP object. This value is the number of secondsthat the object will wait for a response from the agent on the remotehost. The default timeout is 5.0 seconds.

If a parameter is specified, the timeout for the object is set tothe 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 toretry sending a SNMP message to the remote host. The default number ofretries is 1.

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

max_msg_size() - set or get the current maxMsgSize for the object

   $octets = $session->max_msg_size([$octets]);

This method returns the current value for the maximum message size(maxMsgSize) for the Net::SNMP object. This value is the largestmessage size in octets that can be prepared or processed by the object.The default maxMsgSize is 1472 octets for UDP/IPv4, 1452 octets forUDP/IPv6, 1460 octets for TCP/IPv4, and 1440 octets for TCP/IPv6.

If a parameter is specified, the maxMsgSize is set to the providedvalue if it falls within the range 484 to 65535 octets. The undefinedvalue is returned upon an error and the error() method may be used to determine the cause.

NOTE: When using SNMPv3, the maxMsgSize is actually containedin the SNMP message (as msgMaxSize). If the value received from aremote device is less than the current maxMsgSize, the size isautomatically adjusted to be the lower value.

translate() - enable or disable the translation mode for the object

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

When the object decodes the GetResponse-PDU that is returned inresponse 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 ASCII charactersare converted into a hexadecimal representation prefixed with "0x". NOTE:The following ASCII control characters are considered to be printableby the module: NUL(0x00), HT(0x09), LF(0x0A), FF(0x0C), and CR(0x0D).
  • 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 SNMPerror-status field is set to 128 which is equal to the exporteddefinition NOSUCHOBJECT (see "EXPORTS").
  • noSuchInstance exception values return the string "noSuchInstance"instead of an empty string. If translation is not enabled, the SNMPerror-status field is set to 129 which is equal to the exporteddefinition NOSUCHINSTANCE (see "EXPORTS").
  • endOfMibView exception values return the string "endOfMibView"instead of an empty string. If translation is not enabled, the SNMPerror-status field is set to 130 which is equal to the exporteddefinition ENDOFMIBVIEW (see "EXPORTS").
  • Counter64, Counter, Gauge, and TimeTick values that have beenincorrectly encoded as signed negative values are returned as unsignedvalues.

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

If the argument passed is any Perl variable type except an arrayreference, the translation mode for all ASN.1 types is set to eitherenabled 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 beenabled for all types, while a false value will disable translation forall types.

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

The translate() method returns a bit mask indicatingwhich ASN.1 types are to be translated. Definitions of the bit to ASN.1type 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

   $mask = $session->debug([$mask]);

This method is used to enable or disable debugging for the Net::SNMPmodule. Debugging can be enabled on a per component level as defined bya bit mask passed to the debug() method. The bit mask is broken up as follows:

  • 0x02 - Message or PDU encoding and decoding
  • 0x04 - Transport Layer
  • 0x08 - Dispatcher
  • 0x10 - Message Processing
  • 0x20 - Security

Symbols representing these bit mask values are defined by the module and can be exported using the :debug tag (see "EXPORTS"). If a non-numeric value is passed to the debug()method, it is evaluated in boolean context. Debugging for all of thecomponents is then enabled or disabled based on the resulting truthvalue.

The current debugging mask 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_base_match() - determine if an OID has a specified OID base

   $value = oid_base_match($base_oid, $oid);

This function takes two OBJECT IDENTIFIERs in dotted notation andreturns a true value (i.e. 0x1) if the second OBJECT IDENTIFIER isequal to or is a child of the first OBJECT IDENTIFIER in the SNMPManagement Information Base (MIB). This function can be used inconjunction 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 tree branch.

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.

snmp_type_ntop() - convert an ASN.1 type to presentation format

   $text = snmp_type_ntop($type);

This function takes an ASN.1 type octet and returns a text stringsuitable for presentation. Some ASN.1 type definitions map to the sameoctet value when encoded. This method cannot distinquish between thesemultiple mappings and the most basic type name will be returned.

ticks_to_time() - convert TimeTicks to formatted time

   $time = ticks_to_time($timeticks);

This function takes an ASN.1 TimeTicks value and returns a stringrepresenting the time defined by the value. The TimeTicks value isexpected to be a non-negative integer value representing the time inhundredths of a second since some epoch. The returned string willdisplay the time in days, hours, and seconds format according to thevalue of the TimeTicks argument.

EXPORTS ^

The Net::SNMP module uses the Exporter module to exportuseful constants and subroutines. These exportable symbols are definedbelow and follow the rules and conventions of the Exporter module (see Exporter).

Default

&snmp_dispatcher, INTEGER, INTEGER32, OCTET_STRING,OBJECT_IDENTIFIER, IPADDRESS, COUNTER, COUNTER32, GAUGE, GAUGE32,UNSIGNED32, TIMETICKS, OPAQUE, COUNTER64, NOSUCHOBJECT, NOSUCHINSTANCE,ENDOFMIBVIEW

Exportable

&snmp_debug, &snmp_dispatcher, &snmp_type_ntop,&oid_base_match, &oid_lex_sort, &ticks_to_time, 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, REPORT, DEBUG_ALL, DEBUG_NONE,DEBUG_MESSAGE, DEBUG_TRANSPORT, DEBUG_DISPATCHER,DEBUG_PROCESSING,DEBUG_SECURITY, COLD_START, WARM_START, LINK_DOWN,LINK_UP,AUTHENTICATION_FAILURE, EGP_NEIGHBOR_LOSS, ENTERPRISE_SPECIFIC,SNMP_VERSION_1,SNMP_VERSION_2C, SNMP_VERSION_3, SNMP_PORT,SNMP_TRAP_PORT, 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, REPORT

:debug

&snmp_debug, DEBUG_ALL, DEBUG_NONE, DEBUG_MESSAGE, DEBUG_TRANSPORT, DEBUG_DISPATCHER, DEBUG_PROCESSING, DEBUG_SECURITY

:generictrap

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

:snmp

&snmp_debug, &snmp_dispatcher, &snmp_type_ntop,&oid_base_match, &oid_lex_sort, &ticks_to_time,SNMP_VERSION_1, SNMP_VERSION_2C, SNMP_VERSION_3, SNMP_PORT,SNMP_TRAP_PORT

: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 ^

1. Blocking SNMPv1 get-request for sysUpTime

This example gets the sysUpTime from a remote host.

   #! /usr/local/bin/perl

use strict;

use Net::SNMP;

my ($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';

my $result = $session->get_request(
-varbindlist => [$sysUpTime]
);

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

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

$session->close;

exit 0;

2. Blocking SNMPv3 set-request of sysContact

This example sets the sysContact information on the remote host to "Help Desk x911". The named arguments passed to the session()constructor are for the demonstration of syntax only. These parameterswill need to be set according to the SNMPv3 parameters of the remotehost used by the script.

   #! /usr/local/bin/perl

use strict;

use Net::SNMP;

my ($session, $error) = Net::SNMP->session(
-hostname => 'myv3host.company.com',
-version => 'snmpv3',
-username => 'myv3Username',
-authkey => '0x05c7fbde31916f64da4d5b77156bdfa7',
-authprotocol => 'md5',
-privkey => '0x93725fd3a02a48ce02df4e065a1c1746'
);

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

my $sysContact = '1.3.6.1.2.1.1.4.0';

my $result = $session->set_request(
-varbindlist => [$sysContact, OCTET_STRING, 'Help Desk x911']
);

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

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

$session->close;

exit 0;

3. Non-blocking SNMPv2c get-bulk-request for ifTable

This example gets the contents of the ifTable by sendingget-bulk-requests until the responses are no longer part of theifTable. The ifTable can also be retrieved using the get_table() method.

   #! /usr/local/bin/perl

use strict;

use Net::SNMP qw(:snmp);

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

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

my $ifTable = '1.3.6.1.2.1.2.2';

my $result = $session->get_bulk_request(
-callback => [\&table_cb, {}],
-maxrepetitions => 10,
-varbindlist => [$ifTable]
);

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

snmp_dispatcher();

$session->close;

exit 0;

sub table_cb
{
my ($session, $table) = @_;

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

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

} else {

# Loop through each of the OIDs in the response and assign
# the key/value pairs to the anonymous hash that is passed
# to the callback. Make sure that we are still in the table
# before assigning the key/values.

my $next;

foreach my $oid (oid_lex_sort(keys(%{$session->var_bind_list}))) {
if (!oid_base_match($ifTable, $oid)) {
$next = undef;
last;
}
$next = $oid;
$table->{$oid} = $session->var_bind_list->{$oid};
}

# If $next is defined we need to send another request
# to get more of the table.

if (defined($next)) {

$result = $session->get_bulk_request(
-callback => [\&table_cb, $table],
-maxrepetitions => 10,
-varbindlist => [$next]
);

if (!defined($result)) {
printf("ERROR: %s\n", $session->error);
}

} else {

# We are no longer in the table, so print the results.

foreach my $oid (oid_lex_sort(keys(%{$table}))) {
printf("%s => %s\n", $oid, $table->{$oid});
}

}
}
}

4. Non-blocking SNMPv1 get-request for sysUpTime on multiple hosts

This example polls several hosts for their sysUpTime usingnon-blocking objects and reports a warning if this value is less thanthe value from the last poll.

   #! /usr/local/bin/perl

use strict;

use Net::SNMP qw(snmp_dispatcher ticks_to_time);

# List of hosts to poll

my @HOSTS = qw(1.1.1.1 1.1.1.2 localhost);

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

my $INTERVAL = 60;

# Maximum number of polls, including the initial poll.

my $MAX_POLLS = 10;

my $sysUpTime = '1.3.6.1.2.1.1.3.0';

# Create a session for each host and queue the first get-request.

foreach my $host (@HOSTS) {

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

# Queue the get-request, passing references to variables that
# will be used to store the last sysUpTime and the number of
# polls that this session has performed.

my ($last_uptime, $num_polls) = (0, 0);

$session->get_request(
-varbindlist => [$sysUpTime],
-callback => [
\&validate_sysUpTime_cb, \$last_uptime, \$num_polls
]
);

}

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

# Enter the event loop
snmp_dispatcher();

exit 0;


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

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

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

} else {

# Validate the sysUpTime

my $uptime = $session->var_bind_list->{$sysUpTime};

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

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

}

# Queue the next message if we have not reached $MAX_POLLS.
# Since we do not provide a -callback argument, the same
# callback and it's original arguments will be used.

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

$session->error_status;
}

REQUIREMENTS ^

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

AUTHOR ^

David M. Town <dtown@cpan.org>

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 methodswere originally derived by example from the CMU SNMP package whosecopyright follows: Copyright (c) 1988, 1989, 1991, 1992 by CarnegieMellon University. All rights reserved.

COPYRIGHT ^

Copyright (c) 1998-2005 David M. Town. All rights reserved. Thisprogram is free software; you may redistribute it and/or modify itunder the same terms as Perl itself.

Posted by Parker Falcon

댓글을 달아주세요