⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snmp.pm

📁 ucd-snmp源代码
💻 PM
📖 第 1 页 / 共 4 页
字号:
     label => 0,    # leaf textual identifier (e.g., 'sysDescr')     subID => 0,    # leaf numeric OID component of objectID (e.g., '1')     moduleID => 0, # textual identifier for module (e.g., 'RFC1213-MIB')     parent => 0,   # parent node     children => 0, # array reference of children nodes     indexes => 0,  # returns array of column labels     varbinds => 0, # returns array of trap/notification varbinds     nextNode => 0, # next lexico node (BUG! does not return in lexico order)     type => 0,     # returns simple type (see getType for values)     access => 0,   # returns ACCESS (ReadOnly, ReadWrite, WriteOnly,                    # NoAccess, Notify, Create)     status => 0,   # returns STATUS (Mandatory, Optional, Obsolete,                    # Deprecated)     syntax => 0,   # returns 'textualConvention' if defined else 'type'     textualConvention => 0, # returns TEXTUAL-CONVENTION     units => 0,    # returns UNITS     hint => 0,     # returns HINT     enums => 0,    # returns hash ref {tag => num, ...}     ranges => 0,   # returns array ref of hash ref [{low => num, high => num}]     defaultValue => 0, # returns default value     description => 0, # returns DESCRIPTION ($SNMP::save_descriptions must                    # be set prior to MIB initialization/parsing    );# sub TIEHASH - implemented in SNMP.xs# sub FETCH - implemented in SNMP.xssub STORE {    warn "STORE(@_): write access to MIB node not implemented\n";}sub DELETE {    warn "DELETE(@_): write access to MIB node not implemented\n";}sub FIRSTKEY { my $k = keys %node_elements; (each(%node_elements))[0]; }sub NEXTKEY { (each(%node_elements))[0]; }sub EXISTS { exists($node_elements{$_[1]}); }sub CLEAR {    warn "CLEAR(@_): write access to MIB node not implemented\n";}#sub DESTROY {#    warn "DESTROY(@_): write access to MIB node not implemented\n";#    # print "SNMP::MIB::NODE::DESTROY : $_[0]->{label} ($_[0])\n";#}package SNMP::MIB::SAVE_DESCR;sub TIESCALAR { my $class = shift; my $val; bless \$val, $class; }sub FETCH { ${$_[0]}; }sub STORE { SNMP::_set_save_descriptions($_[1]); ${$_[0]} = $_[1]; }sub DELETE { SNMP::_set_save_descriptions(0); ${$_[0]} = 0; }package SNMP;END{SNMP::_sock_cleanup() if defined &SNMP::_sock_cleanup;}# Autoload methods go after __END__, and are processed by the autosplit prog.1;__END__=head1 NAMESNMP - The Perl5 'SNMP' Extension Module v3.1.0 for the UCD SNMPv3 Library=head1 SYNOPSIS use SNMP; ... $sess = new SNMP::Session(DestHost => localhost, Community => public); $val = $sess->get('sysDescr.0'); ... $vars = new SNMP::VarList([sysDescr,0], [sysContact,0], [sysLocation,0]); @vals = $sess->get($vars); ... $vb = new SNMP::Varbind(); do {    $val = $sess->getnext($vb);    print "@{$vb}\n"; } until ($sess->{ErrorNum}); ... $SNMP::save_descriptions = 1; SNMP::initMib(); # assuming mib is not already loaded print "$SNMP::MIB{sysDescr}{description}\n";=head1 DESCRIPTIONThe basic operations of the SNMP protocol are provided by this modulethrough an object oriented interface for modularity and ease of use.The primary class is SNMP::Session which encapsulates the persistentaspects of a connection between the management application and themanaged agent. Internally the class is implemented as a blessed hashreference. This class supplies 'get', 'getnext', 'set', 'fget', and'fgetnext' method calls. The methods take a variety of input argumentformats and support both syncronous and asyncronous operation througha polymorphic API (i.e., method behaviour varies dependent on argspassed - see below).=head1 SNMP::Session$sess = new SNMP::Session(DestHost => 'host', ...)The following arguments may be passed to new as a hash.=over 4=item DestHostdefault 'localhost', hostname or ip addr of SNMP agent=item Communitydefault 'public', SNMP community string (used for both R/W)=item Versiondefault '1', [2 (same as 2c), 2c, 3]=item RemotePortdefault '161', allow remote UDP port to be overriden=item Timeoutdefault '1000000', micro-seconds before retry=item Retriesdefault '5', retries before failure=item RetryNoSuchdefault '0', if enabled NOSUCH errors in 'get' pdus willbe repaired, removing the varbind in error, and resent -undef will be returned for all NOSUCH varbinds, when setto '0' this feature is disabled and the entire get requestwill fail on any NOSUCH error (applies to v1 only)=item SecNamedefault 'initial', security name (v3)=item SecLeveldefault 'noAuthNoPriv', security level [noAuthNoPriv,authNoPriv, authPriv] (v3)=item SecEngineIddefault <none>, security engineID, will be probed if notsupplied (v3)=item ContextEngineIddefault <SecEngineId>, context engineID, will beprobed if not supplied (v3)=item Contextdefault '', context name (v3)=item AuthProtodefault 'MD5', authentication protocol [MD5, SHA] (v3)=item AuthPassdefault <none>, authentication passphrase=item PrivProtodefault 'DES', privacy protocol [DES] (v3)=item PrivPassdefault <none>, privacy passphrase (v3)=item VarFormatsdefault 'undef', used by 'fget[next]', holds an hashreference of output value formatters, (e.g., {<obj> =><sub-ref>, ... }, <obj> must match the <obj> and formatused in the get operation. A special <obj>, '*', may beused to apply all <obj>s, the supplied sub is called totranslate the value to a new format. The sub is calledpassing the Varbind as the arg=item TypeFormatsdefault 'undef', used by 'fget[next]', holds an hashreference of output value formatters, (e.g., {<type> =><sub-ref>, ... }, the supplied sub is called to translatethe value to a new format, unless a VarFormat mathces first(e.g., $sess->{TypeFormats}{INTEGER} = \&mapEnum();although this can be done more efficiently by enabling$SNMP::use_enums or session creation param 'UseEnums')=item UseLongNamesdefaults to the value of SNMP::use_long_names at timeof session creation. set to non-zero to have <tags>for 'getnext' methods generated preferring longer Mib nameconvention (e.g., system.sysDescr vs just sysDescr)=item UseSprintValuedefaults to the value of SNMP::use_sprint_value at timeof session creation. set to non-zero to have return valuesfor 'get' and 'getnext' methods formatted with the librariessprint_value function. This will result in certain data typesbeing returned in non-canonical format Note: values returnedwith this option set may not be appropriate for 'set' operations(see discussion of value formats in <vars> description section)=item UseEnumsdefaults to the value of SNMP::use_enums at time of sessioncreation. set to non-zero to have integer return valuesconverted to enumeration identifiers if possible, these valueswill also be acceptable when supplied to 'set' operations=item UseNumericdefaults to the value of SNMP::use_numeric at time of sessioncreation. set to non-zero to have <tags> for get methods returnedas numeric OID's rather than descriptions.  if UseLongNames isset, returns the entire OID as given, otherwise just the last twooctets.=item TimeStampdefaults to the value of SNMP::timestamp_vars at time of sessioncreation. set to non-zero to have an additional element added toeach Varbind containing the time(2) timestamp.  Reference thistimestamp through the $varbind_ref->stamp() method.  Do not modifythe value of a timestamp -- it is shared between all variablesreceived at the same time.=item ErrorStrread-only, holds the error message assoc. w/ last request=item ErrorNumread-only, holds the snmp_err or staus of last request=item ErrorIndread-only, holds the snmp_err_index when appropriate=backPrivate variables:=over=item DestAddrinternal field used to hold the translated DestHost field=item SessPtrinternal field used to cache a created session structure=back=head2 SNMP::Session methods=over=item $sess->update(E<lt>fieldsE<gt>)Updates the SNMP::Session object with the values fieldspassed in as a hash list (similar to new(E<lt>fieldsE<gt>))B<(WARNING! not fully implemented)>=item $sess->get(E<lt>varsE<gt> [,E<lt>callbackE<gt>])do SNMP GET, multiple <vars> formats accepted.for syncronous operation <vars> will be updatedwith value(s) and type(s) and will also returnretrieved value(s). If <callback> supplied methodwill operate asyncronously=item $sess->fget(E<lt>varsE<gt> [,E<lt>callbackE<gt>])do SNMP GET like 'get' and format the values accordingthe handlers specified in $sess->{VarFormats} and$sess->{TypeFormats}=item $sess->getnext(E<lt>varsE<gt> [,E<lt>callbackE<gt>])do SNMP GETNEXT, multiple <vars> formats accepted,returns retrieved value(s), <vars> passed as arguments areupdated to indicate next lexicographical <obj>,<iid>,<val>,and <type>Note: simple string <vars>,(e.g., 'sysDescr.0')form is not updated. If <callback> supplied methodwill operate asyncronously=item $sess->fgetnext(E<lt>varsE<gt> [,E<lt>callbackE<gt>])do SNMP GETNEXT like getnext and format the values accordingthe handlers specified in $sess->{VarFormats} and$sess->{TypeFormats}=item $sess->set(E<lt>varsE<gt> [,E<lt>callbackE<gt>])do SNMP SET, multiple <vars> formats accepted.the value field in all <vars> formats must be in a canonicalformat (i.e., well known format) to ensure unambiguoustranslation to SNMP MIB data value (see discussion ofcanonical value format <vars> description section),returns snmp_errno. If <callback> supplied methodwill operate asyncronously=item $sess->getbulk(E<lt>non-repeatersE<gt>, E<lt>max-repeatersE<gt>, E<lt>varsE<gt>)do an SNMP GETBULK, from the list of Varbinds, the singlenext lexico instance is fetched for the first n Varbindsas defined by <non-repeaters>. For remaining Varbinds,the m lexico instances are retrieved each of the remainingVarbinds, where m is <max-repeaters>.=item $sess->bulkwalk(E<lt>non-repeatersE<gt>, E<lt>max-repeatersE<gt>, E<lt>varsE<gt> [,E<lt>callbackE<gt>])Do a "bulkwalk" of the list of Varbinds.  This is done bysending a GETBULK request (see getbulk() above) for theVarbinds.  For each requested variable, the response isexamined to see if the next lexico instance has left therequested sub-tree.  Any further instances returned forthis variable are ignored, and the walk for that sub-treeis considered complete.If any sub-trees were not completed when the end of theresponses is reached, another request is composed, consistingof the remaining variables.  This process is repeated untilall sub-trees have been completed, or too many packets havebeen exchanged (to avoid loops).The bulkwalk() method returns an array containing an array ofVarbinds, one for each requested variable, in the order of thevariable requests.  Upon error, bulkwalk() returns undef andsets $sess->ErrorStr and $sess->ErrorNum.  If a callback issupplied, bulkwalk() returns the SNMP request id, and returnsimmediately.  The callback will be called with the suppliedargument list and the returned variables list.Note: Because the client must "discover" that the tree iscomplete by comparing the returned variables with those thatwere requested, there is a potential "gotcha" when using themax-repeaters value.  Consider the following code to print alist of interfaces and byte counts:    $numInts = $sess->get('ifNumber.0');    ($desc, $in, $out) = $sess->bulkwalk(0, $numInts,		  [['ifDescr'], ['ifInOctets'], ['ifOutOctets']]);    for $i (0..($numInts - 1)) {        printf "Interface %4s: %s inOctets, %s outOctets\n",                  $$desc[$i]->val, $$in[$i]->val, $$out[$i]->val;    }This code will produce *two* requests to the agent -- the firstto get the interface values, and the second to discover that allthe information was in the first packet.  To get around this,use '$numInts + 1' for the max_repeaters value.  This asks theagent to include one additional (unrelated) variable that signalsthe end of the sub-tree, allowing bulkwalk() to determine thatthe request is complete.=back=head1 SNMP::TrapSession$sess = new SNMP::Session(DestHost => 'host', ...)supports all applicable fields from SNMP::Session(see above)=head2 SNMP::TrapSession methods=over=item $sess->trap(enterprise, agent, generic, specific, uptime, <vars>)    $sess->trap(enterprise=>'.1.3.6.1.4.1.2021', # or 'ucdavis' [default]                agent => '127.0.0.1', # or 'localhost',[dflt 1st intf on host]                generic => specific,  # can be omitted if 'specific' supplied                specific => 5,        # can be omitted if 'generic' supplied                uptime => 1234,       # dflt to localhost uptime (0 on win32)                [[ifIndex, 1, 1],[sysLocation, 0, "here"]]); # optional vars                                                             # always last=item trap(oid, uptime, <vars>) - v2 format    $sess->trap(oid => 'snmpRisingAlarm',                uptime => 1234,                [[ifIndex, 1, 1],[sysLocation, 0, "here"]]); # optional vars                                                             # always last=back=head1 Acceptable variable formats:<vars> may be one of the following forms:=over=item SNMP::VarListrepresents an array of MIB objects to get or set,implemented as a blessed reference to an array ofSNMP::Varbinds, (e.g., [<varbind1>, <varbind2>, ...])=item SNMP::Varbindrepresents a single MIB object to get or set, implemented asa blessed reference to a 4 element array;[<obj>, <iid>, <val>, <type>].=over=item <obj>one of the following forms:=over=item 1)leaf identifier (e.g., 'sysDescr') assumed to beunique for practical purposes=item 2)fully qualified identifier (e.g.,'.iso.org.dod.internet.mgmt.mib-2.system.sysDescr')=item 3)fully qualified, dotted-decimal, numeric OID (e.g.,'.1.3.6.1.2.1.1.1')=back=item <iid>the dotted-decimal, instance identifier. forscalar MIB objects use '0'=item <val>the SNMP data value retrieved from or being setto the agents MIB. for (f)get(next) operations<val> may have a variety of formats as determined bysession and package settings. However for setoperations the <val> format must be canonical toensure unambiguous translation. The canonical formsare as follows:=over=item OBJECTIDdotted-decimal (e.g., .1.3.6.1.2.1.1.1)=item OCTETSTRperl scalar containing octets=item INTEGERdecimal signed integer (or enum)=item NETADDRdotted-decimal=item IPADDRdotted-decimal=item COUNTER

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -