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

SNMP编程

开发平台:

C/C++

  1. /* $Id: snmpv3trap.src,v 1.4.2.5 2009/01/28 13:01:35 prathika Exp $ */
  2. /*
  3.  * @(#)snmpv3trap.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 send a
  9.  * v3 Trap message using com.adventnet.snmp.snmp2 package of AdventNetSNMP2 api.
  10.  * The user could run this application by giving any one of the following usage.
  11.  *  
  12.  * java snmpv3trap [-d] [-p port][-e engineID(0x....)] [-a auth_protocol] [-w auth_password] [-s priv_password] [-pp privProtocol(DES/AES-128/AES-192/AES-256/3DES)] [-i contextName] -m MIB_files userName host TimeTicksvalue OIDvalue [OID value] ...
  13.  * e.g.
  14.  * java snmpv3trap -m "../../../mibs/RFC1213-MIB ../../../mibs/SNMPv2-MIB" -e 0x000012141516171819202121 -a MD5 -w initial2Pass -i initial initial2 10.3.2.120 16352 coldStartTrap ifIndex.2 2
  15.  * 
  16.  * If the oid is not starting with a dot (.) it will be prefixed by .1.3.6.1.2.1 .
  17.  * So the entire OID of 1.1.0 will become .1.3.6.1.2.1.1.1.0 . You can also
  18.  * give the entire OID .
  19.  * 
  20.  * If the mib is loaded you can also give string oids in the following formats
  21.  * .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 or system.sysDescr.0 or
  22.  * sysDescr.0 .
  23.  *
  24.  * Options:
  25.  * [-d]                  - Debug output. By default off.
  26.  * [-p] <port>           - remote port no. By default 162.
  27.  * [-e] <engineID>       - Engine ID.
  28.  * [-a] <autProtocol>    - The authProtocol(MD5/SHA). Mandatory if authPassword is specified
  29.  * [-w] <authPassword>   - The authentication password.
  30.  * [-s] <privPassword>   - The privacy protocol password. Must be accompanied with auth password and authProtocol fields.
  31.  * [-pp]<privProtocol>   - The privacy protocol (DES/AES-128/AES-192/AES-256/3DES)
  32.  * [-n] <contextName>    - The context to be used for the v3 pdu.
  33.  * [-i] <contextID>      - The contextID to be used for the v3 pdu.
  34.  * -m <MIBfile>          - MIB files.Mandatory.To load multiple mibs give within double quotes files seperated by a blank space.       
  35.  * <timeticks> Mandatory - the value of object sysUpTime when the event occurred
  36.  * <OID-value> Mandatory - Object Identifier  
  37.  * <username>  Mandatory - The v3 principal/userName.
  38.  * <host>      Mandatory - The RemoteHost (agent).Format (string without double qoutes/IpAddress).
  39.  * <OID>       Mandatory - Object Identifier.
  40.  * <value>     Mandatory - The object instance value to be set .
  41.  */ 
  42.     
  43. import java.lang.*;
  44. import java.util.*;
  45. import java.net.*;
  46. import com.adventnet.snmp.snmp2.*;
  47. import com.adventnet.snmp.mibs.*;
  48. import com.adventnet.snmp.snmp2.usm.*;
  49. public class snmpv3trap 
  50. {
  51.     private static final int DEBUG = 0;
  52.     private static final int PORT = 1;
  53.     private static final int MIBS = 2;
  54.     private static final int AUTH_PROTOCOL = 3;
  55.     private static final int AUTH_PASSWORD = 4;
  56.     private static final int PRIV_PASSWORD = 5;
  57.     private static final int CONTEXT_NAME = 6;
  58.     private static final int CONTEXT_ID = 7;
  59.     private static final int ENGINEID = 8;
  60.     static final int USM_SECURITY_MODEL = 3;
  61.     private static final int PRIV_PROTOCOL=9;
  62.     public static void main(String args[]) 
  63.     {
  64.         
  65.         // Take care of getting options
  66.         String usage = 
  67.             "nsnmpv3trap [-d] [-p port][-e engineID(0x....)]n"+
  68.             "[-a auth_protocol] [-w auth_password] [-s priv_password]n"+
  69.             "[-n contextName] [-i contextID][-pp privProtocol(DES/AES-128/AES-192/AES-256/3DES)] -m MIB_files userNamen"+
  70.             "host TimeTicksvalue OIDvalue [OID value] ...";
  71.         String options[] = 
  72.             {
  73.                 "-d", "-p", "-m", "-a", "-w", "-s", "-n", "-i", "-e" ,"-pp"
  74.             };
  75.         String values[] = 
  76.             {
  77.                 "None", null, null, null, null, null, null, null, null , null
  78.             };
  79.    
  80.         String id = new String(""); 
  81.         String userName = new String("");
  82.         int authProtocol = USMUserEntry.NO_AUTH;
  83.         int privProtocol = USMUserEntry.NO_PRIV;
  84.         String authPassword = new String ("");
  85.         String privPassword = new String ("");
  86.         String contextName = new String ("");
  87.         String contextID = new String ("");
  88.     
  89.         ParseOptions opt = new ParseOptions(args,options,values, usage);
  90.         if (opt.remArgs.length<4) 
  91.         {
  92.             opt.usage_error();
  93.         }   
  94.                      
  95.         // Start SNMP API
  96.         SnmpAPI api;
  97.         api = new SnmpAPI();
  98.         if (values[DEBUG].equals("Set"))
  99.         {
  100.             api.setDebug( true );
  101.         }   
  102.         
  103.         SnmpPDU pdu = new SnmpPDU();
  104.         Snmp3Message msg = (Snmp3Message)(pdu.getMsg());
  105.         pdu.setCommand( api.TRP2_REQ_MSG );
  106.         // Open session 
  107.         SnmpSession session = new SnmpSession(api);
  108.    
  109.         // set remoteHost
  110.         UDPProtocolOptions ses_opt = new UDPProtocolOptions(opt.remArgs[1]);
  111.         // set version
  112.         session.setVersion( SnmpAPI.SNMP_VERSION_3 ) ;
  113.     
  114.         // set EngineID
  115.         try 
  116.         {        
  117.             if(values[PORT] != null)
  118.             {
  119.                 ses_opt.setRemotePort( Integer.parseInt(values[PORT]) );
  120.             }   
  121.             else
  122.             {
  123.                 ses_opt.setRemotePort(162);
  124.             }   
  125.             
  126.             if (values[ENGINEID]!=null) 
  127.             {
  128.                 id = values[ENGINEID];
  129.                 if(id.startsWith("0x") || id.startsWith("0X"))
  130.                 {
  131.                     id = new String(gethexValue(values[ENGINEID]));
  132.                 }   
  133.             }
  134.         }
  135.         catch (NumberFormatException ex) 
  136.         {
  137.             System.err.println("Invalid Integer Arg");
  138.         }
  139.         catch (StringIndexOutOfBoundsException sie)
  140.         {
  141.             System.err.println("Invalid engineID. Please specify proper" +
  142.                                         " hex value. Exception = " + sie);
  143.             opt.usage_error();
  144.         }
  145.         session.setProtocolOptions(ses_opt);
  146.             
  147.         userName = opt.remArgs[0];
  148.                 
  149.         if ((values[AUTH_PROTOCOL] != null) && (values[AUTH_PASSWORD] != null)) 
  150.         {
  151.             if(values[AUTH_PROTOCOL].equals("SHA"))
  152.             {
  153.                 authProtocol = USMUserEntry.SHA_AUTH;
  154.             }   
  155.             else 
  156.             {
  157.                 authProtocol = USMUserEntry.MD5_AUTH;                   
  158.             }   
  159.             if(authProtocol==USMUserEntry.NO_AUTH)
  160.             {
  161.                 System.err.println("Enter authentication protocol");
  162.                 opt.usage_error();
  163.             }
  164.                     
  165.             authPassword = values[AUTH_PASSWORD];
  166.             if (values[PRIV_PASSWORD] != null) 
  167. {
  168.               privPassword = values[PRIV_PASSWORD];
  169.     if(values[PRIV_PROTOCOL] !=null)
  170.     {
  171.   if(values[PRIV_PROTOCOL].equals("DES"))
  172.   {  
  173.     
  174.      privProtocol=USMUserEntry.CBC_DES;
  175.   }
  176.   else if(values[PRIV_PROTOCOL].equals("AES-128"))
  177.   {  
  178.     
  179.      privProtocol=USMUserEntry.CFB_AES_128;
  180.   }
  181.   else if(values[PRIV_PROTOCOL].equals("AES-192"))
  182.   {  
  183.     
  184.      privProtocol=USMUserEntry.CFB_AES_192;
  185.   }
  186.   else if(values[PRIV_PROTOCOL].equals("AES-256"))
  187.   {  
  188.     
  189.      privProtocol=USMUserEntry.CFB_AES_256;
  190.   }
  191.   else if(values[PRIV_PROTOCOL].equals("3DES"))
  192.   {  
  193.     
  194.      privProtocol=USMUserEntry.CBC_3DES;
  195.   }
  196.   else
  197.   {
  198.   System.out.println(" Invalid privProtocol ");
  199.    opt.usage_error();
  200.   }
  201.     }
  202.     else
  203.     {
  204.     System.out.println(" Please specify the privProtocol value ");
  205.                      opt.usage_error();
  206.     
  207.     }     
  208. }          
  209.         }
  210.         else if ((values[AUTH_PROTOCOL] != null) 
  211.                 || (values[AUTH_PASSWORD] != null) 
  212.                 || (values[PRIV_PASSWORD] != null)) 
  213.         {
  214.             opt.usage_error();
  215.         }
  216.     
  217.         if (values[CONTEXT_NAME] != null)
  218.         {
  219.             contextName = values[CONTEXT_NAME];
  220.         }   
  221.         if (values[CONTEXT_ID] != null) 
  222.         {
  223.             contextID = values[CONTEXT_ID];
  224.         }   
  225.         createUSMTable(userName.getBytes(), id.getBytes(), authProtocol,
  226.            authPassword, privPassword, api,privProtocol);
  227.         pdu.setUserName(userName.getBytes());
  228.     
  229.         // Loading MIBS 
  230.         MibOperations mibOps = new MibOperations();
  231.      
  232.         // To load MIBs from compiled file
  233.          mibOps.setLoadFromCompiledMibs(true);
  234.         if (values[MIBS] != null) 
  235.         {
  236.             try 
  237.             {
  238.                 System.err.println("Loading MIBs: "+values[MIBS]);
  239.                 mibOps.loadMibModules(values[MIBS]);
  240.             }
  241.             catch (Exception ex) 
  242.             {
  243.                 System.err.println("Error loading MIBs: "+ex.getMessage());
  244.             }
  245.         }
  246.         
  247.         // Adding the sysUpTime variable binding 
  248.         SnmpOID oid = mibOps.getSnmpOID(".1.3.6.1.2.1.1.3.0");
  249.         if (oid == null) 
  250.         {
  251.             System.exit(1);
  252.         }   
  253.         else     
  254.         {
  255.             addVarBind(mibOps, pdu, oid, opt.remArgs[2]);
  256.         }   
  257.         // Adding the snmpTrapOID variable binding
  258.          oid = mibOps.getSnmpOID(".1.3.6.1.6.3.1.1.4.1.0");
  259.         if (oid == null) 
  260.         {
  261.             System.exit(1);
  262.         }
  263.         else 
  264.         {
  265.             addVarBind(mibOps, pdu, oid, opt.remArgs[3]);
  266.         }   
  267.     
  268.         // add Variable Bindings
  269.         for (int i=4;i<opt.remArgs.length;) 
  270.         { 
  271.             if (opt.remArgs.length < i+2)
  272.             {
  273.                 opt.usage_error(); //need "{OID value}"
  274.             }
  275.             oid = mibOps.getSnmpOID(opt.remArgs[i++]);       
  276.             if (oid == null)
  277.             { 
  278.                 System.exit(1);
  279.             }
  280.             else 
  281.             {
  282.                 addVarBind(mibOps, pdu, oid, opt.remArgs[i++]);
  283.             }
  284.         } // end of add variable bindings
  285.         try
  286.         {
  287.             // Opening session
  288.             session.open();
  289.             // Send PDU
  290.              session.send(pdu);    
  291.         } 
  292.         catch (SnmpException e) 
  293.         {
  294.             System.err.println("Sending PDU"+e.getMessage());
  295.         }
  296.         // close session    
  297.         session.close();
  298.         // stop api thread
  299.         api.close();
  300.         System.exit(0);
  301.     }
  302.     /** adds the varbind  with specified oid and value */
  303.     static void addVarBind( MibOperations mibOps, SnmpPDU pdu, SnmpOID oid, String value)
  304.     {        
  305.         // Get the MibNode for this SnmpOID instance if found 
  306.         MibNode node = mibOps.getMibNode(oid);
  307.         if (node == null) 
  308.         {
  309.             System.err.println("Failed. MIB node unavailable for OID:"+oid);
  310.         }   
  311.         else
  312.         {
  313.             // Get the syntax associated with this node
  314.             if (node.getSyntax() == null) 
  315.             {
  316.                 System.err.println("Failed. OID not a leaf node.");
  317.             }
  318.             else
  319.             {
  320.                 SnmpVarBind varbind = null;
  321.                 try
  322.                 {
  323.                     LeafSyntax syntx = node.getSyntax();
  324.                     if(syntx.getType() == SnmpAPI.OBJID)
  325.                     {
  326.                         SnmpOID snmpoid = mibOps.getSnmpOID(value);
  327.                         value = snmpoid.toString();
  328.                     }
  329.                     // Get the SnmpVar instance for the value
  330.                     SnmpVar var = syntx.createVariable(value);
  331.                     // Create SnmpVarBind instance 
  332.                     varbind = new SnmpVarBind(oid,var);
  333.                 }
  334.                 catch (SnmpException ex) 
  335.                 { 
  336.                   System.err.println("Error creating variable."); 
  337.                 }
  338.                 // Add the variable-bindings to the PDU
  339.                 pdu.addVariableBinding(varbind);      
  340.             }
  341.         }  
  342.     }
  343.     private static byte[] gethexValue(String value)
  344.     {
  345.         byte temp;
  346.         byte[] Key=new byte[value.length()/2 - 1];
  347.         String ss,str;
  348.         ss = value.substring(2);
  349.         for(int i = 0; i < ss.length(); i+=2)
  350.         {
  351.             str = ss.substring(i,i+2);
  352.             temp = (byte)Integer.parseInt(str,16);
  353.             Key[i/2] = temp;
  354.         }
  355.         return Key;    
  356.     }
  357.     
  358.     public static void createUSMTable(byte[] name, byte[] engineID, 
  359.                                     int authProtocol, String authPassword,
  360.                                     String privPassword, SnmpAPI api, int privProtocol)
  361.     {
  362.         byte level = 0;
  363.     
  364.         USMUserEntry entry = new USMUserEntry(name, engineID);
  365.         entry.setAuthProtocol(authProtocol);
  366.         if ((authProtocol != USMUserEntry.NO_AUTH) && (authPassword != null))
  367.         {
  368.             byte[] authKey = USMUtils.password_to_key(authProtocol, 
  369.                                             authPassword.getBytes(), 
  370.                                             authPassword.getBytes().length,
  371.                                             engineID);
  372.             entry.setAuthKey(authKey);
  373.             level = 1;
  374.             
  375.             if ((privPassword != null)&&(privPassword.length()>0))
  376.             {
  377.                 byte[] tempKey = USMUtils.password_to_key(authProtocol,
  378.                                             privPassword.getBytes(), 
  379.                                             privPassword.getBytes().length,
  380.                                             engineID, privProtocol);
  381.       entry.setPrivProtocol(privProtocol);          
  382.       byte privKey[]=null;
  383. if(privProtocol==USMUserEntry.CFB_AES_192)
  384. {
  385. privKey=new byte[24];
  386. System.arraycopy(tempKey,0,privKey,0,24);
  387. }
  388. else if(privProtocol==USMUserEntry.CFB_AES_256)
  389. {
  390. privKey =new byte[32];
  391. System.arraycopy(tempKey,0,privKey,0,32);
  392. }
  393. else if(privProtocol==USMUserEntry.CBC_3DES)
  394. {
  395. privKey =new byte[32];
  396. System.arraycopy(tempKey,0,privKey,0,32);
  397. }
  398. else
  399. {
  400. privKey=new byte[16];
  401. System.arraycopy(tempKey,0,privKey,0,16);
  402. }
  403.                 entry.setPrivKey(privKey);
  404.                 level |= 2;
  405.             }
  406.         }
  407.     
  408.         entry.setSecurityLevel(level);
  409.         USMUserTable uut = (USMUserTable)api.getSecurityProvider().
  410.                                             getTable(USM_SECURITY_MODEL);
  411.         uut.addEntry(entry);
  412.         api.setSnmpEngineID(engineID);
  413.     }   
  414.   
  415. }