KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snmp4j > tools > console > SnmpRequest


1 /*_############################################################################
2   _##
3   _## SNMP4J - SnmpRequest.java
4   _##
5   _## Copyright 2003-2007 Frank Fock and Jochen Katz (SNMP4J.org)
6   _##
7   _## Licensed under the Apache License, Version 2.0 (the "License");
8   _## you may not use this file except in compliance with the License.
9   _## You may obtain a copy of the License at
10   _##
11   _## http://www.apache.org/licenses/LICENSE-2.0
12   _##
13   _## Unless required by applicable law or agreed to in writing, software
14   _## distributed under the License is distributed on an "AS IS" BASIS,
15   _## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   _## See the License for the specific language governing permissions and
17   _## limitations under the License.
18   _##
19   _##########################################################################*/

20
21 package org.snmp4j.tools.console;
22
23 import java.io.IOException JavaDoc;
24 import java.util.Vector JavaDoc;
25 import org.snmp4j.*;
26 import org.snmp4j.mp.*;
27 import org.snmp4j.security.*;
28 import org.snmp4j.smi.*;
29 import org.snmp4j.transport.*;
30 import org.snmp4j.util.*;
31 import org.snmp4j.event.ResponseEvent;
32 import java.util.StringTokenizer JavaDoc;
33 import org.snmp4j.log.LogFactory;
34 import org.snmp4j.asn1.BER;
35 import org.snmp4j.log.JavaLogFactory;
36 import org.snmp4j.log.LogLevel;
37
38 /**
39  * The SnmpRequest application is an example implementation of most of the
40  * SNMP4J features. It can be used to send SNMP requests to a target or to
41  * listen for traps/notifications and inform requests.
42  *
43  * @author Frank Fock
44  * @version 1.8
45  */

46 public class SnmpRequest implements CommandResponder, PDUFactory {
47
48   // initialize Java logging
49
static {
50     LogFactory.setLogFactory(new JavaLogFactory());
51     BER.setCheckSequenceLength(false);
52   }
53
54   public static final int DEFAULT = 0;
55   public static final int WALK = 1;
56   public static final int LISTEN = 2;
57   public static final int TABLE = 3;
58   public static final int CVS_TABLE = 4;
59   public static final int TIME_BASED_CVS_TABLE = 5;
60
61   Target target;
62   Address address;
63   OID authProtocol;
64   OID privProtocol;
65   OctetString privPassphrase;
66   OctetString authPassphrase;
67   OctetString community = new OctetString("public");
68   OctetString authoritativeEngineID;
69   OctetString contextEngineID;
70   OctetString contextName = new OctetString();
71   OctetString securityName = new OctetString();
72   OctetString localEngineID = new OctetString(MPv3.createLocalEngineID());
73
74   TimeTicks sysUpTime = new TimeTicks(0);
75   OID trapOID = SnmpConstants.coldStart;
76
77   PDUv1 v1TrapPDU = new PDUv1();
78
79   int version = SnmpConstants.version3;
80   int engineBootCount = 0;
81   int retries = 1;
82   int timeout = 1000;
83   int pduType = PDU.GETNEXT;
84   int maxRepetitions = 10;
85   int nonRepeaters = 0;
86   int maxSizeResponsePDU = 65535;
87   Vector JavaDoc vbs = new Vector JavaDoc();
88
89   protected int operation = DEFAULT;
90
91   int numDispatcherThreads = 2;
92
93   boolean useDenseTableOperation = false;
94
95   // table options
96
OID lowerBoundIndex, upperBoundIndex;
97
98
99   public SnmpRequest(String JavaDoc[] args) {
100     // Set the default counter listener to return proper USM and MP error
101
// counters.
102
CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());
103
104     vbs.add(new VariableBinding(new OID("1.3.6")));
105     int paramStart = parseArgs(args);
106     if (paramStart >= args.length) {
107       printUsage();
108       System.exit(1);
109     }
110     else {
111       checkOptions();
112       address = getAddress(args[paramStart++]);
113       Vector JavaDoc vbs = getVariableBindings(args, paramStart);
114       checkTrapVariables(vbs);
115       if (vbs.size() > 0) {
116         this.vbs = vbs;
117       }
118     }
119   }
120
121   public int getPduType() {
122     return pduType;
123   }
124
125   public int getVersion() {
126     return version;
127   }
128
129   public Vector JavaDoc getVbs() {
130     return vbs;
131   }
132
133   public boolean isUseDenseTableOperation() {
134     return useDenseTableOperation;
135   }
136
137   public OID getUpperBoundIndex() {
138     return upperBoundIndex;
139   }
140
141   public OID getTrapOID() {
142     return trapOID;
143   }
144
145   public int getTimeout() {
146     return timeout;
147   }
148
149   public Target getTarget() {
150     return target;
151   }
152
153   public TimeTicks getSysUpTime() {
154     return sysUpTime;
155   }
156
157   public OctetString getSecurityName() {
158     return securityName;
159   }
160
161   public int getRetries() {
162     return retries;
163   }
164
165   public OID getPrivProtocol() {
166     return privProtocol;
167   }
168
169   public OctetString getPrivPassphrase() {
170     return privPassphrase;
171   }
172
173   public int getOperation() {
174     return operation;
175   }
176
177   public int getNumDispatcherThreads() {
178     return numDispatcherThreads;
179   }
180
181   public int getNonRepeaters() {
182     return nonRepeaters;
183   }
184
185   public int getMaxRepetitions() {
186     return maxRepetitions;
187   }
188
189   public OID getLowerBoundIndex() {
190     return lowerBoundIndex;
191   }
192
193   public OctetString getContextName() {
194     return contextName;
195   }
196
197   public OctetString getContextEngineID() {
198     return contextEngineID;
199   }
200
201   public OctetString getCommunity() {
202     return community;
203   }
204
205   public OctetString getAuthoritativeEngineID() {
206     return authoritativeEngineID;
207   }
208
209   public OID getAuthProtocol() {
210     return authProtocol;
211   }
212
213   public OctetString getAuthPassphrase() {
214     return authPassphrase;
215   }
216
217   public Address getAddress() {
218     return address;
219   }
220
221   private void checkOptions() {
222     if ((operation == WALK) &&
223         ((pduType != PDU.GETBULK) && (pduType != PDU.GETNEXT))) {
224       throw new IllegalArgumentException JavaDoc(
225           "Walk operation is not supported for PDU type: "+
226           PDU.getTypeString(pduType));
227     }
228     else if ((operation == WALK) && (vbs.size() != 1)) {
229       throw new IllegalArgumentException JavaDoc(
230           "There must be exactly one OID supplied for walk operations");
231     }
232     if ((pduType == PDU.V1TRAP) && (version != SnmpConstants.version1)) {
233       throw new IllegalArgumentException JavaDoc(
234           "V1TRAP PDU type is only available for SNMP version 1");
235     }
236   }
237
238   private void checkTrapVariables(Vector JavaDoc vbs) {
239     if ((pduType == PDU.INFORM) ||
240         (pduType == PDU.TRAP)) {
241       if ((vbs.size() == 0) ||
242           ((vbs.size() > 1) &&
243            (!((VariableBinding) vbs.get(0)).getOid().equals(SnmpConstants.
244           sysUpTime)))) {
245         vbs.add(0, new VariableBinding(SnmpConstants.sysUpTime, sysUpTime));
246       }
247       if ((vbs.size() == 1) ||
248           ((vbs.size() > 2) &&
249            (!((VariableBinding) vbs.get(1)).getOid().equals(SnmpConstants.
250           snmpTrapOID)))) {
251         vbs.add(1, new VariableBinding(SnmpConstants.snmpTrapOID, trapOID));
252       }
253     }
254   }
255
256   public synchronized void listen() throws IOException JavaDoc {
257     AbstractTransportMapping transport;
258     if (address instanceof TcpAddress) {
259       transport = new DefaultTcpTransportMapping((TcpAddress) address);
260     }
261     else {
262       transport = new DefaultUdpTransportMapping((UdpAddress) address);
263     }
264     ThreadPool threadPool =
265         ThreadPool.create("DispatcherPool", numDispatcherThreads);
266     MessageDispatcher mtDispatcher =
267         new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
268
269     // add message processing models
270
mtDispatcher.addMessageProcessingModel(new MPv1());
271     mtDispatcher.addMessageProcessingModel(new MPv2c());
272     mtDispatcher.addMessageProcessingModel(new MPv3());
273
274     // add all security protocols
275
SecurityProtocols.getInstance().addDefaultProtocols();
276
277     Snmp snmp = new Snmp(mtDispatcher, transport);
278     if (version == SnmpConstants.version3) {
279       USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0);
280       SecurityModels.getInstance().addSecurityModel(usm);
281       if (authoritativeEngineID != null) {
282         snmp.setLocalEngine(authoritativeEngineID.getValue(), 0, 0);
283       }
284       // Add the configured user to the USM
285
addUsmUser(snmp);
286     }
287     else {
288       CommunityTarget target = new CommunityTarget();
289       target.setCommunity(community);
290       this.target = target;
291     }
292
293     snmp.addCommandResponder(this);
294
295     transport.listen();
296     System.out.println("Listening on "+address);
297
298     try {
299       this.wait();
300     }
301     catch (InterruptedException JavaDoc ex) {
302     }
303   }
304
305   private void addUsmUser(Snmp snmp) {
306     snmp.getUSM().addUser(securityName, new UsmUser(securityName,
307                                                     authProtocol,
308                                                     authPassphrase,
309                                                     privProtocol,
310                                                     privPassphrase));
311   }
312
313   private Snmp createSnmpSession() throws IOException JavaDoc {
314     AbstractTransportMapping transport;
315     if (address instanceof TcpAddress) {
316       transport = new DefaultTcpTransportMapping();
317     }
318     else {
319       transport = new DefaultUdpTransportMapping();
320     }
321     // Could save some CPU cycles:
322
// transport.setAsyncMsgProcessingSupported(false);
323
Snmp snmp = new Snmp(transport);
324
325     if (version == SnmpConstants.version3) {
326       USM usm = new USM(SecurityProtocols.getInstance(),
327                         new OctetString(MPv3.createLocalEngineID()),
328                         engineBootCount);
329       SecurityModels.getInstance().addSecurityModel(usm);
330       addUsmUser(snmp);
331     }
332     return snmp;
333   }
334
335   private Target createTarget() {
336     if (version == SnmpConstants.version3) {
337       UserTarget target = new UserTarget();
338       if (authPassphrase != null) {
339         if (privPassphrase != null) {
340           target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
341         }
342         else {
343           target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
344         }
345       }
346       else {
347         target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
348       }
349       target.setSecurityName(securityName);
350       return target;
351     }
352     else {
353       CommunityTarget target = new CommunityTarget();
354       target.setCommunity(community);
355       return target;
356     }
357   }
358
359   public PDU send() throws IOException JavaDoc {
360     Snmp snmp = createSnmpSession();
361     this.target = createTarget();
362     target.setVersion(version);
363     target.setAddress(address);
364     target.setRetries(retries);
365     target.setTimeout(timeout);
366     target.setMaxSizeRequestPDU(maxSizeResponsePDU);
367     snmp.listen();
368
369     PDU request = createPDU(target);
370     if (request.getType() == PDU.GETBULK) {
371       request.setMaxRepetitions(maxRepetitions);
372       request.setNonRepeaters(nonRepeaters);
373     }
374     for (int i=0; i<vbs.size(); i++) {
375       request.add((VariableBinding)vbs.get(i));
376     }
377
378     PDU response = null;
379     if (operation == WALK) {
380       walk(snmp, request, target);
381       return null;
382     }
383     else {
384       ResponseEvent responseEvent;
385       long startTime = System.currentTimeMillis();
386       responseEvent = snmp.send(request, target);
387       if (responseEvent != null) {
388         response = responseEvent.getResponse();
389         System.out.println("Received response after "+
390                            (System.currentTimeMillis()-startTime)+" millis");
391       }
392     }
393     snmp.close();
394     return response;
395   }
396
397   private PDU walk(Snmp snmp, PDU request, Target target) throws IOException JavaDoc {
398     request.setNonRepeaters(0);
399     OID rootOID = request.get(0).getOid();
400     PDU response = null;
401     final WalkCounts counts = new WalkCounts();
402     final long startTime = System.currentTimeMillis();
403     TreeUtils treeUtils = new TreeUtils(snmp, new DefaultPDUFactory());
404     treeUtils.getSubtree(target, rootOID, null, new TreeListener() {
405       public boolean next(TreeEvent e) {
406         counts.requests++;
407         if (e.getVariableBindings() != null) {
408           counts.objects += e.getVariableBindings().length;
409           for (int i=0; i<e.getVariableBindings().length; i++) {
410             System.out.println(e.getVariableBindings()[i].toString());
411           }
412         }
413         return true;
414       }
415
416       public void finished(TreeEvent e) {
417         System.out.println();
418         System.out.println("Total requests sent: "+counts.requests);
419         System.out.println("Total objects received: "+counts.objects);
420         System.out.println("Total walk time: "+
421                            (System.currentTimeMillis()-startTime)+" milliseconds");
422         if (e.isError()) {
423           System.err.println("The following error occurred during walk:");
424           System.err.println(e.getErrorMessage());
425         }
426       }
427     });
428     return response;
429   }
430
431
432   private static Vector JavaDoc getVariableBindings(String JavaDoc[] args, int position) {
433     Vector JavaDoc v = new Vector JavaDoc(args.length-position+1);
434     for (int i=position; i<args.length; i++) {
435       String JavaDoc oid = args[i];
436       char type = 'i';
437       String JavaDoc value = null;
438       int equal = oid.indexOf("={");
439       if (equal > 0) {
440         oid = args[i].substring(0, equal);
441         type = args[i].charAt(equal+2);
442         value = args[i].substring(args[i].indexOf('}')+1);
443       }
444       else if (oid.indexOf('-') > 0) {
445         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(oid, "-");
446         if (st.countTokens() != 2) {
447           throw new IllegalArgumentException JavaDoc("Illegal OID range specified: '"+
448                                              oid);
449         }
450         oid = st.nextToken();
451         VariableBinding vbLower = new VariableBinding(new OID(oid));
452         v.add(vbLower);
453         long last = Long.parseLong(st.nextToken());
454         long first = vbLower.getOid().lastUnsigned();
455         for (long k=first+1; k<=last; k++) {
456           OID nextOID = new OID(vbLower.getOid().getValue(), 0,
457                                 vbLower.getOid().size()-1);
458           nextOID.appendUnsigned(k);
459           VariableBinding next = new VariableBinding(nextOID);
460           v.add(next);
461         }
462         continue;
463       }
464       VariableBinding vb = new VariableBinding(new OID(oid));
465       if (value != null) {
466         Variable variable;
467         switch (type) {
468           case 'i':
469             variable = new Integer32(Integer.parseInt(value));
470             break;
471           case 'u':
472             variable = new UnsignedInteger32(Long.parseLong(value));
473             break;
474           case 's':
475             variable = new OctetString(value);
476             break;
477           case 'x':
478             variable = OctetString.fromString(value, ':', 16);
479             break;
480           case 'd':
481             variable = OctetString.fromString(value, '.', 10);
482             break;
483           case 'b':
484             variable = OctetString.fromString(value, ' ', 2);
485             break;
486           case 'n':
487             variable = new Null();
488             break;
489           case 'o':
490             variable = new OID(value);
491             break;
492           case 't':
493             variable = new TimeTicks(Long.parseLong(value));
494             break;
495           case 'a':
496             variable = new IpAddress(value);
497             break;
498           default:
499             throw new IllegalArgumentException JavaDoc("Variable type "+type+
500                                                " not supported");
501          }
502          vb.setVariable(variable);
503        }
504        v.add(vb);
505     }
506     return v;
507   }
508
509   private static Address getAddress(String JavaDoc transportAddress) {
510     String JavaDoc transport = "udp";
511     int colon = transportAddress.indexOf(':');
512     if (colon > 0) {
513       transport = transportAddress.substring(0, colon);
514       transportAddress = transportAddress.substring(colon+1);
515     }
516     // set default port
517
if (transportAddress.indexOf('/') < 0) {
518       transportAddress += "/161";
519     }
520     if (transport.equalsIgnoreCase("udp")) {
521       return new UdpAddress(transportAddress);
522     }
523     else if (transport.equalsIgnoreCase("tcp")) {
524       return new TcpAddress(transportAddress);
525     }
526     throw new IllegalArgumentException JavaDoc("Unknown transport "+transport);
527   }
528
529   private static String JavaDoc nextOption(String JavaDoc[] args, int position) {
530     if (position+1 >= args.length) {
531       throw new IllegalArgumentException JavaDoc("Missing option value for " +
532                                          args[position]);
533     }
534     return args[position+1];
535   }
536
537   private static OctetString createOctetString(String JavaDoc s) {
538     OctetString octetString;
539     if (s.startsWith("0x")) {
540       octetString = OctetString.fromHexString(s.substring(2), ':');
541     }
542     else {
543       octetString = new OctetString(s);
544     }
545     return octetString;
546   }
547
548   private int parseArgs(String JavaDoc[] args) {
549     for (int i=0; i<args.length; i++) {
550       if (args[i].equals("-a")) {
551         String JavaDoc s = nextOption(args, i++);
552         if (s.equals("MD5")) {
553           authProtocol = AuthMD5.ID;
554         }
555         else if (s.equals("SHA")) {
556           authProtocol = AuthSHA.ID;
557         }
558         else {
559           throw new IllegalArgumentException JavaDoc("Authentication protocol unsupported: "+s);
560         }
561       }
562       else if (args[i].equals("-A")) {
563        authPassphrase = createOctetString(nextOption(args, i++));
564       }
565       else if (args[i].equals("-X") || args[i].equals("-P")) {
566        privPassphrase = createOctetString(nextOption(args, i++));
567       }
568       else if (args[i].equals("-c")) {
569         community = createOctetString(nextOption(args, i++));
570       }
571       else if (args[i].equals("-b")) {
572         engineBootCount = Math.max(Integer.parseInt(nextOption(args, i++)), 0);
573       }
574       else if (args[i].equals("-d")) {
575         String JavaDoc debugOption = nextOption(args, i++);
576         LogFactory.getLogFactory().getRootLogger().setLogLevel(
577             LogLevel.toLevel(debugOption));
578       }
579       else if (args[i].equals("-l")) {
580         localEngineID = createOctetString(nextOption(args, i++));
581       }
582       else if (args[i].equals("-e")) {
583         authoritativeEngineID = createOctetString(nextOption(args, i++));
584       }
585       else if (args[i].equals("-E")) {
586         contextEngineID = createOctetString(nextOption(args, i++));
587       }
588       else if (args[i].equals("-h")) {
589         printUsage();
590         System.exit(0);
591       }
592       else if (args[i].equals("-n")) {
593         contextName = createOctetString(nextOption(args, i++));
594       }
595       else if (args[i].equals("-m")) {
596         maxSizeResponsePDU = Integer.parseInt(nextOption(args, i++));
597       }
598       else if (args[i].equals("-r")) {
599         retries = Integer.parseInt(nextOption(args, i++));
600       }
601       else if (args[i].equals("-t")) {
602         timeout = Integer.parseInt(nextOption(args, i++));
603       }
604       else if (args[i].equals("-u")) {
605         securityName = createOctetString(nextOption(args, i++));
606       }
607       else if (args[i].equals("-V")) {
608         printVersion();
609         System.exit(0);
610       }
611       else if (args[i].equals("-Cr")) {
612         maxRepetitions = Integer.parseInt(nextOption(args, i++));
613       }
614       else if (args[i].equals("-Cn")) {
615         nonRepeaters = Integer.parseInt(nextOption(args, i++));
616       }
617       else if (args[i].equals("-Ce")) {
618         v1TrapPDU.setEnterprise(new OID(nextOption(args, i++)));
619       }
620       else if (args[i].equals("-Ct")) {
621         trapOID = new OID(nextOption(args, i++));
622       }
623       else if (args[i].equals("-Cg")) {
624         v1TrapPDU.setGenericTrap(Integer.parseInt(nextOption(args, i++)));
625       }
626       else if (args[i].equals("-Cs")) {
627         v1TrapPDU.setSpecificTrap(Integer.parseInt(nextOption(args, i++)));
628       }
629       else if (args[i].equals("-Ca")) {
630         v1TrapPDU.setAgentAddress(new IpAddress(nextOption(args, i++)));
631       }
632       else if (args[i].equals("-Cu")) {
633         String JavaDoc upTime = nextOption(args, i++);
634         v1TrapPDU.setTimestamp(Long.parseLong(upTime));
635         sysUpTime.setValue(Long.parseLong(upTime));
636       }
637       else if (args[i].equals("-Ow")) {
638         operation = WALK;
639       }
640       else if (args[i].equals("-Ol")) {
641         operation = LISTEN;
642       }
643       else if (args[i].equals("-OtCSV")) {
644         operation = CVS_TABLE;
645       }
646       else if (args[i].equals("-OttCSV")) {
647         operation = TIME_BASED_CVS_TABLE;
648       }
649       else if (args[i].equals("-Ot")) {
650         operation = TABLE;
651       }
652       else if (args[i].equals("-Otd")) {
653         operation = TABLE;
654         useDenseTableOperation = true;
655       }
656       else if (args[i].equals("-Cil")) {
657         lowerBoundIndex = new OID(nextOption(args, i++));
658       }
659       else if (args[i].equals("-Ciu")) {
660         upperBoundIndex = new OID(nextOption(args, i++));
661       }
662       else if (args[i].equals("-v")) {
663         String JavaDoc v = nextOption(args, i++);
664         if (v.equals("1")) {
665           version = SnmpConstants.version1;
666         }
667         else if (v.equals("2c")) {
668           version = SnmpConstants.version2c;
669         }
670         else if (v.equals("3")) {
671           version = SnmpConstants.version3;
672         }
673         else {
674           throw new IllegalArgumentException JavaDoc("Version "+v+" not supported");
675         }
676       }
677       else if (args[i].equals("-x")) {
678         String JavaDoc s = nextOption(args, i++);
679         if (s.equals("DES")) {
680           privProtocol = PrivDES.ID;
681         }
682         else if ((s.equals("AES128")) || (s.equals("AES"))) {
683           privProtocol = PrivAES128.ID;
684         }
685         else if (s.equals("AES192")) {
686           privProtocol = PrivAES192.ID;
687         }
688         else if (s.equals("AES256")) {
689           privProtocol = PrivAES256.ID;
690         }
691         else {
692           throw new IllegalArgumentException JavaDoc("Privacy protocol " + s +
693                                              " not supported");
694         }
695       }
696       else if (args[i].equals("-p")) {
697         String JavaDoc s = nextOption(args, i++);
698         pduType = PDU.getTypeFromString(s);
699         if (pduType == Integer.MIN_VALUE) {
700           throw new IllegalArgumentException JavaDoc("Unknown PDU type " + s);
701         }
702       }
703       else if (!args[i].startsWith("-")) {
704         return i;
705       }
706       else {
707         throw new IllegalArgumentException JavaDoc("Unknown option "+args[i]);
708       }
709     }
710     return 0;
711   }
712
713   protected static void printVersion() {
714     System.out.println();
715     System.out.println("SNMP4J Command Line Tool v1.8.2 Copyright "+(char)0xA9+
716                        " 2004-2007, Frank Fock and Jochen Katz");
717     System.out.println("http://www.snmp4j.org");
718     System.out.println();
719     System.out.println("SNMP4J is licensed under the Apache License 2.0:");
720     System.out.println("http://www.apache.org/licenses/LICENSE-2.0.txt");
721     System.out.println();
722   }
723
724   /**
725    * printUsage
726    */

727   protected static void printUsage() {
728     String JavaDoc[] usage = new String JavaDoc[] {
729         "",
730         "Usage: SNMP4J [options] [transport:]address [OID[={type}value] ...]",
731         "",
732         " -a authProtocol Sets the authentication protocol used to",
733         " authenticate SNMPv3 messages. Valid values are",
734         " MD5 and SHA.",
735         " -A authPassphrase Sets the authentication pass phrase for authenticated",
736         " SNMPv3 messages.",
737         " -b engineBootCount Sets the engine boot count to the specified value",
738         " greater or equal to zero. Default is zero.",
739         " -c community Sets the community for SNMPv1/v2c messages.",
740         " -Ca agentAddress Sets the agent address field of a V1TRAP PDU.",
741         " The default value is '0.0.0.0'.",
742         " -Cg genericID Sets the generic ID for SNMPv1 TRAPs (V1TRAP).",
743         " The default is 1 (coldStart).",
744         " -Ce enterpriseOID Sets the enterprise OID field of a V1TRAP PDU.",
745         " -Cil lowerBoundIndex Sets the lower bound index for TABLE operations.",
746         " -Ciu upperBoundIndex Sets the upper bound index for TABLE operations.",
747         " -Cn non-repeaters Sets the non-repeaters field for GETBULK PDUs.",
748         " It specifies the number of supplied variables that",
749         " should not be iterated over. The default is 0.",
750         " -Cr max-repetitions Sets the max-repetitions field for GETBULK PDUs.",
751         " This specifies the maximum number of iterations",
752         " over the repeating variables. The default is 10.",
753         " -Cs specificID Sets the specific ID for V1TRAP PDU. The default is 0.",
754         " -Ct trapOID Sets the trapOID (1.3.6.1.6.3.1.1.4.1.0) of an INFORM",
755         " or TRAP PDU. The default is 1.3.6.1.6.3.1.1.5.1.",
756         " -Cu upTime Sets the sysUpTime field of an INFORM, TRAP, or",
757         " V1TRAP PDU.",
758         " -d debugLevel Sets the global debug level for Log4J logging output.",
759         " Valid values are OFF, ERROR, WARN, INFO, and DEBUG.",
760         " -e engineID Sets the authoritative engine ID of the command",
761         " responder used for SNMPv3 request messages. If not",
762         " supplied, the engine ID will be discovered.",
763         " -E contextEngineID Sets the context engine ID used for the SNMPv3 scoped",
764         " PDU. The authoritative engine ID will be used for the",
765         " context engine ID, if the latter is not specified.",
766         " -h Displays this message and then exits the application.",
767         " -l localEngineID Sets the local engine ID of the command generator",
768         " and the notification receiver (thus this SNMP4J-Tool)",
769         " used for SNMPv3 request messages. This option can be",
770         " used to avoid engine ID clashes through duplicate IDs",
771         " leading to usmStatsNotInTimeWindows reports.",
772         " -n contextName Sets the target context name for SNMPv3 messages. ",
773         " Default is the empty string.",
774         " -m maxSizeRespPDU The maximum size of the response PDU in bytes.",
775         " -Ol Activates listen operation mode. In this mode, the",
776         " application will listen for incoming TRAPs and INFORMs",
777         " on the supplied address. Received request will be",
778         " dumped to the console until the application is stopped.",
779         " -Ot Activates table operation mode. In this mode, the",
780         " application receives tabular data from the column",
781         " OIDs specified as parameters. The retrieved rows will",
782         " be dumped to the console ordered by their index values.",
783         " -Otd Activates dense table operation mode. In this mode, the",
784         " application receives tabular data from the column",
785         " OIDs specified as parameters. The retrieved rows will",
786         " be dumped to the console ordered by their index values.",
787         " In contrast to -Ot this option must not be used with",
788         " sparse tables. ",
789         " -OtCSV Same as -Ot except that for each SNMP row received",
790         " exactly one row of comma separated values will printed",
791         " to the console where the first column contains the row",
792         " index.",
793         " -OttCSV Same as -OtCSV except that each row's first column",
794         " will report the current time (millis after 1.1.1970)",
795         " when the request has been sent.",
796         " -Ow Activates walk operation mode for GETNEXT and GETBULK",
797         " PDUs. If activated, the GETNEXT and GETBULK operations",
798         " will be repeated until all instances within the",
799         " OID subtree of the supplied OID have been retrieved",
800         " successfully or until an error occurred.",
801         " -p pduType Specifies the PDU type to be used for the message.",
802         " Valid types are GET, GETNEXT, GETBULK (SNMPv2c/v3),",
803         " SET, INFORM, TRAP, and V1TRAP (SNMPv1).",
804         " -P privacyPassphrase Sets the privacy pass phrase for encrypted",
805         " SNMPv3 messages (same as -X).",
806         " -r retries Sets the number of retries used for requests. A zero",
807         " value will send out a request exactly once.",
808         " Default is 1.",
809         " -t timeout Sets the timeout in milliseconds between retries.",
810         " Default is 1000 milliseconds.",
811         " -u securityName Sets the security name for authenticated v3 messages.",
812         " -v 1|2c|3 Sets the SNMP protocol version to be used.",
813         " Default is 3.",
814         " -V Displays version information and then exits.",
815         " -x privacyProtocol Sets the privacy protocol to be used to encrypt",
816         " SNMPv3 messages. Valid values are DES, AES (AES128),",
817         " AES192, and AES256.",
818         " -X privacyPassphrase Sets the privacy pass phrase for encrypted",
819         " SNMPv3 messages (same as -P).",
820         "",
821         "The address of the target SNMP engine is parsed according to the",
822         "specified <transport> selector (default selector is udp):",
823         "",
824         " udp | tcp hostname[/port]",
825         " ipv4Address[/port]",
826         " ipv6Address[/port]",
827         "",
828         "The OIDs have to be specified in numerical form, for example:",
829         " 1.3.6.1.2.1.1.5.0 (which will return the sysName.0 instance with a GET)",
830         "To request multiple instances, add additional OIDs with a space as",
831         "separator. For the last sub-identifier of a plain OID (without an assigned",
832         "value) a range can be specified, for example '1.3.6.1.2.1.2.2.1-10' will",
833         "has the same effect as enumerating all OIDs from '1.3.6.1.2.1.2.2.1' to",
834         "'1.3.6.1.2.1.2.2.10'.",
835         "For SET and INFORM request, you can specify a value for each OID by",
836         "using the following form: OID={type}value where <type> is one of",
837         "the following single characters enclosed by '{' and '}':",
838         " i Integer32",
839         " u UnsingedInteger32, Gauge32",
840         " s OCTET STRING",
841         " x OCTET STRING specified as hex string where",
842         " bytes separated by colons (':').",
843         " d OCTET STRING specified as decimal string",
844         " where bytes are separated by dots ('.').",
845         " n Null",
846         " o OBJECT IDENTIFIER",
847         " t TimeTicks",
848         " a IpAddress",
849         " b OCTET STRING specified as binary string where",
850         " bytes are separated by spaces.",
851         "",
852         "An example for a complete SNMPv2c SET request to set sysName:",
853         " SNMP4J -c private -v 2c -p SET udp:localhost/161 \"1.3.6.1.2.1.1.5.0={s}SNMP4J\"",
854         "",
855         "To walk the whole MIB tree with GETBULK and using SNMPv3 MD5 authentication:",
856         " SNMP4J -a MD5 -A MD5UserAuthPassword -u MD5User -p GETBULK -Ow 127.0.0.1/161",
857         "",
858         "Listen for unauthenticated SNMPv3 INFORMs and TRAPs and all v1/v2c TRAPs:",
859         " SNMP4J -u aSecurityName -Ol 0.0.0.0/162",
860         "",
861         "Send an unauthenticated SNMPv3 notification (trap):",
862         " SNMP4J -p TRAP -v 3 -u aSecurityName 127.0.0.1/162 \"1.3.6.1.2.1.1.3.0={t}0\" \\",
863         " \"1.3.6.1.6.3.1.1.4.1.0={o}1.3.6.1.6.3.1.1.5.1\" \\",
864         " \"1.3.6.1.2.1.1.1.0={s}System XYZ, Version N.M\"",
865         "Retrieve rows of the columnar objects ifDescr to ifInOctets and ifOutOctets:",
866         " SNMP4J -c public -v 2c -Ot localhost 1.3.6.1.2.1.2.2.1.2-10\\",
867         " 1.3.6.1.2.1.2.2.1.16",
868         ""
869     };
870
871     for (int i=0; i<usage.length; i++) {
872       System.out.println(usage[i]);
873     }
874   }
875
876
877   protected static void printVariableBindings(PDU response) {
878     for (int i=0; i<response.size(); i++) {
879       VariableBinding vb = response.get(i);
880       System.out.println(vb.toString());
881     }
882   }
883
884   protected static void printReport(PDU response) {
885     if (response.size() < 1) {
886       System.out.println("REPORT PDU does not contain a variable binding.");
887       return;
888     }
889
890     VariableBinding vb = response.get(0);
891     OID oid =vb.getOid();
892     if (SnmpConstants.usmStatsUnsupportedSecLevels.equals(oid)) {
893       System.out.print("REPORT: Unsupported Security Level.");
894     }
895     else if (SnmpConstants.usmStatsNotInTimeWindows.equals(oid)) {
896       System.out.print("REPORT: Message not within time window.");
897     }
898     else if (SnmpConstants.usmStatsUnknownUserNames.equals(oid)) {
899       System.out.print("REPORT: Unknown user name.");
900     }
901     else if (SnmpConstants.usmStatsUnknownEngineIDs.equals(oid)) {
902       System.out.print("REPORT: Unknown engine id.");
903     }
904     else if (SnmpConstants.usmStatsWrongDigests.equals(oid)) {
905       System.out.print("REPORT: Wrong digest.");
906     }
907     else if (SnmpConstants.usmStatsDecryptionErrors.equals(oid)) {
908       System.out.print("REPORT: Decryption error.");
909     }
910     else if (SnmpConstants.snmpUnknownSecurityModels.equals(oid)) {
911       System.out.print("REPORT: Unknown security model.");
912     }
913     else if (SnmpConstants.snmpInvalidMsgs.equals(oid)) {
914       System.out.print("REPORT: Invalid message.");
915     }
916     else if (SnmpConstants.snmpUnknownPDUHandlers.equals(oid)) {
917       System.out.print("REPORT: Unknown PDU handler.");
918     }
919     else if (SnmpConstants.snmpUnavailableContexts.equals(oid)) {
920       System.out.print("REPORT: Unavailable context.");
921     }
922     else if (SnmpConstants.snmpUnknownContexts.equals(oid)) {
923       System.out.print("REPORT: Unknown context.");
924     }
925     else {
926       System.out.print("REPORT contains unknown OID ("
927                          + oid.toString() + ").");
928     }
929     System.out.println(" Current counter value is " +
930                        vb.getVariable().toString() + ".");
931   }
932
933   public synchronized void processPdu(CommandResponderEvent e) {
934     PDU command = e.getPDU();
935     if (command != null) {
936       System.out.println(command.toString());
937       if ((command.getType() != PDU.TRAP) &&
938           (command.getType() != PDU.V1TRAP) &&
939           (command.getType() != PDU.REPORT) &&
940           (command.getType() != PDU.RESPONSE)) {
941         command.setErrorIndex(0);
942         command.setErrorStatus(0);
943         command.setType(PDU.RESPONSE);
944         StatusInformation statusInformation = new StatusInformation();
945         StateReference ref = e.getStateReference();
946         try {
947           e.getMessageDispatcher().returnResponsePdu(e.
948                                                      getMessageProcessingModel(),
949                                                      e.getSecurityModel(),
950                                                      e.getSecurityName(),
951                                                      e.getSecurityLevel(),
952                                                      command,
953                                                      e.getMaxSizeResponsePDU(),
954                                                      ref,
955                                                      statusInformation);
956         }
957         catch (MessageException ex) {
958           System.err.println("Error while sending response: "+ex.getMessage());
959           LogFactory.getLogger(SnmpRequest.class).error(ex);
960         }
961       }
962     }
963   }
964
965   public PDU createPDU(Target target) {
966     PDU request;
967     if (target.getVersion() == SnmpConstants.version3) {
968       request = new ScopedPDU();
969       ScopedPDU scopedPDU = (ScopedPDU)request;
970       if (contextEngineID != null) {
971         scopedPDU.setContextEngineID(contextEngineID);
972       }
973       if (contextName != null) {
974         scopedPDU.setContextName(contextName);
975       }
976     }
977     else {
978       if (pduType == PDU.V1TRAP) {
979         request = v1TrapPDU;
980       }
981       else {
982         request = new PDU();
983       }
984     }
985     request.setType(pduType);
986     return request;
987   }
988
989   public void table() throws IOException JavaDoc {
990     Snmp snmp = createSnmpSession();
991     this.target = createTarget();
992     target.setVersion(version);
993     target.setAddress(address);
994     target.setRetries(retries);
995     target.setTimeout(timeout);
996     snmp.listen();
997
998     TableUtils tableUtils = new TableUtils(snmp, this);
999     tableUtils.setMaxNumRowsPerPDU(maxRepetitions);
1000    Counter32 counter = new Counter32();
1001
1002    OID[] columns = new OID[vbs.size()];
1003    for (int i=0; i<columns.length; i++) {
1004      columns[i] = ((VariableBinding)vbs.get(i)).getOid();
1005    }
1006    long startTime = System.currentTimeMillis();
1007    synchronized (counter) {
1008
1009      TableListener listener;
1010      if (operation == TABLE) {
1011        listener = new TextTableListener();
1012      }
1013      else {
1014        listener = new CVSTableListener(System.currentTimeMillis());
1015      }
1016      if (useDenseTableOperation) {
1017        tableUtils.getDenseTable(target, columns, listener, counter,
1018                                 lowerBoundIndex, upperBoundIndex);
1019      }
1020      else {
1021        tableUtils.getTable(target, columns, listener, counter,
1022                            lowerBoundIndex, upperBoundIndex);
1023      }
1024      try {
1025        counter.wait(timeout);
1026      }
1027      catch (InterruptedException JavaDoc ex) {
1028      }
1029    }
1030    System.out.println("Table received in "+
1031                       (System.currentTimeMillis()-startTime)+" milliseconds.");
1032    snmp.close();
1033  }
1034
1035  class CVSTableListener implements TableListener {
1036
1037    private long requestTime;
1038
1039    public CVSTableListener(long time) {
1040      this.requestTime = time;
1041    }
1042
1043    public boolean next(TableEvent event) {
1044      if (operation == TIME_BASED_CVS_TABLE) {
1045        System.out.print(requestTime);
1046        System.out.print(",");
1047      }
1048      System.out.print("\""+event.getIndex()+"\",");
1049      for (int i=0; i<event.getColumns().length; i++) {
1050        Variable v = event.getColumns()[i].getVariable();
1051        String JavaDoc value = v.toString();
1052        switch (v.getSyntax()) {
1053          case SMIConstants.SYNTAX_OCTET_STRING: {
1054            StringBuffer JavaDoc escapedString = new StringBuffer JavaDoc(value.length());
1055            StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(value, "\"", true);
1056            while (st.hasMoreTokens()) {
1057              String JavaDoc token = st.nextToken();
1058              escapedString.append(token);
1059              if (token.equals("\"")) {
1060                escapedString.append("\"");
1061              }
1062            }
1063          }
1064          case SMIConstants.SYNTAX_IPADDRESS:
1065          case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
1066          case SMIConstants.SYNTAX_OPAQUE: {
1067            System.out.print("\"");
1068            System.out.print(value);
1069            System.out.print("\"");
1070            break;
1071          }
1072          default: {
1073            System.out.print(value);
1074          }
1075        }
1076        if (i+1 < event.getColumns().length) {
1077          System.out.print(",");
1078        }
1079      }
1080      System.out.println();
1081      return true;
1082    }
1083
1084    public void finished(TableEvent event) {
1085      synchronized (event.getUserObject()) {
1086        event.getUserObject().notify();
1087      }
1088    }
1089
1090  }
1091
1092  class TextTableListener implements TableListener {
1093
1094    public void finished(TableEvent event) {
1095      System.out.println();
1096      System.out.println("Table walk completed with status "+event.getStatus()+
1097                         ". Received "+
1098                         event.getUserObject()+" rows.");
1099      synchronized (event.getUserObject()) {
1100        event.getUserObject().notify();
1101      }
1102    }
1103
1104    public boolean next(TableEvent event) {
1105      System.out.println("Index = "+event.getIndex()+":");
1106      for (int i=0; i<event.getColumns().length; i++) {
1107        System.out.println(event.getColumns()[i]);
1108      }
1109      System.out.println();
1110      ((Counter32)event.getUserObject()).increment();
1111      return true;
1112    }
1113
1114  }
1115
1116  public static void main(String JavaDoc[] args) {
1117    try {
1118/* Initialize Log4J logging:
1119      if (System.getProperty("log4j.configuration") == null) {
1120        BasicConfigurator.configure();
1121      }
1122      Logger.getRootLogger().setLevel(Level.OFF);
1123*/

1124      SnmpRequest snmpRequest = new SnmpRequest(args);
1125      try {
1126        if (snmpRequest.operation == LISTEN) {
1127          snmpRequest.listen();
1128        }
1129        else if ((snmpRequest.operation == TABLE) ||
1130                 (snmpRequest.operation == CVS_TABLE) ||
1131                 (snmpRequest.operation == TIME_BASED_CVS_TABLE)) {
1132          snmpRequest.table();
1133        }
1134        else {
1135          PDU response = snmpRequest.send();
1136          if ((snmpRequest.getPduType() == PDU.TRAP) ||
1137              (snmpRequest.getPduType() == PDU.REPORT) ||
1138              (snmpRequest.getPduType() == PDU.V1TRAP) ||
1139              (snmpRequest.getPduType() == PDU.RESPONSE)) {
1140            System.out.println(PDU.getTypeString(snmpRequest.getPduType()) +
1141                               " sent successfully");
1142          }
1143          else if (response == null) {
1144            if (snmpRequest.operation != WALK) {
1145              System.out.println("Request timed out.");
1146            }
1147          }
1148          else if (response.getType() == PDU.REPORT)
1149          {
1150            printReport(response);
1151          }
1152          else if (snmpRequest.operation == DEFAULT)
1153          {
1154            System.out.println("Response received with requestID=" +
1155                               response.getRequestID() +
1156                               ", errorIndex=" +
1157                               response.getErrorIndex() + ", " +
1158                               "errorStatus=" + response.getErrorStatusText()+
1159                               "("+response.getErrorStatus()+")");
1160            printVariableBindings(response);
1161          }
1162          else
1163          {
1164            System.out.println("Received something strange: requestID=" +
1165                               response.getRequestID() +
1166                               ", errorIndex=" +
1167                               response.getErrorIndex() + ", " +
1168                               "errorStatus=" + response.getErrorStatusText()+
1169                               "("+response.getErrorStatus()+")");
1170            printVariableBindings(response);
1171          }
1172        }
1173      }
1174      catch (IOException JavaDoc ex) {
1175        System.err.println("Error while trying to send request: " +
1176                           ex.getMessage());
1177        ex.printStackTrace();
1178      }
1179    }
1180    catch (IllegalArgumentException JavaDoc iaex) {
1181      System.err.print("Error: "+iaex.getMessage());
1182      iaex.printStackTrace();
1183    }
1184  }
1185
1186  public void setAddress(Address address) {
1187    this.address = address;
1188  }
1189
1190  public void setVersion(int version) {
1191    this.version = version;
1192  }
1193
1194  public void setVbs(Vector JavaDoc vbs) {
1195    this.vbs = vbs;
1196  }
1197
1198  public void setUseDenseTableOperation(boolean useDenseTableOperation) {
1199    this.useDenseTableOperation = useDenseTableOperation;
1200  }
1201
1202  public void setUpperBoundIndex(OID upperBoundIndex) {
1203    this.upperBoundIndex = upperBoundIndex;
1204  }
1205
1206  public void setTrapOID(OID trapOID) {
1207    this.trapOID = trapOID;
1208  }
1209
1210  public void setTimeout(int timeout) {
1211    this.timeout = timeout;
1212  }
1213
1214  public void setTarget(Target target) {
1215    this.target = target;
1216  }
1217
1218  public void setSysUpTime(TimeTicks sysUpTime) {
1219    this.sysUpTime = sysUpTime;
1220  }
1221
1222  public void setSecurityName(OctetString securityName) {
1223    this.securityName = securityName;
1224  }
1225
1226  public void setRetries(int retries) {
1227    this.retries = retries;
1228  }
1229
1230  public void setPrivProtocol(OID privProtocol) {
1231    this.privProtocol = privProtocol;
1232  }
1233
1234  public void setPrivPassphrase(OctetString privPassphrase) {
1235    this.privPassphrase = privPassphrase;
1236  }
1237
1238  public void setPduType(int pduType) {
1239    this.pduType = pduType;
1240  }
1241
1242  public void setOperation(int operation) {
1243    this.operation = operation;
1244  }
1245
1246  public void setNumDispatcherThreads(int numDispatcherThreads) {
1247    this.numDispatcherThreads = numDispatcherThreads;
1248  }
1249
1250  public void setNonRepeaters(int nonRepeaters) {
1251    this.nonRepeaters = nonRepeaters;
1252  }
1253
1254  public void setMaxRepetitions(int maxRepetitions) {
1255    this.maxRepetitions = maxRepetitions;
1256  }
1257
1258  public void setLowerBoundIndex(OID lowerBoundIndex) {
1259    this.lowerBoundIndex = lowerBoundIndex;
1260  }
1261
1262  public void setContextName(OctetString contextName) {
1263    this.contextName = contextName;
1264  }
1265
1266  public void setContextEngineID(OctetString contextEngineID) {
1267    this.contextEngineID = contextEngineID;
1268  }
1269
1270  public void setCommunity(OctetString community) {
1271    this.community = community;
1272  }
1273
1274  public void setAuthoritativeEngineID(OctetString authoritativeEngineID) {
1275    this.authoritativeEngineID = authoritativeEngineID;
1276  }
1277
1278  public void setAuthProtocol(OID authProtocol) {
1279    this.authProtocol = authProtocol;
1280  }
1281
1282  public void setAuthPassphrase(OctetString authPassphrase) {
1283    this.authPassphrase = authPassphrase;
1284  }
1285
1286  class WalkCounts {
1287    public int requests;
1288    public int objects;
1289  }
1290}
1291
Popular Tags