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

SNMP编程

开发平台:

C/C++

  1. /* $Id: snmpset.src,v 1.4 2002/09/09 05:43:43 pushpar Exp $ */
  2. /*
  3.  * @(#)snmpset.java
  4.  * Copyright (c) 1996-2003 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 SET using com.adventnet.snmp.snmp2 and
  10.  * com.adventnet.snmp.mibs packages of AdventNetSNMP2 api.
  11.  * The user could run this application by giving any one of the following usage.
  12.  *  
  13.  * java snmpset [options] hostname oid value [oid value] ...
  14.  *
  15.  * v1 request:
  16.  * java snmpset [-d] [-c community] [-wc writeCommunity] [-p port] [-t timeout] [-r retries] MIB_files host [OID value] ...
  17.  * e.g. 
  18.  * java snmpset -p 161 -c public  ../../../mibs/RFC1213-MIB adventnet 1.1.0 advent-machine 1.4.0 contact-advent
  19.  *<img SRC="images/v2candv3only.jpg" ALT="v2c and v3 only">
  20.  * v2c request:
  21.  * java snmpset [-d] [-v version(v1,v2)] [-c community] [-wc writeCommunity] [-p port] [-t timeout] [-r retries] MIB_files host [OID value] ...
  22.  * e.g. For v1 request give -v v1 or drop the option -v .
  23.  * java snmpset -p 161 -v v2 -c public ../../../mibs/RFC1213-MIB adventnet 1.7.0 76
  24.  *<img SRC="images/v3only.jpg" ALT="v3 only"> 
  25.  * v3 request:  
  26.  * java snmpset [-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] [-n contextName] [-i contextID] MIB_File host [OID value] ...
  27.  * e.g.
  28.  * java snmpset  ../../../mibs/RFC1213-MIB -v v3 -u initial2 -w initial2Pass -a MD5 10.3.2.120 1.5.0 whatever
  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.  * If the mib is loaded you can also give string oids in the following formats
  35.  * .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 or system.sysDescr.0 or
  36.  * sysDescr.0 .
  37.  * 
  38.  * Options:
  39.  * [-d]                - Debug output. By default off.
  40.  * [-c] <community>    - community String. By default "public".
  41.  * [-wc]<write community> - write community String. By default "public".
  42.  * [-p] <port>         - remote port no. By default 161.
  43.  * [-t] <Timeout>      - Timeout. By default 5000ms.
  44.  * [-r] <Retries>      - Retries. By default 0. 
  45.  *<img SRC="images/v3only.jpg" ALT="v3 only"> [-v] <version>      - version(v1 / v2 / v3). By default v1.
  46.  * [-u] <username>     - The v3 principal/userName
  47.  * [-a] <autProtocol>  - The authProtocol(MD5/SHA). Mandatory if authPassword is specified
  48.  * [-w] <authPassword> - The authentication password.
  49.  * [-s] <privPassword> - The privacy protocol password. Must be accompanied with auth password and authProtocol fields.
  50.  * [-i] <contextName>  - The contextName to be used for the v3 pdu.
  51.  * [-n] <contextID>    - The contextID to be used for the v3 pdu.
  52.  * <MIBfile> Mandatory - MIB files.To load multiple mibs give within double quotes files seperated by a blank space.       
  53.  * <host>  Mandatory   - The RemoteHost (agent).Format (string without double qoutes/IpAddress).
  54.  * <OID>   Mandatory   - Object Identifier.
  55.  * <value> Mandatory   - The object instance value to be set .
  56.  */
  57. import java.lang.*;
  58. import java.util.*;
  59. import java.net.*;
  60. import com.adventnet.snmp.snmp2.*;
  61. import com.adventnet.snmp.mibs.*;
  62. import com.adventnet.snmp.snmp2.usm.*;
  63. public class snmpset {
  64.     private static final int DEBUG = 0;
  65.     
  66.     
  67.     public static void main(String args[]) {
  68.     // Take care of getting options
  69.     String usage = "snmpset [-d] [-v version(v1,v2,v3)] [-c community] [-wc writeCommunity] [-p port] [-r retries] [-t timeout] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-n contextName] [-i contextID]  MIB_files host OID value [OID value] ...";
  70.     String options[] = { "-d", "-c", "-wc", "-p", "-r", "-t", "-v", "-u", "-a", "-w", "-s", "-n", "-i"};
  71.     String values[] = { "None", null, null, null, null, null, null, null, null, null, null, null, null };
  72.     ParseOptions opt = new ParseOptions(args,options,values,usage);
  73.     if (opt.remArgs.length<4) opt.usage_error();
  74.     // Start SNMP API
  75.     SnmpAPI api;
  76.     api = new SnmpAPI();
  77.     if (values[DEBUG].equals("Set")) api.setDebug( true );
  78.     
  79.     // Open session
  80.     SnmpSession session = new SnmpSession(api);
  81.     // set remote Host
  82.     session.setPeername( opt.remArgs[1] );
  83.     // set values
  84.     SetValues setVal = new SetValues(session, values);
  85.     if(setVal.usage_error) opt.usage_error();
  86.     // Loading MIBS
  87.     MibOperations mibOps = new MibOperations();
  88.  
  89.     // To load MIBs from compiled file
  90.  mibOps.setLoadFromCompiledMibs(true);
  91.     if (opt.remArgs[0] != null) try {
  92.         System.err.println("Loading MIBs: "+opt.remArgs[0]);
  93.         mibOps.loadMibModules(opt.remArgs[0]);
  94.     } catch (Exception ex) {
  95.         System.err.println("Error loading MIBs: "+ex.getMessage());
  96.         System.exit(1);
  97.     }
  98.     // Build set request PDU 
  99.     SnmpPDU pdu = new SnmpPDU();
  100.     pdu.setCommand( api.SET_REQ_MSG );
  101.    
  102.     // add Variable Bindings
  103.     for (int i=2;i<opt.remArgs.length;) { 
  104.         if (opt.remArgs.length < i+2) opt.usage_error(); //need "{OID value}"
  105.         SnmpOID oid = mibOps.getSnmpOID(opt.remArgs[i++]);
  106.         if (oid == null) 
  107.             System.exit(1);
  108.          else
  109.         {
  110.             // Get the MibNode for this SnmpOID instance if found 
  111.             MibNode node = mibOps.getMibNode(oid);
  112.             if (node == null) 
  113.                 System.err.println("Failed. MIB node unavailable for OID.");
  114.             else
  115.             {
  116.                 // Get the syntax associated with this node
  117.                 if (node.getSyntax() == null) 
  118.                     System.err.println("Failed. OID not a leaf node or.");
  119.                 else
  120.                 {
  121.                     SnmpVarBind varbind = null;
  122.                     try {
  123.                         // Get the SnmpVar instance for the value
  124.                         SnmpVar var = node.getSyntax().createVariable(opt.remArgs[i++]);
  125.                         // Create SnmpVarBind instance 
  126.                         varbind = new SnmpVarBind(oid,var);
  127.                         
  128.                     } catch (SnmpException ex) { 
  129.                         System.err.println("Error creating variable."); 
  130.                     }
  131.                     // Add the variable-bindings to the PDU
  132.                     pdu.addVariableBinding(varbind);      
  133.                 }
  134.             }
  135.         }
  136.     } // end of add variable bindings
  137.     try {
  138.         session.open();
  139.         // Send PDU
  140.     } catch (SnmpException e) { 
  141.         System.err.println("Error opening seesion");
  142.         System.exit(1);
  143.     }
  144.     
  145.     if(session.getVersion()==SnmpAPI.SNMP_VERSION_3) {
  146. pdu.setUserName(setVal.userName.getBytes());
  147.         USMUtils.init_v3_params(setVal.userName, setVal.authProtocol, setVal.authPassword, setVal.privPassword, session.getPeername(),session.getRemotePort(),session);
  148.         pdu.setContextName(setVal.contextName.getBytes());
  149.         pdu.setContextID(setVal.contextID.getBytes());
  150.     }
  151.     try {
  152.         // Send PDU
  153.         pdu = session.syncSend(pdu);
  154.     } catch (SnmpException e) {
  155.         System.err.println("Sending PDU"+e.getMessage());
  156.         System.exit(1);
  157.     }
  158.     if (pdu == null) {
  159.         // timeout
  160.         System.out.println("Request timed out to: " + opt.remArgs[0] );
  161.         System.exit(1);
  162.     }
  163.     // print and exit
  164.     System.out.println("Response Received from "+ pdu.getRemoteHost());
  165.     // Check for error in response
  166.     if (pdu.getErrstat() != 0) 
  167.         System.err.println("Error in response: " + mibOps.getErrorString(pdu));
  168.     else {
  169.         // print the response pdu varbinds
  170.         System.out.println(mibOps.varBindsToString(pdu));
  171.         // print the response pdu
  172.         System.out.println(mibOps.toString(pdu));
  173.     }
  174.     // close session
  175.     session.close();
  176.     // stop api thread
  177.     api.close();
  178.     
  179.     System.exit(0);
  180.   }
  181. }