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

SNMP编程

开发平台:

C/C++

  1. /* $Id: sendv2trap.src,v 1.5.2.7 2009/01/28 12:45:56 prathika Exp $ */
  2. /*
  3.  * @(#)sendtrap.java
  4.  * Copyright (c) 1996-2009 AdventNet, Inc. All Rights Reserved.
  5.  * Please read the associated COPYRIGHTS file for more details.
  6.  */
  7. /** 
  8.  *  Send SNMP trap based on command line arguments.  Loads MIBs 
  9.  *  as specified, and converts to/from names for loaded MIB data. 
  10.  *  Since variable types are not input, MIBs have to be loaded for
  11.  *  any variables being used in trap PDU.
  12.  *
  13.  * This is an example program to explain how to write an application to send a
  14.  * Trap message using com.adventnet.snmp.beans package of AdventNetSNMP2 api.
  15.  * The user could run this application by giving any one of the following usage.
  16.  *  
  17.  * Note: Refer README file  
  18.  *
  19.  * If the oid is not starting with a dot (.) it will be prefixed by .1.3.6.1.2.1 .
  20.  * So the entire OID of 1.1.0 will become .1.3.6.1.2.1.1.1.0 . You can also
  21.  * give the entire OID .
  22.  * 
  23.  * If the mib is loaded you can also give string oids in the following formats
  24.  * .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 or system.sysDescr.0 or
  25.  * sysDescr.0 .
  26.  *
  27.  * [-d]                - Debug output. By default off.
  28.  * [-c] <community>    - community String. By default "public".
  29.  * [-p] <port>         - remote port no. By default 161.
  30.  * [-m] <mibs>         - The mibs to be loaded. 
  31.  * [-v] <version>      - version(v2 / v3). By default v2.
  32.  * [-e] <engineID>     - EngineID for this entity.
  33.  * [-u] <username>     - The v3 principal/userName
  34.  * [-a] <autProtocol>  - The authProtocol(MD5/SHA). Mandatory if authPassword is specified
  35.  * [-w] <authPassword> - The authentication password.
  36.  * [-s] <privPassword> - The privacy protocol password. Must be accompanied with auth password and authProtocol fields.
  37.  * [-i] <contextName>  - Context Name.
  38.  * [-pp] <privProtocol> - The privacy protocol . Must be accompanied with auth,priv password and authProtocol fields.
  39.  * <host> Mandatory    - The RemoteHost (agent).Format (string without double qoutes/IpAddress).
  40.  * <timeticks> Mandatory - the value of object sysUpTime when the event occurred
  41.  * <OID-value> Mandatory - Object Identifier  
  42.  * <OID>  Mandatory    - Give multiple no. of Object Identifiers.
  43.  */
  44. import java.lang.*;
  45. import java.util.*;
  46. import java.net.*;
  47. import com.adventnet.snmp.beans.*;
  48. import com.adventnet.snmp.snmp2.SnmpException;
  49. import com.adventnet.snmp.snmp2.SnmpOID;
  50. import com.adventnet.snmp.snmp2.usm.*;
  51. public class sendv2trap {
  52.     private static final int ENGINEID = 4;
  53.     private static final int VERSION = 5;
  54.     private static final int USER_NAME = 6;
  55.     private static final int AUTH_PROTOCOL = 7;
  56.     private static final int AUTH_PASSWORD = 8;
  57.     private static final int PRIV_PASSWORD = 9;
  58.     private static final int CONTEXT_NAME = 10;
  59.     
  60.     private static final int COMMUNITY = 1;
  61.     private static final int PORT = 2;
  62.     private static final int MIBS = 3;
  63.     private static final int DEBUG = 0;
  64.     private static final int AGENTADDRESS = 11;
  65.     private static final int PRIV_PROTOCOL = 12;
  66.     
  67.     public static void main(String args[]) {
  68.     // Take care of getting options
  69.     String usage = "sendv2trap [-d Debug][-v version(v2,v3)] [-c community] [-p port] [-e engineID(1234.../0x1234...)] [-u user] [-a auth_protocol(MD5/SHA)] [-w auth_password] [-s priv_password] [-i contextName] [-g agent-address] [ -pp priv_protocol (DES/AES-128/AES-192/AES-256/3DES) ] [-m MIB_file] host TimeTicksvalue trapOID [OID value] ...";
  70.     String options[] = { "-d", "-c", "-p", "-m", "-e", "-v", "-u", "-a", "-w", "-s", "-i" ,"-g", "-pp"};
  71.     String values[] = { "None", null, null, null,null, null, null, null, null, null, null,null, null};
  72.     String id = new String("");
  73.     boolean agentflag=false;
  74.     long upTime=0;
  75.     ParseOptions opt = new ParseOptions(args,options,values, usage);
  76.     if (opt.remArgs.length<3) opt.usage_error();
  77.     // Use an SNMP target bean to perform SNMP operations
  78.     SnmpTarget target = new SnmpTarget();
  79.      //To load MIBs from compiled file
  80.      target.setLoadFromCompiledMibs(true);
  81.     // Set Debug mode
  82.     if (values[DEBUG].equals("Set")) target.setDebug(true);
  83.     target.setTargetHost( opt.remArgs[0] );  // set destination hostname
  84.     
  85.     //Assign the port for sending the trap.
  86.     target.setTargetPort(162);
  87.     if(values[PORT]!=null) {
  88.         try {
  89.             target.setTargetPort(Integer.parseInt(values[PORT]));
  90.         }
  91.         catch(NumberFormatException e) {
  92.             System.err.println("Sending trap to port 162");
  93.         }
  94.     }
  95.     try {
  96.         upTime = Long.parseLong(opt.remArgs[1]);
  97.     } catch (NumberFormatException ex) {
  98.         System.err.println("Invalid Integer Argument for upTime "+ex);
  99.         opt.usage_error();
  100.     }
  101.     
  102.     target.setSnmpVersion(target.VERSION2C);
  103.     if (values[VERSION] != null) // set the version if specified
  104.         if(values[VERSION].equals("v3"))
  105.             target.setSnmpVersion(target.VERSION3);
  106.     if(target.getSnmpVersion()== target.VERSION3) {
  107.         if(values[ENGINEID] != null){
  108.             id =  values[ENGINEID];
  109.             if(id.startsWith("0x") || id.startsWith("0X"))
  110.                 id = new String(gethexValue(values[ENGINEID]));
  111.         }
  112.         if (values[USER_NAME] != null) {
  113.             target.setPrincipal(values[USER_NAME]);
  114.         
  115.         if ((values[AUTH_PROTOCOL] != null) && (values[AUTH_PASSWORD] != null)) {
  116.             if(values[AUTH_PROTOCOL].equals("SHA"))
  117.                 target.setAuthProtocol(target.SHA_AUTH);
  118.             else if(values[AUTH_PROTOCOL].equals("MD5"))
  119.                 target.setAuthProtocol(target.MD5_AUTH);
  120.             else
  121.                 target.setAuthProtocol(target.NO_AUTH);            
  122.             target.setAuthPassword(values[AUTH_PASSWORD]);
  123.             if (values[PRIV_PASSWORD] != null) 
  124.             {
  125.             target.setPrivPassword(values[PRIV_PASSWORD]);
  126.             if(values[PRIV_PROTOCOL] != null)
  127.             {
  128.                     if(values[PRIV_PROTOCOL].equals("AES-128"))
  129.                     {
  130.                        target.setPrivProtocol(target.CFB_AES_128);
  131.                     }
  132.     else if(values[PRIV_PROTOCOL].equals("AES-192"))
  133.                     {
  134.                        target.setPrivProtocol(target.CFB_AES_192);
  135.                     }
  136.     else if(values[PRIV_PROTOCOL].equals("AES-256"))
  137.                     {
  138.                        target.setPrivProtocol(target.CFB_AES_256);
  139.                     }
  140.     else if(values[PRIV_PROTOCOL].equals("3DES"))
  141.                     {
  142.                        target.setPrivProtocol(target.CBC_3DES);
  143.                     }
  144.                     else if(values[PRIV_PROTOCOL].equals("DES"))
  145.                     {
  146.                        target.setPrivProtocol(target.CBC_DES);
  147.                     }
  148.                     else
  149.                     {
  150.                      System.out.println(" Invalid PrivProtocol "+values[PRIV_PROTOCOL]);
  151.                      opt.usage_error();
  152.                     }
  153.             }
  154.         }
  155.         }
  156.         else if ((values[AUTH_PROTOCOL] != null) || (values[AUTH_PASSWORD] != null) || (values[PRIV_PASSWORD] != null)) {
  157.             opt.usage_error();
  158.         }
  159.         }
  160.         else {
  161.             System.err.println("UserName Missing");
  162.             opt.usage_error();
  163.         }
  164.         // Configure the USM entries on this entity.
  165.         createUSMTable(target.getPrincipal().getBytes(),id.getBytes(),
  166.                         target.getAuthProtocol(),target.getAuthPassword(),target.getPrivProtocol(),
  167.                         target.getPrivPassword(), target);
  168.     }
  169.     String community="";
  170.     int extraVarCount=0;
  171.     String agentAddress="";
  172.     if(values[COMMUNITY] != null)
  173.     {
  174.           target.setCommunity( values[COMMUNITY]);
  175.             community=values[COMMUNITY];
  176.             extraVarCount++;                    
  177.     }
  178.     if (values[MIBS] != null) try {  // Load the MIB files 
  179.         System.err.println("Loading MIBs: "+values[MIBS]);
  180.         target.loadMibs(values[MIBS]);
  181.         System.err.println("Done.");
  182.     } catch (Exception ex) {
  183.         System.err.println("Error loading MIBs: "+ex);
  184.     System.exit(1);
  185.     }
  186.     if (values[AGENTADDRESS] != null) 
  187.     {  // Load the MIB files 
  188.         agentAddress=values[AGENTADDRESS];
  189.         extraVarCount++;
  190.     }
  191.     // Put together OID and variable value lists from command line
  192.     String oids[] = null, var_values[] = null;  // trap oids and values
  193.     int num_varbinds = 0;
  194.     for (int i=3;i<opt.remArgs.length;i+=2) { // add Variable Bindings
  195.         if (opt.remArgs.length < i+2) //need "{OID type value}"
  196.            opt.usage_error(); 
  197.         num_varbinds++;
  198.     }
  199.      oids = new String[num_varbinds+extraVarCount];
  200.     var_values = new String[num_varbinds+extraVarCount];
  201.     if(!agentAddress.equals(""))
  202.     {
  203.         oids[0]=".1.3.6.1.6.3.18.1.3.0";
  204.         var_values[0]=agentAddress; 
  205.         if(target.getMibOperations()!=null)
  206.         {
  207.             if(target.getMibOperations().getMibNode(new SnmpOID(".1.3.6.1.6.3.18.1.3.0"))==null)
  208.             {
  209.                 System.out.println("Error : SNMP-TARGET and SNMP-COMMUNITY mibs are not loaded");       
  210.                 System.exit(0);
  211.             }
  212.         }
  213.         else
  214.         {
  215.             System.out.println("Error : SNMP-TARGET and SNMP-COMMUNITY mibs are not loaded");       
  216.             System.exit(0);
  217.         }
  218.     }
  219.         if(!community.equals(""))
  220.         {               
  221.             if(agentflag)//if agent details are given in command line.
  222.             {
  223.                 oids[1]=".1.3.6.1.6.3.18.1.4.0";
  224.                 var_values[1]=community;    
  225.             }
  226.             else//if agent details are not given in command line.
  227.             {
  228.                 oids[0]=".1.3.6.1.6.3.18.1.4.0";
  229.                 var_values[0]=community;
  230.             }
  231.             if(target.getMibOperations()!=null)
  232.             {
  233.                 if(target.getMibOperations().getMibNode(new SnmpOID(".1.3.6.1.6.3.18.1.4.0"))==null)
  234.                 {
  235.                     System.out.println("Error : SNMP-TARGET and SNMP-COMMUNITY mibs are not loaded");       
  236.                     System.exit(0);
  237.                 }
  238.             }
  239.             else
  240.             {
  241.                 System.out.println("Error : SNMP-TARGET and SNMP-COMMUNITY mibs are not loaded");       
  242.                 System.exit(0);
  243.             }
  244.         }
  245.     for (int i=0;i<num_varbinds;i++) { // add Variable Bindings
  246.         oids[i+extraVarCount] = opt.remArgs[(2*i)+3];
  247.         var_values[i+extraVarCount] = opt.remArgs[(2*i)+4];
  248.      }
  249.     try {  // use SnmpTarget methods to send trap w/ specified OIDs/values
  250.         target.setObjectIDList(oids);
  251.         target.snmpSendNotification(upTime, opt.remArgs[2], var_values);
  252.         // allow time to send trap before exiting
  253.         Thread.sleep(500);
  254.     } catch (Exception e) {
  255.         System.err.println("Error Sending Trap: "+e.getMessage());
  256.     }
  257.     
  258.     if (target.getErrorCode() != -1)    {
  259.         System.out.println(target.getErrorString());
  260.     }
  261.     System.exit(0);
  262.     
  263.     }
  264.     public static void createUSMTable(byte[] name, byte[] engineID, 
  265.                                     int authProtocol, String authPassword,
  266.                                     int privProtocol,String privPassword, SnmpTarget target)
  267.     {
  268.         byte level = 0;
  269.     
  270.         USMUserTable uut = target.getUSMTable();
  271.         USMUserEntry entry = new USMUserEntry(name, engineID);
  272.         entry.setAuthProtocol(authProtocol);
  273.         if ((authProtocol != USMUserEntry.NO_AUTH) && (authPassword != null))
  274.         {
  275.             byte[] authKey = USMUtils.password_to_key(authProtocol, 
  276.                                             authPassword.getBytes(), 
  277.                                             authPassword.getBytes().length,
  278.                                             engineID);
  279.             entry.setAuthKey(authKey);
  280.             level = 1;
  281.             
  282.             if ((privPassword != null)&&(privPassword.length()>0))
  283.             {
  284.                 byte tempkey[] =null;
  285.                  
  286. if( privProtocol == USMUserEntry.CFB_AES_192 || privProtocol == USMUserEntry.CFB_AES_256 || privProtocol == USMUserEntry.CBC_3DES)
  287. {
  288. tempkey= USMUtils.password_to_key(authProtocol,
  289. privPassword.getBytes(),
  290. privPassword.length(),
  291. engineID,
  292. privProtocol);
  293. }
  294. else
  295. {
  296.  tempkey = USMUtils.password_to_key(authProtocol,
  297. privPassword.getBytes(),
  298. privPassword.length(),
  299. engineID);
  300. }       
  301.                 byte privKey[]=new byte[tempkey.length];
  302.                 System.arraycopy(tempkey,0,privKey,0,tempkey.length);
  303.                 entry.setPrivProtocol(privProtocol);
  304.                 entry.setPrivKey(privKey);
  305.                 level |= 2;
  306.             }
  307.         }
  308.     
  309.         entry.setSecurityLevel(level);
  310.         uut.addEntry(entry);
  311.         target.setSnmpEngineID(engineID);
  312.     }
  313.     private static byte[] gethexValue(String value)
  314.     {
  315.         byte temp;
  316.         byte[] Key=new byte[value.length()/2 - 1];
  317.         String ss,str;
  318.         ss = value.substring(2);
  319.         for(int i = 0; i < ss.length(); i+=2)
  320.         {
  321.             str = ss.substring(i,i+2);
  322.             temp = (byte)Integer.parseInt(str,16);
  323.             Key[i/2] = temp;
  324.         }
  325.         return Key;    
  326.     }
  327. }