Net_SNMP_util.pm untested

filter: Statementstmt 0.0% 0 / 669 Branchbran 0.0% 0 / 458 Conditioncond 0.0% 0 / 117 MC/DCmcdc 0.0% 0 / 75 Subroutinesub 0.0% 0 / 46 Podpod 0.0% 0 / 40 totaltotal 0.0% 0 / 1405 CC 230 SCAR 70.6
CC
230
Cov
0%
snmpopen
3782.0
snmpwalk_flg
1056.0
ASNtype
600.0
CRAP 1168.2
1 ### - *- mode: Perl -*-
2 ######################################################################
3 ### Net_SNMP_util -- SNMP utilities using Net::SNMP
4 ######################################################################
5 ### Copyright (c) 2005-2011 Mike Mitchell.
6 ###
7 ### This program is free software; you can redistribute it under the
8 ### "Artistic License" included in this distribution (file "Artistic").
9 ######################################################################
10 ### Created by: Mike Mitchell <Mike.Mitchell@sas.com>
11 ###
12 ### Contributions and fixes by:
13 ###
14 ### Laszlo Herczeg <laszlo.herczeg@austinenergy.com>
15 ### ignore unimplemented SNMP_Session.pm options
16 ###
17 ### Daniel McDonald <dmcdonald@digicontech.com>
18 ### make sure snmpwalk_flg stops when last instance in table is fetched
19 ###
20 ### Alexander Kozlov <avk@post.eao.ru>
21 ### Leave snmpwalk_flg early if no OIDs are returned
22 ###
23 ### <jaccobs@online.nl>
24 ### parse NOTIFICATION-TYPE in MIB
25 ###
26 ### Dan Thorson <Dan.Thorson@seagate.com>
27 ### Handle quotes in MIB comments better
28 ###
29 ### Daniel J McDonald <dan.mcdonald@austinenergy.com>
30 ### fix getbulk_request -> get_bulk_request typo
31 ###
32 ### Tobias Oetiker <tobi@oetiker.ch>
33 ### fix '-privpassword' error against snmpv2 hosts
34 ###
35 ######################################################################
36  
37 package Net_SNMP_util;
38  
39 =head1 NAME
40  
41 Net_SNMP_util - SNMP utilities based on Net::SNMP
42  
43 =head1 SYNOPSIS
44  
45 The Net_SNMP_util module implements SNMP utilities using the Net::SNMP module.
46 It implements snmpget, snmpgetnext, snmpwalk, snmpset, snmptrap, and
47 snmpgetbulk. The Net_SNMP_util module assumes that the user has a basic
48 understanding of the Simple Network Management Protocol and related network
49 management concepts.
50  
51 =head1 DESCRIPTION
52  
53 The Net_SNMP_util module simplifies SNMP queries even more than Net::SNMP
54 alone. Easy-to-use "get", "getnext", "walk", "set", "trap", and "getbulk"
55 routines are provided, hiding all the details of a SNMP query.
56  
57 =cut
58  
59 # ==========================================================================
60  
61 use strict;
62 use warnings;
63  
64 ## Validate the version of Perl
65  
66 BEGIN
67 {
68 die('Perl version 5.6.0 or greater is required') if ($] < 5.006);
69 }
70  
71 ## Handle importing/exporting of symbols
72  
73 use vars qw( @ISA @EXPORT $VERSION $ErrorMessage);
74 use Exporter;
75  
76 our @ISA = qw( Exporter );
77  
78 our @EXPORT = qw(
79 snmpget snmpgetnext snmpwalk snmpset snmptrap snmpgetbulk snmpmaptable
80 snmpmaptable4 snmpwalkhash snmpmapOID snmpMIB_to_OID snmpLoad_OID_Cache
81 snmpQueue_MIB_File ErrorMessage
82 );
83  
84 ## Version of the Net_SNMP_util module
85  
86 our $VERSION = 1.16;
87  
88 use Carp;
89  
90 use Net::SNMP v5.0;
91  
92 # The OID numbers from RFC1213 (MIB-II) and RFC1315 (Frame Relay)
93 # are pre-loaded below.
94 %Net_SNMP_util::OIDS =
95 (
96 'iso' => '1',
97 'org' => '1.3',
98 'dod' => '1.3.6',
99 'internet' => '1.3.6.1',
100 'directory' => '1.3.6.1.1',
101 'mgmt' => '1.3.6.1.2',
102 'mib-2' => '1.3.6.1.2.1',
103 'system' => '1.3.6.1.2.1.1',
104 'sysDescr' => '1.3.6.1.2.1.1.1.0',
105 'sysObjectID' => '1.3.6.1.2.1.1.2.0',
106 'sysUpTime' => '1.3.6.1.2.1.1.3.0',
107 'sysUptime' => '1.3.6.1.2.1.1.3.0',
108 'sysContact' => '1.3.6.1.2.1.1.4.0',
109 'sysName' => '1.3.6.1.2.1.1.5.0',
110 'sysLocation' => '1.3.6.1.2.1.1.6.0',
111 'sysServices' => '1.3.6.1.2.1.1.7.0',
112 'interfaces' => '1.3.6.1.2.1.2',
113 'ifNumber' => '1.3.6.1.2.1.2.1.0',
114 'ifTable' => '1.3.6.1.2.1.2.2',
115 'ifEntry' => '1.3.6.1.2.1.2.2.1',
116 'ifIndex' => '1.3.6.1.2.1.2.2.1.1',
117 'ifInOctets' => '1.3.6.1.2.1.2.2.1.10',
118 'ifInUcastPkts' => '1.3.6.1.2.1.2.2.1.11',
119 'ifInNUcastPkts' => '1.3.6.1.2.1.2.2.1.12',
120 'ifInDiscards' => '1.3.6.1.2.1.2.2.1.13',
121 'ifInErrors' => '1.3.6.1.2.1.2.2.1.14',
122 'ifInUnknownProtos' => '1.3.6.1.2.1.2.2.1.15',
123 'ifOutOctets' => '1.3.6.1.2.1.2.2.1.16',
124 'ifOutUcastPkts' => '1.3.6.1.2.1.2.2.1.17',
125 'ifOutNUcastPkts' => '1.3.6.1.2.1.2.2.1.18',
126 'ifOutDiscards' => '1.3.6.1.2.1.2.2.1.19',
127 'ifDescr' => '1.3.6.1.2.1.2.2.1.2',
128 'ifOutErrors' => '1.3.6.1.2.1.2.2.1.20',
129 'ifOutQLen' => '1.3.6.1.2.1.2.2.1.21',
130 'ifSpecific' => '1.3.6.1.2.1.2.2.1.22',
131 'ifType' => '1.3.6.1.2.1.2.2.1.3',
132 'ifMtu' => '1.3.6.1.2.1.2.2.1.4',
133 'ifSpeed' => '1.3.6.1.2.1.2.2.1.5',
134 'ifPhysAddress' => '1.3.6.1.2.1.2.2.1.6',
135 'ifAdminHack' => '1.3.6.1.2.1.2.2.1.7',
136 'ifAdminStatus' => '1.3.6.1.2.1.2.2.1.7',
137 'ifOperHack' => '1.3.6.1.2.1.2.2.1.8',
138 'ifOperStatus' => '1.3.6.1.2.1.2.2.1.8',
139 'ifLastChange' => '1.3.6.1.2.1.2.2.1.9',
140 'at' => '1.3.6.1.2.1.3',
141 'atTable' => '1.3.6.1.2.1.3.1',
142 'atEntry' => '1.3.6.1.2.1.3.1.1',
143 'atIfIndex' => '1.3.6.1.2.1.3.1.1.1',
144 'atPhysAddress' => '1.3.6.1.2.1.3.1.1.2',
145 'atNetAddress' => '1.3.6.1.2.1.3.1.1.3',
146 'ip' => '1.3.6.1.2.1.4',
147 'ipForwarding' => '1.3.6.1.2.1.4.1',
148 'ipOutRequests' => '1.3.6.1.2.1.4.10',
149 'ipOutDiscards' => '1.3.6.1.2.1.4.11',
150 'ipOutNoRoutes' => '1.3.6.1.2.1.4.12',
151 'ipReasmTimeout' => '1.3.6.1.2.1.4.13',
152 'ipReasmReqds' => '1.3.6.1.2.1.4.14',
153 'ipReasmOKs' => '1.3.6.1.2.1.4.15',
154 'ipReasmFails' => '1.3.6.1.2.1.4.16',
155 'ipFragOKs' => '1.3.6.1.2.1.4.17',
156 'ipFragFails' => '1.3.6.1.2.1.4.18',
157 'ipFragCreates' => '1.3.6.1.2.1.4.19',
158 'ipDefaultTTL' => '1.3.6.1.2.1.4.2',
159 'ipAddrTable' => '1.3.6.1.2.1.4.20',
160 'ipAddrEntry' => '1.3.6.1.2.1.4.20.1',
161 'ipAdEntAddr' => '1.3.6.1.2.1.4.20.1.1',
162 'ipAdEntIfIndex' => '1.3.6.1.2.1.4.20.1.2',
163 'ipAdEntNetMask' => '1.3.6.1.2.1.4.20.1.3',
164 'ipAdEntBcastAddr' => '1.3.6.1.2.1.4.20.1.4',
165 'ipAdEntReasmMaxSize' => '1.3.6.1.2.1.4.20.1.5',
166 'ipRouteTable' => '1.3.6.1.2.1.4.21',
167 'ipRouteEntry' => '1.3.6.1.2.1.4.21.1',
168 'ipRouteDest' => '1.3.6.1.2.1.4.21.1.1',
169 'ipRouteAge' => '1.3.6.1.2.1.4.21.1.10',
170 'ipRouteMask' => '1.3.6.1.2.1.4.21.1.11',
171 'ipRouteMetric5' => '1.3.6.1.2.1.4.21.1.12',
172 'ipRouteInfo' => '1.3.6.1.2.1.4.21.1.13',
173 'ipRouteIfIndex' => '1.3.6.1.2.1.4.21.1.2',
174 'ipRouteMetric1' => '1.3.6.1.2.1.4.21.1.3',
175 'ipRouteMetric2' => '1.3.6.1.2.1.4.21.1.4',
176 'ipRouteMetric3' => '1.3.6.1.2.1.4.21.1.5',
177 'ipRouteMetric4' => '1.3.6.1.2.1.4.21.1.6',
178 'ipRouteNextHop' => '1.3.6.1.2.1.4.21.1.7',
179 'ipRouteType' => '1.3.6.1.2.1.4.21.1.8',
180 'ipRouteProto' => '1.3.6.1.2.1.4.21.1.9',
181 'ipNetToMediaTable' => '1.3.6.1.2.1.4.22',
182 'ipNetToMediaEntry' => '1.3.6.1.2.1.4.22.1',
183 'ipNetToMediaIfIndex' => '1.3.6.1.2.1.4.22.1.1',
184 'ipNetToMediaPhysAddress' => '1.3.6.1.2.1.4.22.1.2',
185 'ipNetToMediaNetAddress' => '1.3.6.1.2.1.4.22.1.3',
186 'ipNetToMediaType' => '1.3.6.1.2.1.4.22.1.4',
187 'ipRoutingDiscards' => '1.3.6.1.2.1.4.23',
188 'ipInReceives' => '1.3.6.1.2.1.4.3',
189 'ipInHdrErrors' => '1.3.6.1.2.1.4.4',
190 'ipInAddrErrors' => '1.3.6.1.2.1.4.5',
191 'ipForwDatagrams' => '1.3.6.1.2.1.4.6',
192 'ipInUnknownProtos' => '1.3.6.1.2.1.4.7',
193 'ipInDiscards' => '1.3.6.1.2.1.4.8',
194 'ipInDelivers' => '1.3.6.1.2.1.4.9',
195 'icmp' => '1.3.6.1.2.1.5',
196 'icmpInMsgs' => '1.3.6.1.2.1.5.1',
197 'icmpInTimestamps' => '1.3.6.1.2.1.5.10',
198 'icmpInTimestampReps' => '1.3.6.1.2.1.5.11',
199 'icmpInAddrMasks' => '1.3.6.1.2.1.5.12',
200 'icmpInAddrMaskReps' => '1.3.6.1.2.1.5.13',
201 'icmpOutMsgs' => '1.3.6.1.2.1.5.14',
202 'icmpOutErrors' => '1.3.6.1.2.1.5.15',
203 'icmpOutDestUnreachs' => '1.3.6.1.2.1.5.16',
204 'icmpOutTimeExcds' => '1.3.6.1.2.1.5.17',
205 'icmpOutParmProbs' => '1.3.6.1.2.1.5.18',
206 'icmpOutSrcQuenchs' => '1.3.6.1.2.1.5.19',
207 'icmpInErrors' => '1.3.6.1.2.1.5.2',
208 'icmpOutRedirects' => '1.3.6.1.2.1.5.20',
209 'icmpOutEchos' => '1.3.6.1.2.1.5.21',
210 'icmpOutEchoReps' => '1.3.6.1.2.1.5.22',
211 'icmpOutTimestamps' => '1.3.6.1.2.1.5.23',
212 'icmpOutTimestampReps' => '1.3.6.1.2.1.5.24',
213 'icmpOutAddrMasks' => '1.3.6.1.2.1.5.25',
214 'icmpOutAddrMaskReps' => '1.3.6.1.2.1.5.26',
215 'icmpInDestUnreachs' => '1.3.6.1.2.1.5.3',
216 'icmpInTimeExcds' => '1.3.6.1.2.1.5.4',
217 'icmpInParmProbs' => '1.3.6.1.2.1.5.5',
218 'icmpInSrcQuenchs' => '1.3.6.1.2.1.5.6',
219 'icmpInRedirects' => '1.3.6.1.2.1.5.7',
220 'icmpInEchos' => '1.3.6.1.2.1.5.8',
221 'icmpInEchoReps' => '1.3.6.1.2.1.5.9',
222 'tcp' => '1.3.6.1.2.1.6',
223 'tcpRtoAlgorithm' => '1.3.6.1.2.1.6.1',
224 'tcpInSegs' => '1.3.6.1.2.1.6.10',
225 'tcpOutSegs' => '1.3.6.1.2.1.6.11',
226 'tcpRetransSegs' => '1.3.6.1.2.1.6.12',
227 'tcpConnTable' => '1.3.6.1.2.1.6.13',
228 'tcpConnEntry' => '1.3.6.1.2.1.6.13.1',
229 'tcpConnState' => '1.3.6.1.2.1.6.13.1.1',
230 'tcpConnLocalAddress' => '1.3.6.1.2.1.6.13.1.2',
231 'tcpConnLocalPort' => '1.3.6.1.2.1.6.13.1.3',
232 'tcpConnRemAddress' => '1.3.6.1.2.1.6.13.1.4',
233 'tcpConnRemPort' => '1.3.6.1.2.1.6.13.1.5',
234 'tcpInErrs' => '1.3.6.1.2.1.6.14',
235 'tcpOutRsts' => '1.3.6.1.2.1.6.15',
236 'tcpRtoMin' => '1.3.6.1.2.1.6.2',
237 'tcpRtoMax' => '1.3.6.1.2.1.6.3',
238 'tcpMaxConn' => '1.3.6.1.2.1.6.4',
239 'tcpActiveOpens' => '1.3.6.1.2.1.6.5',
240 'tcpPassiveOpens' => '1.3.6.1.2.1.6.6',
241 'tcpAttemptFails' => '1.3.6.1.2.1.6.7',
242 'tcpEstabResets' => '1.3.6.1.2.1.6.8',
243 'tcpCurrEstab' => '1.3.6.1.2.1.6.9',
244 'udp' => '1.3.6.1.2.1.7',
245 'udpInDatagrams' => '1.3.6.1.2.1.7.1',
246 'udpNoPorts' => '1.3.6.1.2.1.7.2',
247 'udpInErrors' => '1.3.6.1.2.1.7.3',
248 'udpOutDatagrams' => '1.3.6.1.2.1.7.4',
249 'udpTable' => '1.3.6.1.2.1.7.5',
250 'udpEntry' => '1.3.6.1.2.1.7.5.1',
251 'udpLocalAddress' => '1.3.6.1.2.1.7.5.1.1',
252 'udpLocalPort' => '1.3.6.1.2.1.7.5.1.2',
253 'egp' => '1.3.6.1.2.1.8',
254 'egpInMsgs' => '1.3.6.1.2.1.8.1',
255 'egpInErrors' => '1.3.6.1.2.1.8.2',
256 'egpOutMsgs' => '1.3.6.1.2.1.8.3',
257 'egpOutErrors' => '1.3.6.1.2.1.8.4',
258 'egpNeighTable' => '1.3.6.1.2.1.8.5',
259 'egpNeighEntry' => '1.3.6.1.2.1.8.5.1',
260 'egpNeighState' => '1.3.6.1.2.1.8.5.1.1',
261 'egpNeighStateUps' => '1.3.6.1.2.1.8.5.1.10',
262 'egpNeighStateDowns' => '1.3.6.1.2.1.8.5.1.11',
263 'egpNeighIntervalHello' => '1.3.6.1.2.1.8.5.1.12',
264 'egpNeighIntervalPoll' => '1.3.6.1.2.1.8.5.1.13',
265 'egpNeighMode' => '1.3.6.1.2.1.8.5.1.14',
266 'egpNeighEventTrigger' => '1.3.6.1.2.1.8.5.1.15',
267 'egpNeighAddr' => '1.3.6.1.2.1.8.5.1.2',
268 'egpNeighAs' => '1.3.6.1.2.1.8.5.1.3',
269 'egpNeighInMsgs' => '1.3.6.1.2.1.8.5.1.4',
270 'egpNeighInErrs' => '1.3.6.1.2.1.8.5.1.5',
271 'egpNeighOutMsgs' => '1.3.6.1.2.1.8.5.1.6',
272 'egpNeighOutErrs' => '1.3.6.1.2.1.8.5.1.7',
273 'egpNeighInErrMsgs' => '1.3.6.1.2.1.8.5.1.8',
274 'egpNeighOutErrMsgs' => '1.3.6.1.2.1.8.5.1.9',
275 'egpAs' => '1.3.6.1.2.1.8.6',
276 'transmission' => '1.3.6.1.2.1.10',
277 'frame-relay' => '1.3.6.1.2.1.10.32',
278 'frDlcmiTable' => '1.3.6.1.2.1.10.32.1',
279 'frDlcmiEntry' => '1.3.6.1.2.1.10.32.1.1',
280 'frDlcmiIfIndex' => '1.3.6.1.2.1.10.32.1.1.1',
281 'frDlcmiState' => '1.3.6.1.2.1.10.32.1.1.2',
282 'frDlcmiAddress' => '1.3.6.1.2.1.10.32.1.1.3',
283 'frDlcmiAddressLen' => '1.3.6.1.2.1.10.32.1.1.4',
284 'frDlcmiPollingInterval' => '1.3.6.1.2.1.10.32.1.1.5',
285 'frDlcmiFullEnquiryInterval' => '1.3.6.1.2.1.10.32.1.1.6',
286 'frDlcmiErrorThreshold' => '1.3.6.1.2.1.10.32.1.1.7',
287 'frDlcmiMonitoredEvents' => '1.3.6.1.2.1.10.32.1.1.8',
288 'frDlcmiMaxSupportedVCs' => '1.3.6.1.2.1.10.32.1.1.9',
289 'frDlcmiMulticast' => '1.3.6.1.2.1.10.32.1.1.10',
290 'frCircuitTable' => '1.3.6.1.2.1.10.32.2',
291 'frCircuitEntry' => '1.3.6.1.2.1.10.32.2.1',
292 'frCircuitIfIndex' => '1.3.6.1.2.1.10.32.2.1.1',
293 'frCircuitDlci' => '1.3.6.1.2.1.10.32.2.1.2',
294 'frCircuitState' => '1.3.6.1.2.1.10.32.2.1.3',
295 'frCircuitReceivedFECNs' => '1.3.6.1.2.1.10.32.2.1.4',
296 'frCircuitReceivedBECNs' => '1.3.6.1.2.1.10.32.2.1.5',
297 'frCircuitSentFrames' => '1.3.6.1.2.1.10.32.2.1.6',
298 'frCircuitSentOctets' => '1.3.6.1.2.1.10.32.2.1.7',
299 'frOutOctets' => '1.3.6.1.2.1.10.32.2.1.7',
300 'frCircuitReceivedFrames' => '1.3.6.1.2.1.10.32.2.1.8',
301 'frCircuitReceivedOctets' => '1.3.6.1.2.1.10.32.2.1.9',
302 'frInOctets' => '1.3.6.1.2.1.10.32.2.1.9',
303 'frCircuitCreationTime' => '1.3.6.1.2.1.10.32.2.1.10',
304 'frCircuitLastTimeChange' => '1.3.6.1.2.1.10.32.2.1.11',
305 'frCircuitCommittedBurst' => '1.3.6.1.2.1.10.32.2.1.12',
306 'frCircuitExcessBurst' => '1.3.6.1.2.1.10.32.2.1.13',
307 'frCircuitThroughput' => '1.3.6.1.2.1.10.32.2.1.14',
308 'frErrTable' => '1.3.6.1.2.1.10.32.3',
309 'frErrEntry' => '1.3.6.1.2.1.10.32.3.1',
310 'frErrIfIndex' => '1.3.6.1.2.1.10.32.3.1.1',
311 'frErrType' => '1.3.6.1.2.1.10.32.3.1.2',
312 'frErrData' => '1.3.6.1.2.1.10.32.3.1.3',
313 'frErrTime' => '1.3.6.1.2.1.10.32.3.1.4',
314 'frame-relay-globals' => '1.3.6.1.2.1.10.32.4',
315 'frTrapState' => '1.3.6.1.2.1.10.32.4.1',
316 'snmp' => '1.3.6.1.2.1.11',
317 'snmpInPkts' => '1.3.6.1.2.1.11.1',
318 'snmpInBadValues' => '1.3.6.1.2.1.11.10',
319 'snmpInReadOnlys' => '1.3.6.1.2.1.11.11',
320 'snmpInGenErrs' => '1.3.6.1.2.1.11.12',
321 'snmpInTotalReqVars' => '1.3.6.1.2.1.11.13',
322 'snmpInTotalSetVars' => '1.3.6.1.2.1.11.14',
323 'snmpInGetRequests' => '1.3.6.1.2.1.11.15',
324 'snmpInGetNexts' => '1.3.6.1.2.1.11.16',
325 'snmpInSetRequests' => '1.3.6.1.2.1.11.17',
326 'snmpInGetResponses' => '1.3.6.1.2.1.11.18',
327 'snmpInTraps' => '1.3.6.1.2.1.11.19',
328 'snmpOutPkts' => '1.3.6.1.2.1.11.2',
329 'snmpOutTooBigs' => '1.3.6.1.2.1.11.20',
330 'snmpOutNoSuchNames' => '1.3.6.1.2.1.11.21',
331 'snmpOutBadValues' => '1.3.6.1.2.1.11.22',
332 'snmpOutGenErrs' => '1.3.6.1.2.1.11.24',
333 'snmpOutGetRequests' => '1.3.6.1.2.1.11.25',
334 'snmpOutGetNexts' => '1.3.6.1.2.1.11.26',
335 'snmpOutSetRequests' => '1.3.6.1.2.1.11.27',
336 'snmpOutGetResponses' => '1.3.6.1.2.1.11.28',
337 'snmpOutTraps' => '1.3.6.1.2.1.11.29',
338 'snmpInBadVersions' => '1.3.6.1.2.1.11.3',
339 'snmpEnableAuthenTraps' => '1.3.6.1.2.1.11.30',
340 'snmpInBadCommunityNames' => '1.3.6.1.2.1.11.4',
341 'snmpInBadCommunityUses' => '1.3.6.1.2.1.11.5',
342 'snmpInASNParseErrs' => '1.3.6.1.2.1.11.6',
343 'snmpInTooBigs' => '1.3.6.1.2.1.11.8',
344 'snmpInNoSuchNames' => '1.3.6.1.2.1.11.9',
345 'ifName' => '1.3.6.1.2.1.31.1.1.1.1',
346 'ifInMulticastPkts' => '1.3.6.1.2.1.31.1.1.1.2',
347 'ifInBroadcastPkts' => '1.3.6.1.2.1.31.1.1.1.3',
348 'ifOutMulticastPkts' => '1.3.6.1.2.1.31.1.1.1.4',
349 'ifOutBroadcastPkts' => '1.3.6.1.2.1.31.1.1.1.5',
350 'ifHCInOctets' => '1.3.6.1.2.1.31.1.1.1.6',
351 'ifHCInUcastPkts' => '1.3.6.1.2.1.31.1.1.1.7',
352 'ifHCInMulticastPkts' => '1.3.6.1.2.1.31.1.1.1.8',
353 'ifHCInBroadcastPkts' => '1.3.6.1.2.1.31.1.1.1.9',
354 'ifHCOutOctets' => '1.3.6.1.2.1.31.1.1.1.10',
355 'ifHCOutUcastPkts' => '1.3.6.1.2.1.31.1.1.1.11',
356 'ifHCOutMulticastPkts' => '1.3.6.1.2.1.31.1.1.1.12',
357 'ifHCOutBroadcastPkts' => '1.3.6.1.2.1.31.1.1.1.13',
358 'ifLinkUpDownTrapEnable' => '1.3.6.1.2.1.31.1.1.1.14',
359 'ifHighSpeed' => '1.3.6.1.2.1.31.1.1.1.15',
360 'ifPromiscuousMode' => '1.3.6.1.2.1.31.1.1.1.16',
361 'ifConnectorPresent' => '1.3.6.1.2.1.31.1.1.1.17',
362 'ifAlias' => '1.3.6.1.2.1.31.1.1.1.18',
363 'ifCounterDiscontinuityTime' => '1.3.6.1.2.1.31.1.1.1.19',
364 'experimental' => '1.3.6.1.3',
365 'private' => '1.3.6.1.4',
366 'enterprises' => '1.3.6.1.4.1',
367 );
368  
369 # GIL
370 my %revOIDS = (); # Reversed %Net_SNMP_util::OIDS hash
371 my $RevNeeded = 1;
372  
373 undef $Net_SNMP_util::Host;
374 undef $Net_SNMP_util::Session;
375 undef $Net_SNMP_util::Version;
376 undef $Net_SNMP_util::LHost;
377 undef $Net_SNMP_util::IPv4only;
378 undef $Net_SNMP_util::ContextEngineID;
379 undef $Net_SNMP_util::ContextName;
380 $Net_SNMP_util::Debug = 0;
381 $Net_SNMP_util::SuppressWarnings = 0;
382 $Net_SNMP_util::CacheFile = "OID_cache.txt";
383 $Net_SNMP_util::CacheLoaded = 0;
384 $Net_SNMP_util::ReturnArrayRefs = 0;
385 $Net_SNMP_util::ReturnHashRefs = 0;
386 $Net_SNMP_util::MaxRepetitions = 12;
387  
388 ### Prototypes
389 sub snmpget ($@);
390 sub snmpgetnext ($@);
391 sub snmpopen ($$$);
392 sub snmpwalk ($@);
393 sub snmpwalk_flg ($$@);
394 sub snmpset ($@);
395 sub snmptrap ($$$$$@);
396 sub snmpgetbulk ($$$@);
397 sub snmpwalkhash ($$@);
398 sub toOID (@);
399 sub snmpmapOID (@);
400 sub snmpMIB_to_OID ($);
401 sub Check_OID ($);
402 sub snmpLoad_OID_Cache ($);
403 sub snmpQueue_MIB_File (@);
404 sub ASNtype ($);
405 sub error_msg ($);
406 sub MIB_fill_OID ($);
407  
408 sub version () { $VERSION; }
409  
410 =head1 Option Notes
411  
412 =over
413  
414 =item host Parameter
415  
416 SNMP parameters can be specified as part of the hostname/ip address passed
417 as the first argument. The syntax is
418  
419 community@host:port:timeout:retries:backoff:version
420  
421 If the community is left off, it defaults to "public".
422 If the port is left off, it defaults to 161 for everything but snmptrap().
423 The snmptrap() routine uses a default port of 162.
424 Timeout and retries defaults to whatever Net::SNMP uses, currently 5.0 seconds
425 and 1 retry (2 tries total).
426 The backoff parameter is currently unimplemented.
427 The version parameter defaults to SNMP version 1. Some SNMP values such as
428 64-bit counters have to be queried using SNMP version 2. Specifying "2" or
429 "2c" as the version parameter will accomplish this. The snmpgetbulk routine
430 is only supported in SNMP version 2 and higher. Additional security features
431 are available under SNMP version 3.
432  
433 Some machines have additional security features that only allow SNMP
434 queries to come from certain IP addresses. If the host doing the query
435 has multiple interfaces, it may be necessary to specify the interface
436 the query should come from. The port parameter is further broken down into
437  
438 remote_port!local_address!local_port
439  
440 Here are some examples:
441  
442 somehost
443 somehost:161
444 somehost:161!192.168.2.4!4000 use 192.168.2.4 and port 4000 as source
445 somehost:!192.168.2.4 use 192.168.2.4 as source
446 somehost:!!4000 use port 4000 as source
447  
448 Most people will only need to use the first form ("somehost").
449  
450 =item OBJECT IDENTIFIERs
451  
452 To further simplify SNMP queries, the query routines use a small table that
453 maps the textual representation of OBJECT IDENTIFIERs to their dotted notation.
454 The OBJECT IDENTIFIERs from RFC1213 (MIB-II) and RFC1315 (Frame Relay) are
455 preloaded. This allows OBJECT IDENTIFIERs like "ifInOctets.4" to be used
456 instead of the more cumbersome "1.3.6.1.2.1.2.2.1.10.4".
457  
458 Several functions are provided to manage the mapping table. Mapping entries
459 can be added directly, SNMP MIB files can be read, and a cache file with the
460 text-to-OBJECT-IDENTIFIER mappings are maintained. By default, the file
461 "OID_cache.txt" is loaded, but it can by changed by setting the variable
462 $Net_SNMP_util::CacheFile to the desired file name. The functions to
463 manipulate the mappings are:
464  
465 snmpmapOID Add a textual OID mapping directly
466 snmpMIB_to_OID Read a SNMP MIB file
467 snmpLoad_OID_Cache Load an OID-mapping cache file
468 snmpQueue_MIB_File Queue a SNMP MIB file for loading on demand
469  
470 =item Net::SNMP extensions
471  
472 This module is built on top of Net::SNMP. Net::SNMP has a different method
473 of specifying SNMP parameters. To support this different method, this module
474 will accept an optional hash reference containing the SNMP parameters. The
475 hash may contain the following:
476  
477 [-port => $port,]
478 [-localaddr => $localaddr,]
479 [-localport => $localport,]
480 [-version => $version,]
481 [-domain => $domain,]
482 [-timeout => $seconds,]
483 [-retries => $count,]
484 [-maxmsgsize => $octets,]
485 [-debug => $bitmask,]
486 [-community => $community,] # v1/v2c
487 [-username => $username,] # v3
488 [-authkey => $authkey,] # v3
489 [-authpassword => $authpasswd,] # v3
490 [-authprotocol => $authproto,] # v3
491 [-privkey => $privkey,] # v3
492 [-privpassword => $privpasswd,] # v3
493 [-privprotocol => $privproto,] # v3
494 [-contextengineid => $engine_id,] # v3
495 [-contextname => $name,] # v3
496  
497 Please see the documentation for Net::SNMP for a description of these
498 parameters.
499  
500 =item SNMPv3 Arguments
501  
502 A SNMP context is a collection of management information accessible by a SNMP
503 entity. An item of management information may exist in more than one context
504 and a SNMP entity potentially has access to many contexts. The combination of
505 a contextEngineID and a contextName unambiguously identifies a context within
506 an administrative domain. In a SNMPv3 message, the contextEngineID and
507 contextName are included as part of the scopedPDU. All methods that generate
508 a SNMP message optionally take a B<-contextengineid> and B<-contextname>
509 argument to configure these fields.
510  
511 =over
512  
513 =item Context Engine ID
514  
515 The B<-contextengineid> argument expects a hexadecimal string representing
516 the desired contextEngineID. The string must be 10 to 64 characters (5 to
517 32 octets) long and can be prefixed with an optional "0x". Once the
518 B<-contextengineid> is specified it stays with the object until it is changed
519 again or reset to default by passing in the undefined value. By default, the
520 contextEngineID is set to match the authoritativeEngineID of the authoritative
521 SNMP engine.
522  
523 =item Context Name
524  
525 The contextName is passed as a string which must be 0 to 32 octets in length
526 using the B<-contextname> argument. The contextName stays with the object
527 until it is changed. The contextName defaults to an empty string which
528 represents the "default" context.
529  
530 =back
531  
532 =back
533  
534 =cut
535  
536 # [public methods] ---------------------------------------------------
537  
538 =head1 Functions
539  
540 =head2 snmpget() - send a SNMP get-request to the remote agent
541  
542 @result = snmpget(
543 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
544 [\%param_hash],
545 @oids
546 );
547  
548 This function performs a SNMP get-request query to gather data from the remote
549 agent on the host specified. The message is built using the list of OBJECT
550 IDENTIFIERs passed as an array. Each OBJECT IDENTIFIER is placed into a single
551 SNMP GetRequest-PDU in the same order that it held in the original list.
552  
553 The requested values are returned in an array in the same order as they were
554 requested. In scalar context the first requested value is returned.
555  
556 =cut
557  
558 #
559 # snmpget.
560 #
561 sub snmpget ($@) {
562 my($host, @vars) = @_;
563 my($session, @enoid, %args, $ret, $oid, @retvals);
564  
565 @retvals = ();
566 $session = &snmpopen($host, 0, \@vars);
567 if (!defined($session)) {
568 carp "SNMPGET Problem for $host"
569 unless ($Net_SNMP_util::SuppressWarnings > 1);
570 return wantarray ? @retvals : undef;
571 }
572  
573 @enoid = &toOID(@vars);
574 if ($#enoid < 0) {
575 return wantarray ? @retvals : undef;
576 }
577  
578 $args{'-varbindlist'} = \@enoid;
579 if ($Net_SNMP_util::Version > 2) {
580 $args{'-contextengineid'} = $Net_SNMP_util::ContextEngineID
581 if (defined($Net_SNMP_util::ContextEngineID));
582 $args{'-contextname'} = $Net_SNMP_util::ContextName
583 if (defined($Net_SNMP_util::ContextName));
584 }
585  
586 $ret = $session->get_request(%args);
587  
588 if ($ret) {
589 foreach $oid (@enoid) {
590 push @retvals, $ret->{$oid} if (exists($ret->{$oid}));
591 }
592 return wantarray ? @retvals : $retvals[0];
593 }
594 $ret = join(' ', @vars);
595 error_msg("SNMPGET Problem for $ret on ${host}: " . $session->error());
596 return wantarray ? @retvals : undef;
597 }
598  
599 =head2 snmpgetnext() - send a SNMP get-next-request to the remote agent
600  
601 @result = snmpgetnext(
602 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
603 [\%param_hash],
604 @oids
605 );
606  
607 This function performs a SNMP get-next-request query to gather data from the
608 remote agent on the host specified. The message is built using the list of
609 OBJECT IDENTIFIERs passed as an array. Each OBJECT IDENTIFIER is placed into a
610 single SNMP GetNextRequest-PDU in the same order that it held in the original
611 list.
612  
613 The requested values are returned in an array in the same order as they were
614 requested. The OBJECT IDENTIFIER number is added as a prefix to each value
615 using a colon as a separator, like '1.3.6.1.2.1.2.2.1.2.1:ethernet'.
616 In scalar context the first requested value is returned.
617  
618 =cut
619  
620 #
621 # snmpgetnext.
622 #
623 sub snmpgetnext ($@) {
624 my($host, @vars) = @_;
625 my($session, @enoid, %args, $ret, $oid, @retvals);
626  
627 @retvals = ();
628 $session = &snmpopen($host, 0, \@vars);
629 if (!defined($session)) {
630 carp "SNMPGETNEXT Problem for $host"
631 unless ($Net_SNMP_util::SuppressWarnings > 1);
632 return wantarray ? @retvals : undef;
633 }
634  
635 @enoid = &toOID(@vars);
636 if ($#enoid < 0) {
637 return wantarray ? @retvals : undef;
638 }
639  
640 $args{'-varbindlist'} = \@enoid;
641 if ($Net_SNMP_util::Version > 2) {
642 $args{'-contextengineid'} = $Net_SNMP_util::ContextEngineID
643 if (defined($Net_SNMP_util::ContextEngineID));
644 $args{'-contextname'} = $Net_SNMP_util::ContextName
645 if (defined($Net_SNMP_util::ContextName));
646 }
647  
648 $ret = $session->get_next_request(%args);
649  
650 if ($ret) {
651 foreach $oid (@enoid) {
652 push @retvals, $oid . ':' . $ret->{$oid} if (exists($ret->{$oid}));
653 }
654 return wantarray ? @retvals : $retvals[0];
655 }
656 $ret = join(' ', @vars);
657 error_msg("SNMPGETNEXT Problem for $ret on ${host}: " . $session->error());
658 return wantarray ? @retvals : undef;
659 }
660  
661 =head2 snmpgetbulk() - send a SNMP get-bulk-request to the remote agent
662  
663 @result = snmpgetbulk(
664 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
665 $nonrepeaters,
666 $maxrepetitions,
667 [\%param_hash],
668 @oids
669 );
670  
671 This function performs a SNMP get-bulk-request query to gather data from the
672 remote agent on the host specified.
673  
674 =over
675  
676 =item *
677  
678 The B<$nonrepeaters> value specifies the number of variables in the @oids list
679 for which a single successor is to be returned. If it is null or undefined,
680 a value of 0 is used.
681  
682 =item *
683  
684 The B<$maxrepetitions> value specifies the number of successors to be returned
685 for the remaining variables in the @oids list. If it is null or undefined,
686 the default value of 12 is used.
687  
688 =item *
689  
690 The message is built using the list of
691 OBJECT IDENTIFIERs passed as an array. Each OBJECT IDENTIFIER is placed into a
692 single SNMP GetNextRequest-PDU in the same order that it held in the original
693 list.
694  
695 =back
696  
697 The requested values are returned in an array in the same order as they were
698 requested.
699  
700 B<NOTE:> This function can only be used when the SNMP version is set to
701 SNMPv2c or SNMPv3.
702  
703 =cut
704  
705 #
706 # snmpgetbulk.
707 #
708 sub snmpgetbulk ($$$@) {
709 my($host, $nr, $mr, @vars) = @_;
710 my($session, %args, @enoid, $ret);
711 my($oid, @retvals);
712  
713 @retvals = ();
714 $session = &snmpopen($host, 0, \@vars);
715 if (!defined($session)) {
716 carp "SNMPGETBULK Problem for $host"
717 unless ($Net_SNMP_util::SuppressWarnings > 1);
718 return @retvals;
719 }
720  
721 if ($Net_SNMP_util::Version < 2) {
722 carp "SNMPGETBULK Problem for $host : must use SNMP version > 1"
723 unless ($Net_SNMP_util::SuppressWarnings > 1);
724 return @retvals;
725 }
726  
727 $args{'-nonrepeaters'} = $nr if ($nr > 0);
728 $mr = $Net_SNMP_util::MaxRepetitions if ($mr <= 0);
729 $args{'-maxrepetitions'} = $mr;
730  
731 if ($Net_SNMP_util::Version > 2) {
732 $args{'-contextengineid'} = $Net_SNMP_util::ContextEngineID
733 if (defined($Net_SNMP_util::ContextEngineID));
734 $args{'-contextname'} = $Net_SNMP_util::ContextName
735 if (defined($Net_SNMP_util::ContextName));
736 }
737  
738 @enoid = &toOID(@vars);
739 return @retvals if ($#enoid < 0);
740  
741 $args{'-varbindlist'} = \@enoid;
742 $ret = $session->get_bulk_request(%args);
743  
744 if ($ret) {
745 @enoid = &Net::SNMP::oid_lex_sort(keys %$ret);
746 foreach $oid (@enoid) {
747 push @retvals, $oid . ":" . $ret->{$oid};
748 }
749 return @retvals;
750 } else {
751 $ret = join(' ', @vars);
752 error_msg("SNMPGETBULK Problem for $ret on ${host}: " . $session->error());
753 return @retvals;
754 }
755 }
756  
757  
758 =head2 snmpwalk() - walk OBJECT IDENTIFIER tree(s) on the remote agent
759  
760 @result = snmpwalk(
761 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
762 [\%param_hash],
763 @oids
764 );
765  
766 This function performs a sequence of SNMP get-next-request or get-bulk-request
767 (if the SNMP version is 2 or higher) queries to gather data from the remote
768 agent on the host specified. The initial message is built using the list of
769 OBJECT IDENTIFIERs passed as an array. Each OBJECT IDENTIFIER is placed into a
770 single SNMP GetNextRequest-PDU in the same order that it held in the original
771 list. Queries continue until all the returned OBJECT IDENTIFIERs are no longer
772 a child of the base OBJECT IDENTIFIERs.
773  
774 The requested values are returned in an array in the same order as they were
775 requested. The OBJECT IDENTIFIER number is added as a prefix to each value
776 using a colon as a separator, like '1.3.6.1.2.1.2.2.1.2.1:ethernet'. If only
777 one OBJECT IDENTIFIER is requested, just the "instance" part of the OBJECT
778 IDENTIFIER is added as a prefix, like '1:ethernet', '2:ethernet', '3:fddi'.
779  
780 =cut
781  
782 #
783 # snmpwalk.
784 #
785 sub snmpwalk ($@) {
786 my($host, @vars) = @_;
787 return(&snmpwalk_flg($host, undef, @vars));
788 }
789  
790 =head2 snmpset() - send a SNMP set-request to the remote agent
791  
792 @result = snmpset(
793 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
794 [\%param_hash],
795 $oid1, $type1, $value1,
796 [$oid2, $type2, $value2 ...]
797 );
798  
799 This function is used to modify data on the remote agent using a SNMP
800 set-request. The message is built using the list of values consisting of groups
801 of an OBJECT IDENTIFIER, an object type, and the actual value to be set.
802 The object type can be one of the following strings:
803  
804 integer | int
805 string | octetstring | octet string
806 oid | object id | object identifier
807 ipaddr | ip addr4ess
808 timeticks
809 uint | uinteger | uinteger32 | unsigned int | unsigned integer | unsigned integer32
810 counter | counter 32
811 counter64
812 gauge | gauge32
813  
814 The object type may also be an octet corresponding to the ASN.1 type. See
815 the Net::SNMP documentation for more information.
816  
817 The requested values are returned in an array in the same order as they were
818 requested. In scalar context the first requested value is returned.
819  
820 =cut
821  
822 #
823 # snmpset.
824 #
825 sub snmpset($@) {
826 my($host, @vars) = @_;
827 my($session, @vals, %args, $ret);
828 my($oid, $type, $value, @enoid, @retvals);
829  
830 @retvals = ();
831 $session = &snmpopen($host, 0, \@vars);
832 if (!defined($session)) {
833 carp "SNMPSET Problem for $host"
834 unless ($Net_SNMP_util::SuppressWarnings > 1);
835 return wantarray ? @retvals : undef;
836 }
837  
838 if ($Net_SNMP_util::Version > 2) {
839 $args{'-contextengineid'} = $Net_SNMP_util::ContextEngineID
840 if (defined($Net_SNMP_util::ContextEngineID));
841 $args{'-contextname'} = $Net_SNMP_util::ContextName
842 if (defined($Net_SNMP_util::ContextName));
843 }
844  
845 while(@vars) {
846 ($oid) = toOID((shift @vars));
847 $ret = shift @vars;
848 $value = shift @vars;
849 $type = ASNtype($ret);
850 if (!defined($type)) {
851 carp "Unknown SNMP type: $type\n"
852 unless ($Net_SNMP_util::SuppressWarnings > 1);
853 }
854 push @vals, $oid, $type, $value;
855 push @enoid, $oid;
856 }
857 if ($#vals < 0) {
858 return wantarray ? @retvals : undef;
859 }
860  
861 $args{'-varbindlist'} = \@vals;
862  
863 $ret = $session->set_request(%args);
864 if ($ret) {
865 foreach $oid (@enoid) {
866 push @retvals, $ret->{$oid} if (exists($ret->{$oid}));
867 }
868 return wantarray ? @retvals : $retvals[0];
869 }
870 $ret = join(' ', @enoid);
871 error_msg("SNMPSET Problem for $ret on ${host}: " . $session->error());
872 return wantarray ? @retvals : undef;
873 }
874  
875 =head2 snmptrap() - send a SNMP trap to the remote manager
876  
877 @result = snmptrap(
878 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
879 $enterprise,
880 $agentaddr,
881 $generictrap,
882 $specifictrap,
883 [\%param_hash],
884 $oid1, $type1, $value1,
885 [$oid2, $type2, $value2 ...]
886 );
887  
888 This function sends a SNMP trap to the remote manager on the host specified.
889 The message is built using the list of values consisting of groups of an
890 OBJECT IDENTIFIER, an object type, and the actual value to be set.
891 The object type can be one of the following strings:
892  
893 integer | int
894 string | octetstring | octet string
895 oid | object id | object identifier
896 ipaddr | ip addr4ess
897 timeticks
898 uint | uinteger | uinteger32 | unsigned int | unsigned integer | unsigned integer32
899 counter | counter 32
900 counter64
901 gauge | gauge32
902  
903 The object type may also be an octet corresponding to the ASN.1 type. See
904 the Net::SNMP documentation for more information.
905  
906 A true value is returned if sending the trap is successful. The undefined value
907 is returned when a failure has occurred.
908  
909 When the trap is sent as SNMPv2c, the B<$enterprise>, B<$agentaddr>,
910 B<$generictrap>, and B<$specifictrap> arguments are ignored. Furthermore,
911 the first two (oid, type, value) tuples should be:
912  
913 =over
914  
915 =item *
916  
917 sysUpTime.0 - ('1.3.6.1.2.1.1.3.0', 'timeticks', $timeticks)
918  
919 =item *
920  
921 snmpTrapOID.0 - ('1.3.6.1.6.3.1.1.4.1.0', 'oid', $oid)
922  
923 =back
924  
925 B<NOTE:> This function can only be used when the SNMP version is set to
926 SNMPv1 or SNMPv2c.
927  
928 =cut
929  
930 #
931 # Send an SNMP trap
932 #
933 sub snmptrap($$$$$@) {
934 my($host, $ent, $agent, $gen, $spec, @vars) = @_;
935 my($oid, $type, $value, $ret, @enoid, @vals);
936 my($session, %args);
937  
938 $session = &snmpopen($host, 1, \@vars);
939 if (!defined($session)) {
940 carp "SNMPTRAP Problem for $host"
941 unless ($Net_SNMP_util::SuppressWarnings > 1);
942 return undef;
943 }
944  
945 if ($Net_SNMP_util::Version == 1) {
946 $args{'-enterprise'} = $ent if (defined($ent) and (length($ent) > 0));
947 $args{'-agentaddr'} = $agent if (defined($agent) and (length($agent) > 0));
948 $args{'-generictrap'} = $gen if (defined($gen) and (length($gen) > 0));
949 $args{'-specifictrap'} = $spec if (defined($spec) and (length($spec) > 0));
950 } elsif ($Net_SNMP_util::Version > 2) {
951 carp "SNMPTRAP Problem for $host : must use SNMP version 1 or 2"
952 unless ($Net_SNMP_util::SuppressWarnings > 1);
953 }
954  
955 while(@vars) {
956 ($oid) = toOID((shift @vars));
957 $ret = shift @vars;
958 $value = shift @vars;
959 $type = ASNtype($ret);
960 if (!defined($type)) {
961 carp "unknown SNMP type: $type"
962 unless ($Net_SNMP_util::SuppressWarnings > 1);
963 }
964 push @vals, $oid, $type, $value;
965 push @enoid, $oid;
966 }
967 return undef unless defined $vals[0];
968  
969 $args{'-varbindlist'} = \@vals;
970  
971 if ($Net_SNMP_util::Version == 1) {
972 $ret = $session->trap_request(%args);
973 } else {
974 $ret = $session->snmpv2_trap(%args);
975 }
976  
977 if (!$ret) {
978 $ret = join(' ', @enoid);
979 error_msg("SNMPTRAP Problem for $ret on ${host}: " . $session->error());
980 }
981 return $ret;
982 }
983  
984 =head2 snmpmaptable() - walk OBJECT IDENTIFIER tree(s) on the remote agent
985  
986 $result = snmpmaptable(
987 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
988 \&function,
989 [\%param_hash],
990 @oids
991 );
992  
993 This function performs a sequence of SNMP get-next-request or get-bulk-request
994 (if the SNMP version is 2 or higher) queries to gather data from the remote
995 agent on the host specified. The initial message is built using the list of
996 OBJECT IDENTIFIERs passed as an array. Each OBJECT IDENTIFIER is placed into a
997 single SNMP GetNextRequest-PDU in the same order that it held in the original
998 list. Queries continue until all the returned OBJECT IDENTIFIERs are no longer
999 a child of the base OBJECT IDENTIFIERs. The OBJECT IDENTIFIERs must correspond
1000 to column entries for a conceptual row in a table. They may however be columns
1001 in different tables as long as each table is indexed the same way.
1002  
1003 =over
1004  
1005 =item *
1006  
1007 The B<\&function> argument will be called once per row of the table. It
1008 will be passed the row index as a partial OBJECT IDENTIFIER in dotted notation,
1009 e.g. "1.3" or "10.0.1.34", and the values of the requested table columns in
1010 that row.
1011  
1012 =back
1013  
1014 The number of rows in the table is returned on success. The undefined value
1015 is returned when a failure has occurred.
1016  
1017 =cut
1018  
1019 #
1020 # walk a table, calling a user-supplied function for each
1021 # column of a table.
1022 #
1023 sub snmpmaptable($$@) {
1024 my($host, $fun, @vars) = @_;
1025 return snmpmaptable4($host, $fun, 0, @vars);
1026 }
1027  
1028 =head2 snmpmaptable4() - walk OBJECT IDENTIFIER tree(s) on the remote agent
1029  
1030 $result = snmpmaptable4(
1031 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
1032 \&function,
1033 $maxrepetitions,
1034 [\%param_hash],
1035 @oids
1036 );
1037  
1038 This function performs a sequence of SNMP get-next-request or get-bulk-request
1039 (if the SNMP version is 2 or higher) queries to gather data from the remote
1040 agent on the host specified. The initial message is built using the list of
1041 OBJECT IDENTIFIERs passed as an array. Each OBJECT IDENTIFIER is placed into a
1042 single SNMP GetNextRequest-PDU in the same order that it held in the original
1043 list. Queries continue until all the returned OBJECT IDENTIFIERs are no longer
1044 a child of the base OBJECT IDENTIFIERs. The OBJECT IDENTIFIERs must correspond
1045 to column entries for a conceptual row in a table. They may however be columns
1046 in different tables as long as each table is indexed the same way.
1047  
1048 =over
1049  
1050 =item *
1051  
1052 The B<\&function> argument will be called once per row of the table. It
1053 will be passed the row index as a partial OBJECT IDENTIFIER in dotted notation,
1054 e.g. "1.3" or "10.0.1.34", and the values of the requested table columns in
1055 that row.
1056  
1057 =item *
1058  
1059 The B<$maxrepetitions> argument specifies the number of rows to be returned
1060 by a single get-bulk-request. If it is null or undefined, the default value
1061 of 12 is used.
1062  
1063 =back
1064  
1065 The number of rows in the table is returned on success. The undefined value
1066 is returned when a failure has occurred.
1067  
1068 =cut
1069  
1070 sub snmpmaptable4($$$@) {
1071 my($host, $fun, $max_reps, @vars) = @_;
1072 my($session, @enoid, %args, $ret);
1073 my($oid, $soid, $toid, $inst, @row, $nr);
1074  
1075 $session = &snmpopen($host, 0, \@vars);
1076 if (!defined($session)) {
1077 carp "SNMPMAPTABLE Problem for $host"
1078 unless ($Net_SNMP_util::SuppressWarnings > 1);
1079 return undef;
1080 }
1081  
1082 @enoid = toOID(@vars);
1083 return undef unless defined $enoid[0];
1084  
1085 if ($Net_SNMP_util::Version > 1) {
1086 $max_reps = $Net_SNMP_util::MaxRepetitions if ($max_reps <= 0);
1087 $args{'-maxrepetitions'} = $max_reps;
1088 }
1089 if ($Net_SNMP_util::Version > 2) {
1090 $args{'-contextengineid'} = $Net_SNMP_util::ContextEngineID
1091 if (defined($Net_SNMP_util::ContextEngineID));
1092 $args{'-contextname'} = $Net_SNMP_util::ContextName
1093 if (defined($Net_SNMP_util::ContextName));
1094 }
1095  
1096 $args{'-columns'} = \@enoid;
1097  
1098 $ret = $session->get_entries(%args);
1099  
1100 if ($ret) {
1101 $soid = $enoid[0];
1102 $nr = 0;
1103 foreach $oid (&Net::SNMP::oid_lex_sort(keys %$ret)) {
1104 if (&Net::SNMP::oid_base_match($soid, $oid)) {
1105 $inst = substr($oid, length($soid)+1);
1106 undef @row;
1107 foreach $toid (@enoid) {
1108 push @row, $ret->{$toid . "." . $inst};
1109 }
1110 &$fun($inst, @row);
1111 $nr++;
1112 } else {
1113 return($nr) if ($nr > 0);
1114 }
1115 }
1116 return($nr);
1117 } else {
1118 $ret = join(' ', @vars);
1119 error_msg("SNMPMAPTABLE Problem for $ret on ${host}: " . $session->error());
1120 return undef;
1121 }
1122 }
1123  
1124 =head2 snmpwalkhash() - send a SNMP get-next-request to the remote agent
1125  
1126 @result = snmpwalkhash(
1127 [community@]host[:port[:timeout[:retries[:backoff[:version]]]]],
1128 \&function(),
1129 [\%param_hash],
1130 @oids,
1131 [\%hash]
1132 );
1133  
1134 This function performs a sequence of SNMP get-next-request or get-bulk-request
1135 (if the SNMP version is 2 or higher) queries to gather data from the remote
1136 agent on the host specified. The message is built using the list of
1137 OBJECT IDENTIFIERs passed as an array. Each OBJECT IDENTIFIER is placed into a
1138 single SNMP GetNextRequest-PDU in the same order that it held in the original
1139 list. Queries continue until all the returned OBJECT IDENTIFIERs are outside
1140 of the tree specified by the initial OBJECT IDENTIFIERs.
1141  
1142 The B<\&function> is called once for every returned value. It is passed a
1143 reference to a hash, the hostname, the textual OBJECT IDENTIFIER, the
1144 dotted-numberic OBJECT IDENTIFIER, the instance, the value and the requested
1145 textual OBJECT IDENTIFIER. That function can customize the result so the
1146 values can be extracted later by hosts, by oid_names, by oid_numbers,
1147 by instances... like these:
1148  
1149 $hash{$host}{$name}{$inst} = $value;
1150 $hash{$host}{$oid}{$inst} = $value;
1151 $hash{$name}{$inst} = $value;
1152 $hash{$oid}{$inst} = $value;
1153 $hash{$oid . '.' . $ints} = $value;
1154 $hash{$inst} = $value;
1155 ...
1156  
1157 If the last argument to B<snmpwalkhash> is a reference to a hash, that hash
1158 reference is passed to the passed-in function instead of a local hash
1159 reference. That way the function can look up other objects unrelated
1160 to the current invocation of B<snmpwalkhash>.
1161  
1162 The snmpwalkhash routine returns the hash.
1163  
1164 =cut
1165  
1166 #
1167 # Walk the MIB, putting everything you find into hashes.
1168 #
1169 sub snmpwalkhash($$@) {
1170 # my($host, $hash_sub, @vars) = @_;
1171 return(&snmpwalk_flg( @_ ));
1172 }
1173  
1174  
1175 =head2 snmpmapOID() - add textual OBJECT INDENTIFIER mapping
1176  
1177 snmpmapOID(
1178 $text1, $oid1,
1179 [ $text2, $oid2 ...]
1180 );
1181  
1182 This routine adds entries to the table that maps textual representation of
1183 OBJECT IDENTIFIERs to their dotted notation. For example,
1184  
1185 snmpmapOID('ciscoCPU', '1.3.6.1.4.1.9.9.109.1.1.1.1.5.1');
1186  
1187 allows the string 'ciscoCPU' to be used as an OBJECT IDENTIFIER in any SNMP
1188 query routine.
1189  
1190 This routine doesn't return anything.
1191  
1192 =cut
1193  
1194 #
1195 # Add passed-in text, OID pairs to the OID mapping table.
1196 #
1197 sub snmpmapOID(@)
1198 {
1199 my(@vars) = @_;
1200 my($oid, $txt);
1201  
1202 $Net_SNMP_util::ErrorMessage = '';
1203 while($#vars >= 0) {
1204 $txt = shift @vars;
1205 $oid = shift @vars;
1206  
1207 next unless($txt =~ /^[a-zA-Z][\w\-]*(\.[a-zA-Z][\w\-])*$/);
1208 next unless($oid =~ /^\d+(\.\d+)*$/);
1209  
1210 $Net_SNMP_util::OIDS{$txt} = $oid;
1211 $RevNeeded = 1;
1212 print "snmpmapOID: $txt => $oid\n" if $Net_SNMP_util::Debug;
1213 }
1214  
1215 return undef;
1216 }
1217  
1218 =head2 snmpLoad_OID_Cache() - Read a file of cached OID mappings
1219  
1220 $result = snmpLoad_OID_Cache(
1221 $file
1222 );
1223  
1224 This routine opens the file named by the B<$file> argument and reads it.
1225 The file should contain text, OBJECT IDENTIFIER pairs, one pair
1226 per line. It adds the pairs as entries to the table that maps textual
1227 representation of OBJECT IDENTIFIERs to their dotted notation.
1228 Blank lines and anything after a '#' or between '--' is ignored.
1229  
1230 This routine returns 0 on success and -1 if the B<$file> could not be opened.
1231  
1232 =cut
1233  
1234 #
1235 # Open the passed-in file name and read it in to populate
1236 # the cache of text-to-OID map table. It expects lines
1237 # with two fields, the first the textual string like "ifInOctets",
1238 # and the second the OID value, like "1.3.6.1.2.1.2.2.1.10".
1239 #
1240 # blank lines and anything after a '#' or between '--' is ignored.
1241 #
1242 sub snmpLoad_OID_Cache ($) {
1243 my($arg) = @_;
1244 my($txt, $oid);
1245  
1246 $Net_SNMP_util::ErrorMessage = '';
1247 if (!open(CACHE, $arg)) {
1248 error_msg("snmpLoad_OID_Cache: Can't open ${arg}: $!");
1249 return -1;
1250 }
1251  
1252 while(<CACHE>) {
1253 s/#.*//; # '#' starts a comment
1254 s/--.*?--/ /g; # comment delimited by '--', like MIBs
1255 s/--.*//; # comment started by '--'
1256 next if (/^$/);
1257 next unless (/\s/); # must have whitespace as separator
1258 chomp;
1259 ($txt, $oid) = split(' ', $_, 2);
1260 $txt = $1 if ($txt =~ /^[\'\"](.*)[\'\"]/);
1261 $oid = $1 if ($oid =~ /^[\'\"](.*)[\'\"]/);
1262 if (($txt =~ /^\.?\d+(\.\d+)*\.?$/)
1263 and ($oid !~ /^\.?\d+(\.\d+)*\.?$/)) {
1264 my($a) = $oid;
1265 $oid = $txt;
1266 $txt = $a;
1267 }
1268 $oid =~ s/^\.//;
1269 $oid =~ s/\.$//;
1270 &snmpmapOID($txt, $oid);
1271 }
1272 close(CACHE);
1273 return 0;
1274 }
1275  
1276 =head2 snmpMIB_to_OID() - Read a MIB file for textual OID mappings
1277  
1278 $result = snmpMIB_to_OID(
1279 $file
1280 );
1281  
1282 This routine opens the file named by the B<$file> argument and reads it.
1283 The file should be an SNMP Management Information Base (MIB) file
1284 that describes OBJECT IDENTIFIERs supported by an SNMP agent.
1285 per line. It adds the textual representation of the OBJECT IDENTIFIERs
1286 to the text-to-OID mapping table.
1287  
1288 This routine returns the number of entries added to the table or -1 if
1289 the B<$file> could not be opened.
1290  
1291 =cut
1292  
1293 #
1294 # Read in the passed MIB file, parsing it
1295 # for their text-to-OID mappings
1296 #
1297 sub snmpMIB_to_OID ($) {
1298 my($arg) = @_;
1299 my($cnt, $quote, $buf, %tOIDs, $tgot);
1300 my($var, @parts, $strt, $indx, $ind, $val);
1301  
1302 $Net_SNMP_util::ErrorMessage = '';
1303 if (!open(MIB, $arg)) {
1304 error_msg("snmpMIB_to_OID: Can't open ${arg}: $!");
1305 return -1;
1306 }
1307 print "snmpMIB_to_OID: loading $arg\n" if $Net_SNMP_util::Debug;
1308 $cnt = 0;
1309 $quote = 0;
1310 $tgot = 0;
1311 $buf = '';
1312 while(<MIB>) {
1313 if ($quote) {
1314 next unless /"/;
1315 $quote = 0;
1316 }
1317 chomp;
1318 $buf .= ' ' . $_;
1319  
1320 $buf =~ s/"[^"]*"//g; # throw away quoted strings
1321 $buf =~ s/--.*?--/ /g; # throw away comments (-- anything --)
1322 $buf =~ s/--.*//; # throw away comments (-- anything to EOL)
1323 $buf =~ s/\s+/ /g; # clean up multiple spaces
1324  
1325 if ($buf =~ /"/) {
1326 $quote = 1;
1327 next;
1328 }
1329  
1330 if ($buf =~ /DEFINITIONS *::= *BEGIN/) {
1331 $cnt += MIB_fill_OID(\%tOIDs) if ($tgot);
1332 $buf = '';
1333 %tOIDs = ();
1334 $tgot = 0;
1335 next;
1336 }
1337 $buf =~ s/OBJECT-TYPE/OBJECT IDENTIFIER/;
1338 $buf =~ s/OBJECT-IDENTITY/OBJECT IDENTIFIER/;
1339 $buf =~ s/OBJECT-GROUP/OBJECT IDENTIFIER/;
1340 $buf =~ s/MODULE-IDENTITY/OBJECT IDENTIFIER/;
1341 $buf =~ s/NOTIFICATION-TYPE/OBJECT IDENTIFIER/;
1342 $buf =~ s/ IMPORTS .*\;//;
1343 $buf =~ s/ SEQUENCE *{.*}//;
1344 $buf =~ s/ SYNTAX .*//;
1345 $buf =~ s/ [\w\-]+ *::= *OBJECT IDENTIFIER//;
1346 $buf =~ s/ OBJECT IDENTIFIER.*::= *{/ OBJECT IDENTIFIER ::= {/;
1347  
1348 if ($buf =~ / ([\w\-]+) OBJECT IDENTIFIER *::= *{([^}]+)}/) {
1349 $var = $1;
1350 $buf = $2;
1351 $buf =~ s/ +$//;
1352 $buf =~ s/\s+\(/\(/g; # remove spacing around '('
1353 $buf =~ s/\(\s+/\(/g;
1354 $buf =~ s/\s+\)/\)/g; # remove spacing before ')'
1355 @parts = split(' ', $buf);
1356 $strt = '';
1357 foreach $indx (@parts) {
1358 if ($indx =~ /([\w\-]+)\((\d+)\)/) {
1359 $ind = $1;
1360 $val = $2;
1361 if (exists($tOIDs{$strt})) {
1362 $tOIDs{$ind} = $tOIDs{$strt} . '.' . $val;
1363 } elsif ($strt ne '') {
1364 $tOIDs{$ind} = "${strt}.${val}";
1365 } else {
1366 $tOIDs{$ind} = $val;
1367 }
1368 $strt = $ind;
1369 $tgot = 1;
1370 } elsif ($indx =~ /^\d+$/) {
1371 if (exists($tOIDs{$strt})) {
1372 $tOIDs{$var} = $tOIDs{$strt} . '.' . $indx;
1373 } else {
1374 $tOIDs{$var} = "${strt}.${indx}";
1375 }
1376 $tgot = 1;
1377 } else {
1378 $strt = $indx;
1379 }
1380 }
1381 $buf = '';
1382 }
1383 }
1384 $cnt += MIB_fill_OID(\%tOIDs) if ($tgot);
1385 $RevNeeded = 1 if ($cnt > 0);
1386 return $cnt;
1387 }
1388  
1389 =head2 snmpQueue_MIB_File() - queue a MIB file for reading "on demand"
1390  
1391 snmpQueue_MIB_File(
1392 $file1,
1393 [$file2, ...]
1394 );
1395  
1396 This routine queues the list of SNMP MIB files for later processing.
1397 Whenever a text-to-OBJECT IDENTIFIER lookup fails, the list of queued MIB
1398 files is consulted. If it isn't empty, the first MIB file in the list is
1399 removed and passed to B<snmpMIB_to_OID()>. The lookup is attempted again,
1400 and if that still fails the next MIB file in the list is removed and passed
1401 to B<snmpMIB_to_OID()>. This process continues until the lookup succeeds
1402 or the list is exhausted.
1403  
1404 This routine doesn't return anything.
1405  
1406 =cut
1407  
1408 #
1409 # Save the passed-in list of MIB files until an OID can't be
1410 # found in the existing table. At that time the MIB file will
1411 # be loaded, and the lookup attempted again.
1412 #
1413 sub snmpQueue_MIB_File (@) {
1414 my(@files) = @_;
1415 my($file);
1416  
1417 $Net_SNMP_util::ErrorMessage = '';
1418 foreach $file (@files) {
1419 push(@Net_SNMP_util::MIB_Files, $file);
1420 }
1421 }
1422  
1423 # [private methods] -------------------------------------
1424  
1425 #
1426 # Start an snmp session
1427 #
1428 sub snmpopen ($$$) {
1429 my($host, $type, $vars) = @_;
1430 my($nhost, $port, $community, $lhost, $lport, $nlhost);
1431 my($timeout, $retries, $backoff, $version, $v4onlystr);
1432 my($opts, %args, $tmp, $sess);
1433 my($debug, $maxmsgsize);
1434  
1435 $type = 0 if (!defined($type));
1436 $community = "public";
1437 $nlhost = "";
1438  
1439 ($community, $host) = ($1, $2) if ($host =~ /^(.*)@([^@]+)$/);
1440  
1441 # We can't split on the : character because a numeric IPv6
1442 # address contains a variable number of :'s
1443 if( ($host =~ /^(\[.*\]):(.*)$/) or ($host =~ /^(\[.*\])$/) ) {
1444 # Numeric IPv6 address between []
1445 ($host, $opts) = ($1, $2);
1446 } else {
1447 # Hostname or numeric IPv4 address
1448 ($host, $opts) = split(':', $host, 2);
1449 }
1450 ($port, $timeout, $retries, $backoff, $version, $v4onlystr)
1451 = split(':', $opts, 6) if(defined($opts) and (length $opts > 0) );
1452  
1453 undef($timeout) if (defined($timeout) and length($timeout) <= 0);
1454 undef($retries) if (defined($retries) and length($retries) <= 0);
1455 undef($backoff) if (defined($backoff) and length($backoff) <= 0);
1456 undef($version) if (defined($version) and length($version) <= 0);
1457  
1458 $v4onlystr = "" unless defined $v4onlystr;
1459  
1460 if (defined($port) and ($port =~ /^([^!]*)!(.*)$/)) {
1461 ($port, $lhost) = ($1, $2);
1462 $nlhost = $lhost;
1463 ($lhost, $lport) = ($1, $2) if ($lhost =~ /^(.*)!(.*)$/);
1464 undef($lport) if (defined($lport) and (length($lport) <= 0));
1465 }
1466 undef($port) if (defined($port) and length($port) <= 0);
1467  
1468 if (ref $vars->[0] eq 'HASH') {
1469 undef($debug);
1470 undef($maxmsgsize);
1471 undef $Net_SNMP_util::ContextEngineID;
1472 undef $Net_SNMP_util::ContextName;
1473 $opts = shift @$vars;
1474 foreach $type (keys %$opts) {
1475 if ($type =~ /^-?return_array_refs$/i) {
1476 $Net_SNMP_util::ReturnArrayRefs = $opts->{$type};
1477 } elsif ($type =~ /^-?return_hash_refs$/i) {
1478 $Net_SNMP_util::ReturnHashRefs = $opts->{$type};
1479 } elsif ($type =~ /^-?contextengineid$/i) {
1480 $Net_SNMP_util::ContextEngineID = $opts->{$type};
1481 } elsif ($type =~ /^-?contextname$/i) {
1482 $Net_SNMP_util::ContextName = $opts->{$type};
1483 } elsif ($type =~ /^-?maxrepetitions$/i) {
1484 $Net_SNMP_util::MaxRepetitions = $opts->{$type};
1485 } elsif ($type =~ /^-?default_max_repetitions$/i) {
1486 $Net_SNMP_util::MaxRepetitions = $opts->{$type};
1487 } elsif ($type =~ /^-?version$/i) {
1488 $version = $opts->{$type};
1489 } elsif ($type =~ /^-?port$/i) {
1490 $port = $opts->{$type};
1491 } elsif ($type =~ /^-?localaddr$/i) {
1492 $lhost = $opts->{$type};
1493 } elsif ($type =~ /^-?community$/i) {
1494 $community = $opts->{$type};
1495 } elsif ($type =~ /^-?timeout$/i) {
1496 $timeout = $opts->{$type};
1497 } elsif ($type =~ /^-?retries$/i) {
1498 $retries = $opts->{$type};
1499 } elsif ($type =~ /^-?maxmsgsize$/i) {
1500 $maxmsgsize = $opts->{$type};
1501 } elsif ($type =~ /^-?debug$/i) {
1502 $debug = $opts->{$type};
1503 } elsif ($type =~ /^-?backoff$/i) {
1504 next; # XXXX not implemented in Net::SNMP
1505 } elsif ($type =~ /^-?avoid_negative_request_ids$/i) {
1506 next; # XXXX not implemented in Net::SNMP
1507 } elsif ($type =~ /^-?lenient_source_/i) {
1508 next; # XXXX not implemented in Net::SNMP
1509 } elsif ($type =~ /^-?use_16bit_request_ids$/i) {
1510 next; # XXXX not implemented in Net::SNMP
1511 } elsif ($type =~ /^-?use_getbulk$/i) {
1512 next; # XXXX not implemented in Net::SNMP
1513 } else {
1514 $tmp = $type;
1515 $tmp = '-' . $tmp unless ($tmp =~ /^-/);
1516 $args{$tmp} = $opts->{$type};
1517 }
1518 }
1519 }
1520  
1521 $port = 162 if ($type == 1 and !defined($port));
1522 $nhost = "$community\@$host";
1523 $nhost .= ":" . $port if (defined($port));
1524 undef($lhost) if (defined($lhost) and (length($lhost) <= 0));
1525  
1526 $version = '1' unless defined $version;
1527 if ($version =~ /1/) {
1528 $version = 1;
1529 } elsif ($version =~ /2/) {
1530 $version = 2;
1531 } elsif ($version =~ /3/) {
1532 $version = 3;
1533 }
1534 $Net_SNMP_util::ErrorMessage = '';
1535 if ((!defined($Net_SNMP_util::Session))
1536 or ($Net_SNMP_util::Host ne $nhost)
1537 or ($Net_SNMP_util::Version ne $version)
1538 or ($Net_SNMP_util::LHost ne $nlhost)
1539 or ($Net_SNMP_util::IPv4only ne $v4onlystr)) {
1540 if (defined($Net_SNMP_util::Session)) {
1541 $Net_SNMP_util::Session->close();
1542 undef $Net_SNMP_util::Session;
1543 undef $Net_SNMP_util::Host;
1544 undef $Net_SNMP_util::Version;
1545 undef $Net_SNMP_util::LHost;
1546 undef $Net_SNMP_util::IPv4only;
1547 }
1548  
1549 $args{'-hostname'} = $host;
1550 $args{'-port'} = $port if (defined($port));
1551 $args{'-localaddr'} = $lhost if (defined($lhost));
1552 $args{'-localport'} = $lport if (defined($lport));
1553 $args{'-version'} = $version;
1554 $args{'-domain'} = "udp/ipv4" if (length($v4onlystr) > 0);
1555 $args{'-timeout'} = $timeout if (defined($timeout));
1556 $args{'-retries'} = $retries if (defined($retries));
1557 $args{'-maxmsgsize'} = $maxmsgsize if (defined($maxmsgsize));
1558 $args{'-debug'} = $debug if (defined($debug));
1559 $args{'-community'} = $community unless ($community eq "public");
1560 if ($version == 3) {
1561 delete $args{'-community'}
1562 } else {
1563 delete $args{'-username'};
1564 delete $args{'-authkey'};
1565 delete $args{'-authpassword'};
1566 delete $args{'-authprotocol'};
1567 delete $args{'-privkey'};
1568 delete $args{'-privpassword'};
1569 delete $args{'-privprotocol'};
1570 }
1571  
1572 ($sess, $tmp) = Net::SNMP->session(%args);
1573  
1574 if (defined($sess)) {
1575 $Net_SNMP_util::Session = $sess;
1576 $Net_SNMP_util::Host = $nhost;
1577 $Net_SNMP_util::Version = $version;
1578 $Net_SNMP_util::LHost = $nlhost;
1579 $Net_SNMP_util::IPv4only = $v4onlystr;
1580 } else {
1581 error_msg("SNMPopen failed: $tmp\n");
1582 return(undef);
1583 }
1584 return $Net_SNMP_util::Session;
1585 } else {
1586 $Net_SNMP_util::Session->timeout($timeout)
1587 if (defined($timeout) and (length($timeout) > 0));
1588 $Net_SNMP_util::Session->retries($retries)
1589 if (defined($retries) and (length($retries) > 0));
1590 $Net_SNMP_util::Session->maxmsgsize($maxmsgsize)
1591 if (defined($maxmsgsize) and (length($maxmsgsize) > 0));
1592 $Net_SNMP_util::Session->debug($debug)
1593 if (defined($debug) and (length($debug) > 0));
1594 $Net_SNMP_util::Session->{_context_engine_id} = undef
1595 if (!defined($Net_SNMP_util::ContextEngineID));
1596 $Net_SNMP_util::Session->{_context_name} = undef
1597 if (!defined($Net_SNMP_util::ContextName));
1598 }
1599 return $Net_SNMP_util::Session;
1600 }
1601  
1602 #
1603 # Given an OID in either ASN.1 or mixed text/ASN.1 notation, return an OID.
1604 #
1605 sub toOID(@) {
1606 my(@vars) = @_;
1607 my($oid, $var, $tmp, $tmpv, @retvar);
1608  
1609 @retvar = ();
1610 foreach $var (@vars) {
1611 ($oid, $tmp) = &Check_OID($var);
1612 if (!$oid and $Net_SNMP_util::CacheLoaded == 0) {
1613 $tmp = $Net_SNMP_util::SuppressWarnings;
1614 $Net_SNMP_util::SuppressWarnings = 1000;
1615  
1616 &snmpLoad_OID_Cache($Net_SNMP_util::CacheFile);
1617  
1618 $Net_SNMP_util::CacheLoaded = 1;
1619 $Net_SNMP_util::SuppressWarnings = $tmp;
1620  
1621 ($oid, $tmp) = &Check_OID($var);
1622 }
1623 while (!$oid and $#Net_SNMP_util::MIB_Files >= 0) {
1624 $tmp = $Net_SNMP_util::SuppressWarnings;
1625 $Net_SNMP_util::SuppressWarnings = 1000;
1626  
1627 snmpMIB_to_OID(shift(@Net_SNMP_util::MIB_Files));
1628  
1629 $Net_SNMP_util::SuppressWarnings = $tmp;
1630  
1631 ($oid, $tmp) = &Check_OID($var);
1632 if ($oid) {
1633 open(CACHE, ">>$Net_SNMP_util::CacheFile");
1634 print CACHE "$tmp\t$oid\n";
1635 close(CACHE);
1636 }
1637 }
1638 if ($oid) {
1639 $var =~ s/^$tmp/$oid/;
1640 } else {
1641 carp("Unknown SNMP var $var\n")
1642 unless ($Net_SNMP_util::SuppressWarnings > 1);
1643 next;
1644 }
1645 while ($var =~ /\"([^\"]*)\"/) {
1646 $tmp = sprintf("%d.%s", length($1), join(".", map(ord, split(//, $1))));
1647 $var =~ s/\"$1\"/$tmp/;
1648 }
1649 print "toOID: $var\n" if $Net_SNMP_util::Debug;
1650 push(@retvar, $var);
1651 }
1652 return @retvar;
1653 }
1654  
1655 #
1656 # Check to see if an OID is in the text-to-OID cache.
1657 # Returns the OID and the corresponding text as two separate
1658 # elements.
1659 #
1660 sub Check_OID ($) {
1661 my($var) = @_;
1662 my($tmp, $tmpv, $oid);
1663  
1664 if ($var =~ /^[a-zA-Z][\w\-]*(\.[a-zA-Z][\w\-]*)*/) {
1665 $tmp = $&;
1666 $tmpv = $tmp;
1667 for (;;) {
1668 last if exists($Net_SNMP_util::OIDS{$tmpv});
1669 last if !($tmpv =~ s/^[^\.]*\.//);
1670 }
1671 $oid = $Net_SNMP_util::OIDS{$tmpv};
1672 if ($oid) {
1673 return ($oid, $tmp);
1674 } else {
1675 my @empty = ();
1676 return @empty;
1677 }
1678 }
1679 return ($var, $var);
1680 }
1681  
1682 sub snmpwalk_flg ($$@) {
1683 my($host, $hash_sub, @vars) = @_;
1684 my($session, %args, @enoid, @poid, $toid, $oid, $got);
1685 my($val, $ret, %soid, %nsoid, @retvals, $tmp);
1686 my(%rethash, $h_ref, @tmprefs);
1687 my($stop);
1688  
1689 $h_ref = (ref $vars[$#vars] eq "HASH") ? pop(@vars) : \%rethash;
1690  
1691 $session = &snmpopen($host, 0, \@vars);
1692 if (!defined($session)) {
1693 carp "SNMPWALK Problem for $host"
1694 unless ($Net_SNMP_util::SuppressWarnings > 1);
1695 if (defined($hash_sub)) {
1696 return ($h_ref) if ($SNMP_util::Return_hash_refs);
1697 return (%$h_ref);
1698 } else {
1699 @retvals = ();
1700 return (@retvals);
1701 }
1702 }
1703  
1704 @enoid = toOID(@vars);
1705 if ($#enoid < 0) {
1706 if (defined($hash_sub)) {
1707 return ($h_ref) if ($SNMP_util::Return_hash_refs);
1708 return (%$h_ref);
1709 } else {
1710 @retvals = ();
1711 return (@retvals);
1712 }
1713 }
1714  
1715 #
1716 # Create/Refresh a reversed hash with oid -> name
1717 #
1718 if (defined($hash_sub) and ($RevNeeded)) {
1719 %revOIDS = reverse %Net_SNMP_util::OIDS;
1720 $RevNeeded = 0;
1721 }
1722  
1723 #
1724 # Create temporary array of refs to return values
1725 #
1726 foreach $oid (0..$#enoid) {
1727 my $tmparray = [];
1728 $tmprefs[$oid] = $tmparray;
1729 $nsoid{$oid} = $oid;
1730 }
1731  
1732 $got = 0;
1733 @poid = @enoid;
1734  
1735 if ($Net_SNMP_util::Version > 1 and $Net_SNMP_util::MaxRepetitions > 0) {
1736 $args{'-maxrepetitions'} = $Net_SNMP_util::MaxRepetitions;
1737 }
1738 if ($Net_SNMP_util::Version > 2) {
1739 $args{'-contextengineid'} = $Net_SNMP_util::ContextEngineID
1740 if (defined($Net_SNMP_util::ContextEngineID));
1741 $args{'-contextname'} = $Net_SNMP_util::ContextName
1742 if (defined($Net_SNMP_util::ContextName));
1743 }
1744  
1745 while($#poid >= 0) {
1746 $args{'-varbindlist'} = \@poid;
1747 if (($Net_SNMP_util::Version > 1)
1748 and ($Net_SNMP_util::MaxRepetitions > 1)) {
1749 $ret = $session->get_bulk_request(%args);
1750 } else {
1751 $ret = $session->get_next_request(%args);
1752 }
1753 last if (!defined($ret));
1754  
1755 %soid = %nsoid;
1756 undef %nsoid;
1757 $stop = 0;
1758 foreach $oid (&Net::SNMP::oid_lex_sort(keys %$ret)) {
1759 $got = 1;
1760 $tmp = -1;
1761 foreach $toid (@enoid) {
1762 $tmp++;
1763 if (&Net::SNMP::oid_base_match($toid, $oid)
1764 and (!exists($soid{$toid}) or ($oid ne $soid{$toid}))) {
1765 $nsoid{$toid} = $oid;
1766 if (defined($hash_sub)) {
1767 #
1768 # extract name of the oid, if possible, the rest becomes the
1769 # instance
1770 #
1771 my $inst = "";
1772 my $upo = $toid;
1773 while (!exists($revOIDS{$upo}) and length($upo)) {
1774 $upo =~ s/(\.\d+?)$//;
1775 if (defined($1) and length($1)) {
1776 $inst = $1 . $inst;
1777 } else {
1778 $upo = "";
1779 last;
1780 }
1781 }
1782 if (length($upo) and exists($revOIDS{$upo})) {
1783 $upo = $revOIDS{$upo} . $inst;
1784 } else {
1785 $upo = $toid;
1786 }
1787  
1788 my $qoid = $oid;
1789 my $tmpo;
1790 $inst = "";
1791 while (!exists($revOIDS{$qoid}) and length($qoid)) {
1792 $qoid =~ s/(\.\d+?)$//;
1793 if (defined($1) and length($1)) {
1794 $inst = $1 . $inst;
1795 } else {
1796 $qoid = "";
1797 last;
1798 }
1799 }
1800 if (length($qoid) and exists($revOIDS{$qoid})) {
1801 $tmpo = $qoid;
1802 $qoid = $revOIDS{$qoid};
1803 } else {
1804 $qoid = $oid;
1805 $tmpo = $toid;
1806 $inst = substr($oid, length($tmpo)+1);
1807 }
1808 #
1809 # call hash_sub
1810 #
1811 &$hash_sub($h_ref, $host, $qoid, $tmpo, $inst, $ret->{$oid}, $upo);
1812 } else {
1813 my $tmpo;
1814 my $tmpv = $ret->{$oid};
1815 $tmpo = substr($oid, length($toid)+1);
1816 push @{$tmprefs[$tmp]}, "$tmpo:$tmpv";
1817 }
1818 } else {
1819 $stop = 1 if ($#enoid == 0);
1820 }
1821 }
1822 }
1823 undef @poid;
1824 @poid = values %nsoid if (!$stop);
1825 }
1826 if ($got) {
1827 if (defined($hash_sub)) {
1828 return ($h_ref) if ($Net_SNMP_util::ReturnHashRefs);
1829 return (%$h_ref);
1830 } elsif ($Net_SNMP_util::Return_array_refs) {
1831 return (@tmprefs);
1832 } else {
1833 do {
1834 $got = 0;
1835 foreach $toid (0..$#enoid) {
1836 next if (scalar(@{$tmprefs[$toid]}) <= 0);
1837 $got = 1;
1838 $oid = shift(@{$tmprefs[$toid]});
1839 if ($#enoid > 0) {
1840 ($oid, $val) = split(':', $oid, 2);
1841 $oid = $enoid[$toid] . '.' . $oid;
1842 push(@retvals, "$oid:$val");
1843 } else {
1844 push(@retvals, $oid);
1845 }
1846 }
1847 } while($got);
1848 return (@retvals);
1849 }
1850 } else {
1851 $ret = join(' ', @vars);
1852 error_msg("SNMPWALK Problem for $ret on ${host}: " . $session->error());
1853 if (defined($hash_sub)) {
1854 return ($h_ref) if ($SNMP_util::Return_hash_refs);
1855 return (%$h_ref);
1856 } else {
1857 @retvals = ();
1858 return (@retvals);
1859 }
1860 }
1861 }
1862  
1863 #
1864 # When passed a string, return the ASN.1 type that corresponds to the
1865 # string.
1866 #
1867 sub ASNtype($) {
1868 my($type) = @_;
1869  
1870 $type =~ tr/A-Z/a-z/;
1871 if ($type eq "int") {
1872 $type = 0x02;
1873 } elsif ($type eq "integer") {
1874 $type = 0x02;
1875 } elsif ($type eq "string") {
1876 $type = 0x04;
1877 } elsif ($type eq "octetstring") {
1878 $type = 0x04;
1879 } elsif ($type eq "octet string") {
1880 $type = 0x04;
1881 } elsif ($type eq "oid") {
1882 $type = 0x06;
1883 } elsif ($type eq "object id") {
1884 $type = 0x06;
1885 } elsif ($type eq "object identifier") {
1886 $type = 0x06;
1887 } elsif ($type eq "ipaddr") {
1888 $type = 0x40;
1889 } elsif ($type eq "ip address") {
1890 $type = 0x40;
1891 } elsif ($type eq "timeticks") {
1892 $type = 0x43;
1893 } elsif ($type eq "uint") {
1894 $type = 0x47;
1895 } elsif ($type eq "uinteger") {
1896 $type = 0x47;
1897 } elsif ($type eq "uinteger32") {
1898 $type = 0x47;
1899 } elsif ($type eq "unsigned int") {
1900 $type = 0x47;
1901 } elsif ($type eq "unsigned integer") {
1902 $type = 0x47;
1903 } elsif ($type eq "unsigned integer32") {
1904 $type = 0x47;
1905 } elsif ($type eq "counter") {
1906 $type = 0x41;
1907 } elsif ($type eq "counter32") {
1908 $type = 0x41;
1909 } elsif ($type eq "counter64") {
1910 $type = 0x46;
1911 } elsif ($type eq "gauge") {
1912 $type = 0x42;
1913 } elsif ($type eq "gauge32") {
1914 $type = 0x42;
1915 } elsif (($type <= 0) or ($type > 255)) {
1916 return undef;
1917 }
1918 return $type;
1919 }
1920  
1921 #
1922 # set the ErrorMessage global and print an error message
1923 #
1924 sub error_msg($)
1925 {
1926 my($msg) = @_;
1927 $Net_SNMP_util::ErrorMessage = $msg;
1928 if ($Net_SNMP_util::SuppressWarnings <= 1) {
1929 $Carp::CarpLevel++;
1930 carp($msg);
1931 $Carp::CarpLevel--;
1932 }
1933 }
1934  
1935 #
1936 # Fill the OIDS hash with results from the MIB parsing
1937 #
1938 sub MIB_fill_OID($)
1939 {
1940 my($href) = @_;
1941 my($cnt, $changed, @del, $var, $val, @parts, $indx);
1942 my(%seen);
1943  
1944 $cnt = 0;
1945 do {
1946 $changed = 0;
1947 @del = ();
1948 foreach $var (keys %$href) {
1949 $val = $href->{$var};
1950 @parts = split('\.', $val);
1951 $val = '';
1952 foreach $indx (@parts) {
1953 if ($indx =~ /^\d+$/) {
1954 $val .= '.' . $indx;
1955 } else {
1956 if (exists($Net_SNMP_util::OIDS{$indx})) {
1957 $val = $Net_SNMP_util::OIDS{$indx};
1958 } else {
1959 $val .= '.' . $indx;
1960 }
1961 }
1962 }
1963 if ($val =~ /^[\d\.]+$/) {
1964 $val =~ s/^\.+//;
1965 if (!exists($Net_SNMP_util::OIDS{$var})
1966 || (length($val) > length($Net_SNMP_util::OIDS{$var}))) {
1967 $Net_SNMP_util::OIDS{$var} = $val;
1968 print "'$var' => '$val'\n" if $Net_SNMP_util::Debug;
1969 $changed = 1;
1970 $cnt++;
1971 }
1972 push @del, $var;
1973 }
1974 }
1975 foreach $var (@del) {
1976 delete $href->{$var};
1977 }
1978 } while($changed);
1979  
1980 $Carp::CarpLevel++;
1981 foreach $var (sort keys %$href) {
1982 $val = $href->{$var};
1983 $val =~ s/\..*//;
1984 next if (exists($seen{$val}));
1985 $seen{$val} = 1;
1986 $seen{$var} = 1;
1987 error_msg(
1988 "snmpMIB_to_OID: prefix \"$val\" unknown, load the parent MIB first.\n"
1989 );
1990 }
1991 $Carp::CarpLevel--;
1992 return $cnt;
1993 }
1994  
1995  
1996 # [documentation] ------------------------------------------------------------
1997  
1998 =head1 EXPORTS
1999  
2000 The Net_SNMP_util module uses the F<Exporter> module to export useful
2001 constants and subroutines. These exportable symbols are defined below and
2002 follow the rules and conventions of the F<Exporter> module (see L<Exporter>).
2003  
2004 =over
2005  
2006 =item Exportable
2007  
2008 &snmpget, &snmpgetnext, &snmpgetbulk, &snmpwalk, &snmpset, &snmptrap,
2009 &snmpmaptable, &snmpmaptable4, &snmpwalkhash, &snmpmapOID, &snmpMIB_to_OID,
2010 &snmpLoad_OID_Cache, &snmpQueue_MIB_File, ErrorMessage
2011  
2012 =back
2013  
2014 =head1 EXAMPLES
2015  
2016 =head2 1. SNMPv1 get-request for sysUpTime
2017  
2018 This example gets the sysUpTime from a remote host.
2019  
2020 #! /usr/local/bin/perl
2021 use strict;
2022 use Net_SNMP_util;
2023 my ($host, $ret)
2024 $host = shift || 'localhost';
2025 $ret = snmpget($host, 'sysUpTime');
2026  
2027 print("sysUpTime for $host is $ret\n");
2028  
2029 exit 0;
2030  
2031 =head2 2. SNMPv3 set-request of sysContact
2032  
2033 This example sets the sysContact information on the remote host to
2034 "Help Desk x911". The parameters passed to the snmpset function are for
2035 the demonstration of syntax only. These parameters will need to be
2036 set according to the SNMPv3 parameters of the remote host used by the script.
2037  
2038 #! /usr/local/bin/perl
2039 use strict;
2040 use Net_SNMP_util;
2041 my($host, %v3hash, $ret);
2042 $host = shift || 'localhost';
2043 $v3hash{'-version'} = 'snmpv3';
2044 $v3hash{'-username'} = 'myv3Username';
2045 $v3hash{'-authkey'} = '0x05c7fbde31916f64da4d5b77156bdfa7';
2046 $v3hash{'-authprotocol'} = 'md5';
2047 $v3hash{'-privkey'} = '0x93725fd3a02a48ce02df4e065a1c1746';
2048  
2049 $ret = snmpset($host, \%v3hash, 'sysContact', 'string', 'Help Desk x911');
2050  
2051 print "sysContact on $host is now $ret\n";
2052 exit 0;
2053  
2054 =head2 3. SNMPv2c walk for ifTable
2055  
2056 This example gets the contents of the ifTable by sending get-bulk-requests
2057 until the responses are no longer part of the ifTable. The ifTable can also
2058 be retrieved using C<snmpmaptable>.
2059  
2060 #! /usr/local/bin/perl
2061 use strict;
2062 use Net_SNMP_util;
2063 my($host, @ret, $oid, $val);
2064 $host = shift || 'localhost';
2065  
2066 @ret = snmpwalk($host . ':::::2', 'ifTable');
2067 foreach $val (@ret) {
2068 ($oid, $val) = split(':', $val, 2);
2069 print "$oid => $val\n";
2070 }
2071 exit 0;
2072  
2073 =head2 4. SNMPv2c maptable collecting ifDescr, ifInOctets, and ifOutOctets.
2074  
2075 This example collects a table containing the columns ifDescr, ifInOctets, and
2076 ifOutOctets. A printing function is called once per row.
2077  
2078 #! /usr/local/bin/perl
2079 use strict;
2080 use Net_SNMP_util;
2081  
2082 sub printfun($$$$) {
2083 my($inst, $desc, $in, $out) = @_;
2084 printf "%3d %-52.52s %10d %10d\n", $inst, $desc, $in, $out;
2085 }
2086  
2087 my($host, @ret);
2088 $host = shift || 'localhost';
2089  
2090 printf "%-3s %-52s %10s %10s\n", "Int", "Description", "In", "Out";
2091 @ret = snmpmaptable($host . ':::::2', \&printfun,
2092 'ifDescr', 'ifInOctets', 'ifOutOctets');
2093  
2094 exit 0;
2095  
2096 =head1 REQUIREMENTS
2097  
2098 =over
2099  
2100 =item *
2101  
2102 The Net_SNMP_util module uses syntax that is not supported in versions of Perl
2103 earlier than v5.6.0.
2104  
2105 =item *
2106  
2107 The Net_SNMP_util module uses the F<Net::SNMP> module, and as such may depend
2108 on other modules. Please see the documentation on F<Net::SNMP> for more
2109 information.
2110  
2111 =back
2112  
2113 =head1 AUTHOR
2114  
2115 Mike Mitchell <Mike.Mitchell@sas.com>
2116  
2117 =head1 ACKNOWLEGEMENTS
2118  
2119 The original concept for this module was based on F<SNMP_Session.pm> written
2120 by Simon Leinen <simon@switch.ch>
2121  
2122 =head1 COPYRIGHT
2123  
2124 Copyright (c) 2007 Mike Mitchell. All rights reserved. This program
2125 is free software; you may redistribute it and/or modify it under the same
2126 terms as Perl itself.
2127  
2128 =cut
2129  
2130 # ======================================================================
2131 1; # [end Net_SNMP_util]