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

SNMP编程

开发平台:

C/C++

  1. /* $Id: snmpbulk.src,v 1.5.2.6 2009/01/28 13:21:46 tmanoj Exp $ */
  2. /*
  3.  * @(#)snmpbulk.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 GETBULK 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.  * Note: The values of non-repeaters max-repetitions should be the last arguments
  14.  *  
  15.  * java snmpbulk [options] hostname oid [oid] ... non-repeaters max-repetitions
  16.  *
  17.  * v2c request:
  18.  * java snmpbulk [-d] [-c community] [-p port] [-t timeout] [-r retries] host OID [OID] ... nonRepeaters maxRepetions
  19.  * e.g. 
  20.  * java snmpbulk -p 161 -c public adventnet 1.2.0 1.2.0 1.5.0 1 2
  21.  *
  22.  * v3 request:
  23.  * java snmpbulk [-d] [-v version(v2,v3)] [-c community] [-p port] [-r retries] [-t timeout] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i contextName] host OID [OID] ... nonRepeaters maxRepetions
  24.  * e.g.
  25.  * java snmpbulk -v v3 -c public -p 161 -u advent -a MD5 -w authPass localhost 1.2.0 1.3.0 1.4.0 1 2
  26.  * 
  27.  * If the oid is not starting with a dot (.) it will be prefixed by .1.3.6.1.2.1 .
  28.  * So the entire OID of 1.1.0 will become .1.3.6.1.2.1.1.1.0 . You can also
  29.  * give the entire OID .
  30.  * 
  31.  * If the mib is loaded you can also give string oids in the following formats
  32.  * .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 or system.sysDescr.0 or
  33.  * sysDescr.0 .
  34.  *
  35.  * Options:
  36.  * [-d]                - Debug output. By default off.
  37.  * [-c] <community>    - community String. By default "public".
  38.  * [-p] <port>         - remote port no. By default 161.
  39.  * [-t] <Timeout>      - Timeout. By default 5000ms.
  40.  * [-r] <Retries>      - Retries. By default 0. 
  41.  * [-v] <version>      - version(v2 / v3).
  42.  * [-u] <username>     - The v3 principal/userName
  43.  * [-a] <autProtocol>  - The authProtocol(MD5/SHA). Mandatory if authPassword is specified
  44.  * [-pp] <privProtocol>- The privProtocol(DES/AES-128/AES-192/AES-256/3DES)
  45.  * [-w] <authPassword> - The authentication password.
  46.  * [-s] <privPassword> - The privacy protocol password. Must be accompanied with auth password and authProtocol fields.
  47.  * [-n] <contextName>  - The contextName to be used for the v3 pdu.
  48.  * [-i] <contextID>    - The contextID to be used for the v3 pdu.
  49.  * <host> Mandatory    - The RemoteHost (agent).Format (string without double qoutes/IpAddress).
  50.  * <OID>  Mandatory    - Give only one Object Identifier.
  51.  * <nonRepeaters>      - non-repeaters. Mandatory
  52.  * <maxRepetions>      - max-repetitions. Mandatory
  53.  */
  54. import java.lang.*;
  55. import java.util.*;
  56. import java.net.*;
  57. import com.adventnet.snmp.snmp2.*;
  58. import com.adventnet.snmp.snmp2.usm.*;
  59. public class snmpbulk
  60. {
  61.     public static void main(String args[])
  62.     {
  63.         // Take care of getting options
  64.         String usage =
  65.             "nsnmpbulk [-d] [-v version(v2,v3)] n" +
  66.             "[-c community] [-p port] [-r retries] n" +
  67.             "[-t timeout] [-u user] [-a auth_protocol] n" +
  68.             "[-w auth_password] [-s priv_password] n" +
  69.             "[-n contextName] [-i contextID] n" +
  70.             "[-DB_driver database_driver]n" +
  71.             "[-DB_url database_url]n" +
  72.             "[-DB_username database_username]n" +
  73.             "[-DB_password database_password]n" +
  74. "[-pp privProtocol(DES/AES-128/AES-192/AES-256/3DES)]n" +
  75. "host OID [OID] ... n" +
  76.             "nonRepeaters maxRepetions";
  77.         String options[] =
  78.         {
  79.             "-d", "-c",  "-wc", "-p", "-r", "-t", "-m",
  80.             "-v", "-u", "-a", "-w", "-s", "-n", "-i",
  81.             "-DB_driver", "-DB_url", "-DB_username", "-DB_password","-pp"
  82.         };
  83.         String values[] =
  84.         {
  85.             "None", null, null, null, null, null, "None",
  86.             null, null, null, null, null, null, null,
  87.             null, null, null, null,null
  88.         };
  89.         
  90.         ParseOptions opt = new ParseOptions(args,options,values, usage);
  91.         // Start SNMP API
  92.         SnmpAPI api;
  93.         api = new SnmpAPI();
  94.         if (values[0].equals("Set"))
  95.         {
  96.             api.setDebug( true );        
  97.         }
  98.         if (opt.remArgs.length<4)
  99.         {
  100.             opt.usage_error();
  101.         }
  102.         // Open session
  103.         SnmpSession session = new SnmpSession(api);
  104.         int PORT = 3;
  105.         
  106.         SnmpPDU pdu = new SnmpPDU();
  107.         UDPProtocolOptions ses_opt = new UDPProtocolOptions();
  108.         ses_opt.setRemoteHost(opt.remArgs[0]);
  109.         if(values[PORT] != null)
  110.         {
  111.             try
  112.             {
  113.                 ses_opt.setRemotePort(Integer.parseInt(values[PORT]));
  114.             }
  115.             catch(Exception exp)
  116.             {
  117.                 System.out.println("Invalid port: " + values[PORT]);
  118.                 System.exit(1);
  119.             }
  120.         }
  121.         pdu.setProtocolOptions(ses_opt);
  122.         //set the values
  123.         SetValues setVal = new SetValues(session, values);
  124.         if(setVal.usage_error)
  125.         {
  126.             opt.usage_error();
  127.         }
  128.         // set version for default
  129.         if(values[7] == null)
  130.         {
  131.             session.setVersion(SnmpAPI.SNMP_VERSION_2C);
  132.         }
  133.         if(session.getVersion()==SnmpAPI.SNMP_VERSION_1)
  134.         {
  135.             opt.usage_error();
  136.         }
  137.         String driver = values[14];
  138.         String url = values[15];
  139.         String username = values[16];
  140.         String password = values[17];
  141.         if(driver != null || url != null ||
  142.             username != null || password != null)
  143.         {
  144.             if(session.getVersion() != 3)
  145.             {
  146.                 System.out.println(
  147.                     "Database option can be used only for SNMPv3.");
  148.                 System.exit(1);
  149.             }
  150.             if(driver == null)
  151.             {
  152.                 System.out.println(
  153.                     "The Database driver name should be given.");
  154.                 System.exit(1);
  155.             }
  156.             if(url == null)
  157.             {
  158.                 System.out.println("The Database URL should be given.");
  159.                 System.exit(1);
  160.             }
  161.             try
  162.             {
  163.                 api.setV3DatabaseFlag(true);
  164.                 api.initJdbcParams(driver, url, username, password);
  165.             }
  166.             catch(Exception exp)
  167.             {
  168.                 System.out.println("Unable to Establish Database Connection.");
  169.                 System.out.println("Please check the driverName and url.");
  170.                 System.exit(1);
  171.             }
  172.         }
  173.         // Build GetBulk request PDU
  174.        // SnmpPDU pdu = new SnmpPDU();
  175.         pdu.setCommand( api.GETBULK_REQ_MSG );
  176.         // add OIDs
  177.         for (int i=1;i<(opt.remArgs.length)-2;i++)
  178.         {
  179.             SnmpOID oid = new SnmpOID(opt.remArgs[i]);
  180.             if (oid.toValue() == null)
  181.             {
  182.                 System.err.println("Invalid OID argument: " + opt.remArgs[i]);
  183.             }
  184.             else 
  185.             {
  186.                 pdu.addNull(oid);
  187.             }
  188.         }
  189.         try
  190.         {
  191.             // set non-repeaters
  192.             pdu.setErrstat(
  193.                 Integer.parseInt(opt.remArgs[(opt.remArgs.length)-2]) );
  194.         }
  195.         catch(NumberFormatException nfe)
  196.         {
  197.             System.out.println("Non-Repeaters value should be an integer. " +
  198.                 opt.remArgs[(opt.remArgs.length)-2]);
  199.             System.exit(1);
  200.         }
  201.         
  202.         try
  203.         {
  204.             // set max-repetitions
  205.             pdu.setErrindex(
  206.                 Integer.parseInt(opt.remArgs[(opt.remArgs.length)-1]) );
  207.         }
  208.         catch(NumberFormatException nfe)
  209.         {
  210.             System.out.println("Non-Repeaters value should be an integer. " +
  211.                 opt.remArgs[(opt.remArgs.length)-1]);
  212.             System.exit(1);
  213.         }
  214.         try
  215.         {
  216.             // open session
  217.             session.open();
  218.         } 
  219.         catch (SnmpException e)
  220.         {
  221.             System.err.println("Error while opening session " +
  222.                 e.getMessage());
  223.             System.exit(1);
  224.         }
  225.         if(session.getVersion()==SnmpAPI.SNMP_VERSION_3)
  226.         {
  227.             pdu.setUserName(setVal.userName.getBytes());
  228.             try
  229.             {
  230.                 USMUtils.init_v3_parameters(
  231.                 setVal.userName,
  232. null,
  233.                 setVal.authProtocol,
  234.                 setVal.authPassword,
  235.                 setVal.privPassword,
  236.                 ses_opt,
  237.                 session,
  238. false,
  239. setVal.privProtocol);
  240.             }
  241.             catch(Exception exp)
  242.             {
  243.                 System.out.println(exp.getMessage());
  244.                 System.exit(1);
  245.             }
  246.             pdu.setContextName(setVal.contextName.getBytes());
  247.             pdu.setContextID(setVal.contextID.getBytes());
  248.         }
  249.         SnmpPDU res_pdu = null;
  250.         try
  251.         {
  252.             res_pdu = session.syncSend(pdu);
  253.         }
  254.         catch(SnmpException e)
  255.         {
  256.             System.err.println("Sending PDU: " + e.getMessage());
  257.             System.exit(1);
  258.         }
  259.         // timeout
  260.         if (res_pdu == null)
  261.         {
  262.             System.out.println("Request timed out to: " + opt.remArgs[0] );
  263.             System.exit(1);
  264.         }
  265.         // print and exit
  266.         String res = "Response PDU received from " + res_pdu.getProtocolOptions().getSessionId() + ".";
  267.         if(res_pdu.getVersion() < 3)
  268.         {
  269.             res = res + " Community = "" + res_pdu.getCommunity() + "".n";
  270.         }
  271.         System.out.println(res);
  272.         // check for error
  273.         if (res_pdu.getErrstat() != 0)
  274.         {
  275.             System.out.println("Error indication in response: " +
  276.                 SnmpException.exceptionString((byte)res_pdu.getErrstat()) +
  277.                 "nErrindex: " + res_pdu.getErrindex());
  278.         }
  279.         else
  280.         {
  281.             Enumeration e = res_pdu.getVariableBindings().elements();
  282.             while(e.hasMoreElements())
  283.             {
  284.                 int error = 0;
  285.                 SnmpVarBind varbind = (SnmpVarBind)e.nextElement();
  286.                 // check for error index
  287.                 if ( (error = varbind.getErrindex()) != 0)
  288.                 {
  289.                     System.out.println("Error Indication in response: " +
  290.                         SnmpException.exceptionString((byte)error));
  291.                 }
  292.                 // print varbind
  293.                 System.out.println(varbind.toTagString() + "n");
  294.             }
  295.         }
  296.         //close session
  297.         session.close();
  298.         // stop api thread
  299.         api.close();
  300.     }
  301. }