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

📄 snmp.pm

📁 snmp的源代码,已经在我的ubuntu下编译通过
💻 PM
📖 第 1 页 / 共 5 页
字号:
Note: The perl SNMP 5.0 module which comes with net-snmp 5.0 andhigher is different than previous versions in a number of ways.  Mostimportantly, it behaves like a proper net-snmp application and callsinit_snmp properly, which means it will read configuration files anduse those defaults where appropriate automatically parse MIB files,etc.  This will likely affect your perl applications if you have, forinstance, default values set up in your snmp.conf file (as the perlmodule will now make use of those defaults).  The docmuentation,however, has sadly not been updated yet (aside from this note), nor isthe read_config default usage implementation fully complete.The 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 taken from library configuration - probably 3 [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, AES] (v3)=item PrivPassdefault <none>, privacy passphrase (v3)=item authMasterKey=item privMasterKey=item authLocalizedKey=item privLocalizedKeyDirectly specified SNMPv3 USM user keys (used if you want to specifythe keys instead of deriving them from a password as above).=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 librariessnprint_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.  UseLongNames will beset so that the full OID is returned to the caller.=item BestGuessdefaults to the value of SNMP::best_guess at time of sessioncreation. this setting controls how <tags> are parsed.  setting to0 causes a regular lookup.  setting to 1 causes a regular expression match (defined as -Ib in snmpcmd) and setting to 2 causes a random access lookup (defined as -IR in snmpcmd).=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.=item $results = $sess->gettable(E<lt>TABLE OIDE<gt>, E<lt>OPTIONS<gt>)This will retrieve an entire table of data and return a hash referenceto that data.  The returned hash reference will have indexes of theOID suffixes for the index data as the key.  The value for each entrywill be another hash containing the data for a given row.  The keys tothat hash will be the column names, and the values will be the data.Example:  #!/usr/bin/perl  use SNMP;  use Data::Dumper;  my $s = new SNMP::Session(DestHost => 'localhost');  print Dumper($s->gettable('ifTable'));On my machine produces:  $VAR1 = {            '6' => {                     'ifMtu' => '1500',                     'ifPhysAddress' => 'PV',                     # ...                     'ifInUnknownProtos' => '0'                   },            '4' => {                     'ifMtu' => '1480',                     'ifPhysAddress' => '',                     # ...                     'ifInUnknownProtos' => '0'                   },            # ...           };By default, it will try to do as optimized retrieval as possible.It'll request multiple columns at once, and use GETBULK if possible.A few options may be specified by passing in an I<OPTIONS> hashcontaining various parameters:=over=item noindexes => 1Instructs the code not to parse the indexes and place the results inthe second hash.  If you don't need the index data, this will befaster.=item columns => [ colname1, ... ]This specifies which columns to collect.  By default, it will try tocollect all the columns defined in the MIB table.=item repeat => I<COUNT>Specifies a GETBULK repeat I<COUNT>.  IE, it will request this manyvarbinds back per column when using the GETBULK operation.  Shorteningthis will mean smaller packets which may help going through somesystems.  By default, this value is calculated and attepmts to guessat what will fit all the results into 1000 bytes.  This calculation isfairly safe, hopefully, but you can either raise or lower the numberusing this option if desired.  In lossy networks, you want to makesure that the packets don't get fragmented and lowering this value isone way to help that.=item nogetbulk => 1Force the use of GETNEXT rather than GETBULK.  (always true forSNMPv1, as it doesn't have GETBULK anyway).  Some agents are greatimplementers of GETBULK and this allows you to force the use ofGETNEXT oprations instead.=back=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

⌨️ 快捷键说明

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