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

SNMP编程

开发平台:

C/C++

  1. /* $Id: snmpv3trapd.src,v 1.4.2.7 2009/01/28 13:31:51 tmanoj Exp $ */
  2. /*
  3.  * @(#)snmpv3trapd.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 for receiving traps using the
  9.  * 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 snmpv3trapd [options]
  13.  *
  14.  * java snmpv3trapd [-d] [-p port][-c community] [-u user] [-e engineID] [-a authProtocol] [-w auth_password] [-s priv_password] [-pp privProtocol(DES/AES-128/AES-192/AES-256/3DES)]
  15.  * e.g. 
  16.  * java snmpv3trapd -p 162 -c public 
  17.  * 
  18.  * Options:
  19.  * [-d]                - Debug output. By default off.
  20.  * [-p] <port>         - remote port no. By default 162.
  21.  * [-c] <community>    - community String. By default "public".               
  22.  */
  23. import java.lang.*;
  24. import java.util.*;
  25. import java.net.*;
  26. import com.adventnet.snmp.snmp2.*;
  27. import com.adventnet.snmp.snmp2.usm.*;
  28. public class snmpv3trapd implements SnmpClient {
  29.     private final static int PORT = 1;
  30.     private final static int COMMUNITY = 2;
  31.     private final static int USER_NAME = 3;
  32.     private final static int ENGID = 4;
  33.     private final static int AUTH_PROTOCOL = 5;
  34.     private final static int AUTH_PASSWORD = 6;
  35.     private final static int PRIV_PASSWORD = 7;
  36.     static final int USM_SECURITY_MODEL = 3;
  37.     private final static int PRIV_PROTOCOL=8;
  38.     static SnmpAPI api;
  39.     public static void main(String args[]) {
  40.         
  41.         System.out.println("Please wait till the snmpv3trapd initializes ...");
  42.         // Take care of getting options
  43.         String usage = "snmpv3trapd [-d] [-p port] [-c community] [-u user] [-e engineID(0x...)] [-a authProtocol] [-w auth_password] [-s priv_password] [-pp privProtocol(DES/AES-128/AES-192/AES-256/3DES)]";
  44.         String options[] = { "-d", "-p", "-c", "-u", "-e", "-a", "-w", "-s", "-pp"};
  45.         String values[] = { "None", null, null, null, null, null, null, null,null};
  46.         ParseOptions opt = new ParseOptions(args,options,values, usage);
  47.         String userName = null;
  48.         int authProtocol = USMUserEntry.NO_AUTH;
  49.         int privProtocol = USMUserEntry.NO_PRIV;
  50.         String authPassword = new String ("");
  51.         String privPassword = new String ("");
  52.         String engineID = null;
  53.         byte secLevel = 0;
  54.                 int portNo=162; // Default port number at which receiver listens.
  55.         // Start SNMP API
  56.         api = new SnmpAPI();
  57.         if (values[0].equals("Set")) api.setDebug( true );
  58.         
  59.         if (opt.remArgs.length>0) opt.usage_error();
  60.         // Open session 
  61.         SnmpSession session = new SnmpSession(api);
  62.         session.addSnmpClient(new snmpv3trapd());
  63.         // set local port
  64.         try {
  65.             if (values[PORT] != null) 
  66.                         {
  67.                             portNo = Integer.parseInt(values[PORT]);
  68.                         }
  69.             UDPProtocolOptions ses_opt = new UDPProtocolOptions();
  70.             ses_opt.setLocalPort(portNo);
  71.             session.setProtocolOptions(ses_opt);
  72.             if (values[USER_NAME] != null) {
  73.                 userName = values[USER_NAME];
  74.             }
  75.             
  76.             if (values[ENGID] != null) {
  77.                 engineID = values[ENGID];
  78.                 if(engineID.startsWith("0x") || engineID.startsWith("0X"))
  79.                     engineID = new String(gethexValue(values[ENGID]));
  80.             }
  81.             
  82.             if (values[AUTH_PROTOCOL] != null) {
  83.                 if ( values[AUTH_PROTOCOL].equals("SHA")){
  84.                     authProtocol = USMUserEntry.SHA_AUTH;
  85.                     secLevel |= 0x01;
  86.                 }
  87.                 else if ( values[AUTH_PROTOCOL].equals("MD5")){
  88.                     authProtocol = USMUserEntry.MD5_AUTH;
  89.                     secLevel |= 0x01;
  90.                 }
  91.                 else
  92.                     authProtocol = USMUserEntry.NO_AUTH;
  93.             }
  94.             
  95.             if (values[AUTH_PASSWORD] != null) {
  96.                 if (secLevel == 0x01)
  97.                     authPassword = values[AUTH_PASSWORD];
  98.                 else
  99.                     opt.usage_error();
  100.             }
  101.             
  102.             if(values[PRIV_PASSWORD] != null) {
  103.                if(values[PRIV_PROTOCOL] !=null)
  104.     {
  105.   if(values[PRIV_PROTOCOL].equals("DES"))
  106.   {  
  107.      privPassword = values[PRIV_PASSWORD];
  108.      privProtocol=USMUserEntry.CBC_DES;
  109.      secLevel |= 0x02;
  110.   }
  111.   else if(values[PRIV_PROTOCOL].equals("AES-128"))
  112.   {  
  113.      privPassword = values[PRIV_PASSWORD];
  114.      privProtocol=USMUserEntry.CFB_AES_128;
  115.      secLevel |= 0x02;
  116.   }
  117.   else if(values[PRIV_PROTOCOL].equals("AES-192"))
  118.   {  
  119.      privPassword = values[PRIV_PASSWORD];
  120.      privProtocol=USMUserEntry.CFB_AES_192 ;
  121.      secLevel |= 0x02;
  122.   }
  123.   else if(values[PRIV_PROTOCOL].equals("AES-256"))
  124.   {  
  125.      privPassword = values[PRIV_PASSWORD];
  126.      privProtocol=USMUserEntry.CFB_AES_256;
  127.      secLevel |= 0x02;
  128.   }
  129.   else if(values[PRIV_PROTOCOL].equals("3DES"))
  130.   {  
  131.      privPassword = values[PRIV_PASSWORD];
  132.      privProtocol=USMUserEntry.CBC_3DES;
  133.      secLevel |= 0x02;
  134.   }
  135.   else
  136.   {
  137.   System.out.println(" Invalid privProtocol ");
  138.    opt.usage_error();
  139.   }
  140.     }
  141.     else
  142.     {
  143.     System.out.println(" Please specify the privProtocol value ");
  144.                      opt.usage_error();
  145.     
  146.     }                   
  147.  
  148.             }
  149.         }
  150.         catch (NumberFormatException ex) {
  151.             System.err.println("Invalid Integer Arg: " + ex.getMessage());
  152.             System.exit(1);
  153.         }
  154.         catch (StringIndexOutOfBoundsException sie){
  155.             System.err.println("Invalid engineID. Please specify proper" +
  156.                                             " hex value. Exception = " + sie);
  157.             opt.usage_error();
  158.         }
  159.         if(userName != null) {
  160.             // Create a new USMUserEntry for the userName and engineID pair.
  161.             USMUserEntry user = new USMUserEntry(userName.getBytes(),
  162.                                                 engineID.getBytes());
  163.             if ((secLevel & 0x01)== 0x01)
  164.             {
  165.                 user.setAuthProtocol(authProtocol);
  166.                 user.setAuthPassword(authPassword.getBytes());
  167.                 // Convert the auth password to key.
  168.                 byte[] authKey = 
  169.                     USMUtils.password_to_key(authProtocol, 
  170.                                             authPassword.getBytes(),
  171.                                             authPassword.getBytes().length,
  172.                                             engineID.getBytes());
  173.                 user.setAuthKey(authKey);
  174.                 if (secLevel == 0x03)
  175.                 {
  176.                     user.setPrivProtocol(privProtocol);
  177.                     user.setPrivPassword(privPassword.getBytes());
  178.                     // Convert the priv password to key.
  179.                     byte[] privKey = USMUtils.password_to_key(authProtocol,
  180.                                             privPassword.getBytes(),
  181.                                             privPassword.getBytes().length,
  182.                                             engineID.getBytes(),privProtocol);
  183.                     user.setPrivKey(privKey);
  184.                 }
  185.             }
  186.             user.setSecurityLevel(secLevel);
  187.             USMUserTable uut = (USMUserTable)api.getSecurityProvider().
  188.                                             getTable(USM_SECURITY_MODEL);
  189.             uut.addEntry(user);
  190.             // create a SnmpEngineEntry for the localhost,port pair
  191.             SnmpEngineEntry e = new SnmpEngineEntry("localhost", portNo);
  192.             e.setEngineID(engineID.getBytes());
  193.             // Add the SnmpEngineEntry reference to USMUserEntry.
  194.             user.setEngineEntry(e);
  195.         }
  196.         // set community in case of v1/v2c
  197.         if(values[COMMUNITY] != null)
  198.             session.setCommunity(values[COMMUNITY]);
  199.         
  200.         // Open the session
  201.         try { 
  202.             session.open(); 
  203.         }
  204.         catch (SnmpException e) {
  205.             System.err.println(e);
  206.             System.exit(1);
  207.         }
  208.         System.out.println("snmpv3trapd ready to receive v1/v2c/v3 traps");
  209.     }
  210.     
  211.     public boolean authenticate(SnmpPDU pdu, String community){
  212.         if(pdu.getVersion() == SnmpAPI.SNMP_VERSION_3)
  213.             return true;
  214.         else
  215.             return (pdu.getCommunity().equals(community));
  216.     }
  217.   
  218.     public boolean callback(SnmpSession session,SnmpPDU pdu, int requestID){
  219.         // check trap version
  220.         if (pdu.getCommand() == api.TRP_REQ_MSG) {
  221.             System.out.println("Trap received from: "
  222.                 +pdu.getProtocolOptions().getSessionId()
  223.                 +", community: " + pdu.getCommunity());
  224.             System.out.println("Enterprise: " + pdu.getEnterprise());
  225.             System.out.println("Agent: " 
  226.                                 + (pdu.getAgentAddress()).getHostAddress());
  227.             System.out.println("TRAP_TYPE: " + pdu.getTrapType());
  228.             System.out.println("SPECIFIC NUMBER: " + pdu.getSpecificType());
  229.             System.out.println("Time: " + pdu.getUpTime()+"nVARBINDS:");
  230.             // print varbinds
  231.             for (Enumeration e = pdu.getVariableBindings().elements();
  232.                                                     e.hasMoreElements();)
  233.                 System.out.println(((SnmpVarBind) e.nextElement()).
  234.                                                     toTagString());
  235.         }
  236.         else if(pdu.getCommand() == api.TRP2_REQ_MSG)
  237.         {
  238.             System.out.println("Trap received from: "
  239.                 + pdu.getProtocolOptions().getSessionId()
  240.                 + ", community: " + pdu.getCommunity());
  241.             for (Enumeration e = pdu.getVariableBindings().elements();
  242.                                                     e.hasMoreElements();)
  243.                 System.out.println(((SnmpVarBind) e.nextElement()).
  244.                                                     toTagString());
  245.         }
  246.         else
  247.             System.err.println("Non trap PDU received.");
  248.         System.out.println(""); // a blank line between traps
  249.         return true;
  250.   
  251.     }
  252.   
  253.     public void debugPrint(String debugOutput){
  254.         System.out.println(debugOutput);
  255.         return;    
  256.     }
  257.     
  258.     private static byte[] gethexValue(String value)
  259.     {
  260.         byte temp;
  261.         byte[] Key=new byte[value.length()/2 - 1];
  262.         String ss,str;
  263.         ss = value.substring(2);
  264.         for(int i = 0; i < ss.length(); i+=2)
  265.         {
  266.             str = ss.substring(i,i+2);
  267.             temp = (byte)Integer.parseInt(str,16);
  268.             Key[i/2] = temp;
  269.         }
  270.         return Key;
  271.     }
  272.     
  273. }