📄 snmp.pm
字号:
sub STORE { SNMP::_debug_internals($_[1]); ${$_[0]} = $_[1];}sub DELETE { SNMP::_debug_internals(0); ${$_[0]} = undef;}package SNMP::DUMP_PACKET;# controls packet dump output from libsnmpsub TIESCALAR { my $class = shift; my $val; bless \$val, $class; }sub FETCH { ${$_[0]}; }sub STORE { SNMP::_dump_packet($_[1]); ${$_[0]} = $_[1]; }sub DELETE { SNMP::_dump_packet(0); ${$_[0]} = 0; }package SNMP::MIB;sub TIEHASH { bless {};}sub FETCH { my $this = shift; my $key = shift; if (!defined $this->{$key}) { tie(%{$this->{$key}}, SNMP::MIB::NODE, $key) or return undef; } $this->{$key};}sub STORE { warn "STORE(@_) : write access to the MIB not implemented\n";}sub DELETE { delete $_[0]->{$_[1]}; # just delete cache entry}sub FIRSTKEY { return '.1'; } # this should actually start at .0 but # because nodes are not stored in lexico # order in ucd-snmp node tree walk will # miss most of the treesub NEXTKEY { # this could be sped up by using an XS __get_next_oid maybe my $node = $_[0]->FETCH($_[1])->{nextNode}; $node->{objectID};}sub EXISTS { exists $_[0]->{$_[1]} || $_[0]->FETCH($_[1]); }sub CLEAR { undef %{$_[0]}; } # clear the cachepackage SNMP::MIB::NODE;my %node_elements = ( objectID => 0, # dotted decimal fully qualified OID 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 augments => 0, # textual identifier of augmented object );# 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::MIB::REPLACE_NEWER; # Controls MIB parsingsub TIESCALAR { my $class = shift; my $val; bless \$val, $class; }sub FETCH { ${$_[0]}; }sub STORE { SNMP::_set_replace_newer($_[1]); ${$_[0]} = $_[1];}sub DELETE { SNMP::_set_replace_newer(0); ${$_[0]} = 0;}package SNMP::MIB::MIB_OPTIONS;sub TIESCALAR { my $class = shift; my $val; bless \$val, $class; }sub FETCH { ${$_[0]}; }sub STORE { SNMP::_mib_toggle_options($_[1]); ${$_[0]} = $_[1]; }sub DELETE { SNMP::_mib_toggle_options(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 for the Net-SNMP SNMP package.=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 DESCRIPTIONNote: 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 NonIncreasingdefaults to the value of SNMP::non_increasing at time of sessioncreation. this setting controls if a non-increasing OID duringbulkwalk will causes an error. setting to 0 causes the defaultbehaviour (which may, in very badly performing agents, result in a never-ending loop).setting to 1 causes an error (OID not increasing) when this error occur.=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>])
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -