snmpwalk.java
上传用户:aonuowh
上传日期:2021-05-23
资源大小:35390k
文件大小:12k
源码类别:

SNMP编程

开发平台:

C/C++

  1. /* $Id: snmpwalk.src,v 1.6.2.8 2009/01/28 13:32:52 tmanoj Exp $ */
  2. /*
  3.  * @(#)snmpwalk.java
  4.  * Copyright (c) 1996-2009 AdventNet, Inc. All Rights Reserved.
  5.  * Please read the associated COPYRIGHTS file for more details.
  6.  */
  7. /**
  8.  * This is an example program to explain how to write an application to do
  9.  * the basic SNMP operation WALK using com.adventnet.snmp.snmp2 package of
  10.  * AdventNetSNMP2 api.
  11.  * The user could run this application by giving any one of the following usage.
  12.  *  
  13.  * java snmpwalk [options] hostname oid
  14.  *
  15.  * v1 request: 
  16.  * java snmpwalk snmpwalk [-d] [-c community] [-p port] [-t timeout] [-r retries] host OID
  17.  * e.g. 
  18.  * java snmpwalk -p 161 -c public adventnet .1.3.6.1 
  19.  *
  20.  * v2c request:  
  21.  * java snmpwalk [-d] [-v version(v1,v2)] [-c community] [-p port] [-t timeout] [-r retries] host OID
  22.  * e.g. 
  23.  * java snmpwalk -v v2 -p 161 -c public -m rfc1213-mib adventnet .1.3.6.1
  24.  * 
  25.  * v3 request:
  26.  * java snmpwalk [-d] [-v version(v1,v2,v3)] [-c community] [-p port] [-r retries] [-t timeout] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] host OID
  27.  * e.g.
  28.  * java snmpwalk -v v3 -u initial2 -w initial2Pass -a MD5 10.3.2.120 .1.3
  29.  * 
  30.  * If the oid is not starting with a dot (.) it will be prefixed by .1.3.6.1.2.1 .
  31.  * So the entire OID of 1.1.0 will become .1.3.6.1.2.1.1.1.0 . You can also
  32.  * give the entire OID .
  33.  * 
  34.  * Options:
  35.  * [-d]                - Debug output. By default off.
  36.  * [-c] <community>    - community String. By default "public".
  37.  * [-p] <port>         - remote port no. By default 161.
  38.  * [-t] <Timeout>      - Timeout. By default 5000ms.
  39.  * [-r] <Retries>      - Retries. By default 0.      
  40.  * [-v] <version>      - version(v1 / v2 / v3). By default v1.
  41.  * [-u] <username>     - The v3 principal/userName
  42.  * [-a] <autProtocol>  - The authProtocol(MD5/SHA). Mandatory if authPassword is specified
  43.  * [-pp]<privProtocol> - The privProtocol(DES/AES-128/AES-192/AES-256/3DES).
  44.  * [-w] <authPassword> - The authentication password.
  45.  * [-s] <privPassword> - The privacy protocol password. Must be accompanied with auth password and authProtocol fields.
  46.  * [-n] <contextName>  - The context to be used for the v3 pdu.
  47.  * [-i] <contextID>    - The context to be used for the v3 pdu.
  48.  * <host> Mandatory    - The RemoteHost (agent).Format (string without double qoutes/IpAddress).
  49.  * <OID>  Mandatory    - Give multiple no. of Object Identifiers.
  50.  */
  51. import java.lang.*;
  52. import java.util.*;
  53. import java.net.*;
  54. import com.adventnet.snmp.snmp2.*;
  55. import com.adventnet.snmp.snmp2.usm.*;
  56. public class snmpwalk
  57. {
  58.     public static void main(String args[])
  59.     {
  60.  
  61.         // Take care of getting options
  62.         String usage =
  63.             "nsnmpwalk [-d] [-v version(v1,v2,v3)] n" +
  64.             "[-c community] [-p port] [-r retries] n" +
  65.             "[-t timeout] [-u user] [-a auth_protocol] n" +
  66.             "[-w auth_password] [-s priv_password] n" +
  67.             "[-n contextName] [-i contextID] n" +
  68.             "[-DB_driver database_driver]n" +
  69.             "[-DB_url database_url]n" +
  70.             "[-DB_username database_username]n" +
  71.             "[-DB_password database_password]n" +
  72. "[-pp privProtocol(DES/AES-128/AES-192/AES-256/3DES)]n"+
  73. "host OIDn";
  74.         String options[] =
  75.         {
  76.             "-d", "-c",  "-wc", "-p", "-r", "-t", "-m",
  77.             "-v", "-u", "-a", "-w", "-s", "-n", "-i",
  78.             "-DB_driver", "-DB_url", "-DB_username", "-DB_password","-pp"
  79.         };
  80.         
  81.         String values[] =
  82.         {
  83.             "None", null, null, null, null, null, "None",
  84.             null, null, null, null, null, null, null,
  85.             null, null, null, null, null
  86.         };
  87.         ParseOptions opt = new ParseOptions(args,options,values, usage);
  88.         if (opt.remArgs.length!=2)
  89.         {
  90.             opt.usage_error();
  91.         }
  92.         
  93.         // Start SNMP API
  94.         SnmpAPI api;
  95.         api = new SnmpAPI();
  96.         if (values[0].equals("Set"))
  97.         {
  98.             api.setDebug( true );
  99.         }
  100.         // Open session
  101.         SnmpSession session = new SnmpSession(api);
  102.         int PORT = 3;
  103.         
  104.         // set remote Host and remote Port
  105.         UDPProtocolOptions ses_opt = new UDPProtocolOptions();
  106. ses_opt.setRemoteHost(opt.remArgs[0]);
  107. if(values[PORT] != null)
  108. {
  109. try
  110. {
  111. ses_opt.setRemotePort(Integer.parseInt(values[PORT]));
  112. }
  113. catch(Exception exp)
  114. {
  115. System.out.println("Invalid port: " + values[PORT]);
  116. System.exit(1);
  117. }
  118. }
  119. session.setProtocolOptions(ses_opt);
  120.         //set the values
  121.         SetValues setVal = new SetValues(session, values);
  122.         if(setVal.usage_error)
  123.         {
  124.             opt.usage_error(); 
  125.         }
  126.         String driver = values[14];
  127.         String url = values[15];
  128.         String username = values[16];
  129.         String password = values[17];
  130.         if(driver != null || url != null ||
  131.             username != null || password != null)
  132.         {
  133.             if(session.getVersion() != 3)
  134.             {
  135.                 System.out.println(
  136.                     "Database option can be used only for SNMPv3.");
  137.                 System.exit(1);
  138.             }
  139.             if(driver == null)
  140.             {
  141.                 System.out.println(
  142.                     "The Database driver name should be given.");
  143.                 System.exit(1);
  144.             }
  145.             if(url == null)
  146.             {
  147.                 System.out.println("The Database URL should be given.");
  148.                 System.exit(1);
  149.             }
  150.             try
  151.             {
  152.                 api.setV3DatabaseFlag(true);
  153.                 api.initJdbcParams(driver, url, username, password);
  154.             }
  155.             catch(Exception exp)
  156.             {
  157.                 System.out.println("Unable to Establish Database Connection.");
  158.                 System.out.println("Please check the driverName and url.");
  159.                 System.exit(1);
  160.             }
  161.         }
  162.         // Build GETNEXT request PDU
  163.         SnmpPDU pdu = new SnmpPDU();
  164.         pdu.setCommand( api.GETNEXT_REQ_MSG );
  165.         // need to save the root OID to walk sub-tree
  166.         SnmpOID oid = new SnmpOID(opt.remArgs[1]);
  167.         int rootoid[] = (int[]) oid.toValue();  
  168.         if (rootoid == null) //if don't have a valid OID for first, exit
  169.         {
  170.             System.err.println("Invalid OID argument: " + opt.remArgs[1]);
  171.             System.exit(1);
  172.         }
  173.         else
  174.         {
  175.             pdu.addNull(oid);
  176.         }
  177.         try
  178.         {
  179.             session.open();
  180.         }
  181.         catch (SnmpException e)
  182.         {
  183.             System.err.println("Error in open session "+e.getMessage());
  184.             System.exit(1);
  185.         }
  186.         
  187.         if(session.getVersion()==SnmpAPI.SNMP_VERSION_3)
  188.         {
  189.             System.out.println("UserName = " + setVal.userName);
  190.             pdu.setUserName(setVal.userName.getBytes());
  191.             try
  192.             {
  193.                 USMUtils.init_v3_parameters(
  194.                 setVal.userName,
  195. null,
  196.                 setVal.authProtocol,
  197.                 setVal.authPassword,
  198.                 setVal.privPassword,
  199.                 ses_opt,
  200.                 session,
  201. false,
  202. setVal.privProtocol);
  203.             }
  204.             catch(Exception exp)
  205.             {
  206.                 System.out.println(exp.getMessage());
  207.                 System.exit(1);
  208.             }
  209.             pdu.setContextName(setVal.contextName.getBytes());
  210.             pdu.setContextID(setVal.contextID.getBytes());
  211.         }
  212.         // loop for each PDU in the walk
  213.         while (true) // until received OID isn't in sub-tree
  214.         {
  215.             try
  216.             {
  217.                 // Send PDU and receive response PDU
  218.                 pdu = session.syncSend(pdu);
  219.             }
  220.             catch (SnmpException e)
  221.             {
  222.                 System.err.println("Sending PDU"+e.getMessage());
  223.                 System.exit(1);
  224.             }
  225.             if (pdu == null)
  226.             {
  227.                 // timeout
  228.                 System.out.println("Request timed out to: " + opt.remArgs[0] );
  229.                 System.exit(1);
  230.             }
  231.             // stop if outside sub-tree
  232.             if (!isInSubTree(rootoid,pdu))
  233.             {
  234.                 System.out.println("Not in sub tree.");
  235.                 break; 
  236.             }
  237.             int version = pdu.getVersion();
  238.             if(version == SnmpAPI.SNMP_VERSION_1)
  239.             {
  240.                 // check for error 
  241.                 if (pdu.getErrstat() != 0)
  242.                 {
  243.                     System.out.println("Error Indication in response: " +
  244.                         SnmpException.exceptionString((byte)pdu.getErrstat()) + 
  245.                         "nErrindex: " + pdu.getErrindex()); 
  246.                     System.exit(1);
  247.                 }
  248.                 // print response pdu variable-bindings                    
  249.                 System.out.println(pdu.printVarBinds());
  250.             }
  251.             else if((version == SnmpAPI.SNMP_VERSION_2C) ||
  252.                 (version == SnmpAPI.SNMP_VERSION_3))
  253.             {
  254.                 
  255.                 Enumeration e = pdu.getVariableBindings().elements();
  256.                 while(e.hasMoreElements())
  257.                 {
  258.                     int error = 0;
  259.                     SnmpVarBind varbind = (SnmpVarBind)e.nextElement();
  260.                     // check for error
  261.                     if ( (error = varbind.getErrindex()) != 0)
  262.                     {
  263.                         System.out.println("Error Indication in response: " +
  264.                             SnmpException.exceptionString((byte)error));
  265.                         System.exit(1);
  266.                     }
  267.                     // print response pdu variable-bindings
  268.                     System.out.println(pdu.printVarBinds());
  269.                 }
  270.             }
  271.             else
  272.             {
  273.                 System.out.println("Invalid Version Number");
  274.             }
  275.             // set GETNEXT_REQ_MSG to do walk
  276.             // Don't forget to set request id to 0 otherwise next request will fail
  277.             pdu.setReqid(0);
  278.             SnmpOID first_oid = pdu.getObjectID(0);
  279.             pdu = new SnmpPDU();
  280.             pdu.setCommand( api.GETNEXT_REQ_MSG );
  281.             pdu.setUserName(setVal.userName.getBytes());
  282.             pdu.setContextName(setVal.contextName.getBytes());
  283.             pdu.setContextID(setVal.contextID.getBytes());
  284.             pdu.addNull(first_oid);
  285.         } // end of while true
  286.         
  287.         // Print the GroupCounters
  288.         String[] localAddr = ses_opt.getLocalAddresses();
  289.         int localPort = ses_opt.getLocalPort();
  290.         SnmpGroup group = api.getSnmpGroup(localAddr[localAddr.length - 1],localPort);
  291.         if(group != null)
  292.         {
  293.             System.out.println("The SnmpGroup Counter values :");
  294.             System.out.println("snmpInPkts = " + group.getSnmpInPkts());
  295.             System.out.println("snmpOutPkts = " + group.getSnmpOutPkts());
  296.             System.out.println("snmpInGetResponses = " + group.getSnmpInGetResponses());
  297.             System.out.println("snmpOutGetRequests = " + group.getSnmpOutGetRequests());
  298.             System.out.println("snmpOutGetNexts = " + group.getSnmpOutGetNexts());
  299.         }   
  300.         // close session
  301.         session.close();
  302.         // stop api thread
  303.         api.close();
  304.         System.exit(0);
  305.     }
  306.     /** check if first varbind oid has rootoid as an ancestor in MIB tree */
  307.     static boolean isInSubTree(int[] rootoid, SnmpPDU pdu)
  308.     {
  309.         SnmpOID objID = (SnmpOID) pdu.getObjectID(0);
  310.         if (objID == null)
  311.         {
  312.             return false;
  313.         }
  314.         int oid[] = (int[]) objID.toValue();
  315.         if (oid == null)
  316.         {
  317.             return false;        
  318.         }
  319.         if (oid.length < rootoid.length)
  320.         {
  321.             return false;
  322.         }
  323.         for (int i=0;i<rootoid.length;i++)
  324.         {
  325.             if (oid[i] != rootoid[i])
  326.             {
  327.                 return false;
  328.             }
  329.         }
  330.         return true;
  331.     }
  332. }