www.pudn.com > SnmpMaster.rar > SnmpCommand.java


package snmpmaster;

import java.lang.*;
import java.util.*;
import java.net.*;
import com.adventnet.snmp.snmp2.*;
import com.adventnet.snmp.snmp2.usm.*;

public class SnmpCommand {
static snmptrapd trapd = new snmptrapd();
  public SnmpCommand() {
  }
  /////////////////////////////////////////////////
  public void ResiveTrap()
  {
  trapd.ResiveTrap();
  }
  ///////////ResiveTrap()///////////////////////////
  /*
  Param:    remoteHost (String)
	    OID        (String)
	    type       (String)
	    value      (String)
  */
  public void SetValue(Hashtable Param)
  {
    String values[] = { "None", null, null, null, null, null, "None", null, null, null, null, null, null, null };

    String remoteHost = (String)Param.get("remoteHost");
    String OID = (String)Param.get("OID");
    String type = (String)Param.get("type");
    String value = (String)Param.get("Value");

    SnmpAPI api;
    api = new SnmpAPI();
    api.start();        // Start SNMP API
    SnmpSession session = new SnmpSession(api); // Open session
    session.setPeername(remoteHost);// set remote Host
    session.setRemotePort(4700);// set remote Port

    //SetValues setVal = new SetValues( session, values );
    try
    {
      session.open();
    }
    catch (SnmpException e )
    {
      System.err.println("Error opening socket: "+e);
    }   //open session
    SnmpPDU pdu = new SnmpPDU();
    pdu.setCommand( api.SET_REQ_MSG );// Build set request PDU

    SnmpOID oid = new SnmpOID(OID);// add OID

    byte dataType;// get the type 只接受string
    if (type.equalsIgnoreCase("String")) {
      dataType = SnmpAPI.STRING;
      }
    else {
    System.err.println("Invalid variable type: " + type);
    return;
    }
    // create SnmpVar instance for the value and the type
    SnmpVar var = null;
    try {
     var = SnmpVar.createVariable( value, dataType );
        }
    catch(SnmpException e){
    System.err.println("Cannot create variable: " + oid + " with value: " + value);
    return;
    }
    SnmpVarBind varbind = new SnmpVarBind(oid, var);//create varbind
    pdu.addVariableBinding(varbind); // add variable binding
    // Send PDU
     try {
     pdu = session.syncSend(pdu);
	} catch (SnmpException e) {
      System.err.println("Sending PDU"+e.getMessage());
	}
	// print the response pdu varbinds
    if (pdu == null)
    {
      System.out.println("Request timed out to");
      return;
    }
    System.out.println("Response PDU received from " +pdu.getAddress()+ ", community: " + pdu.getCommunity());
    System.out.println(pdu.printVarBinds());

    if (pdu.getErrstat() != 0)
           System.err.println(pdu.getError());
    else
           // print the response pdu varbinds
           System.out.println(pdu.printVarBinds());



    session.close();// close session
    api.close();// stop api thread
  }
  public Hashtable GetResponse(String CmdCode,Hashtable param)
  {
  Hashtable OidValue = new Hashtable();
  //如果CmdCode == "custom";则需要从param中获取参数 Ip 和 Oid
  //如果CmdCode != "custom",则需要从param中获取Ip,而Oid则需要通过配置进行设置
  /*param
  Ip: (String)
  Oid (Vector)
  */
  String Ip = "";
  Vector Oid = new Vector(); //存储参数中传递的Oid
  Hashtable OidConfig = new Hashtable(); //存储snmp配置
  Hashtable CmdConfig = new Hashtable(); //存储CommamdInterface配置
  String Action = ""; //获取需要进行的操作

  ParseConfig parseConfig = new ParseConfig();

  Ip = (String)param.get("Ip");  //Ip的值在param中的位置为0
  if(CmdCode.equals("custom")) //如果不是执行配置的命令
  {
  Oid = (Vector)param.get("Oid");
  Vector CustomValue = GetValueByCustom(Ip,Oid); //根据参数传递Oid输入获得对应节点的值

  OidValue.put("Ip",Ip);
  OidValue.put("Oid",Oid); //Vector
  OidValue.put("Value",CustomValue); //Vector
  }
  else //如果是执行配置的命令
  {
  OidConfig = parseConfig.GetOidConfig(); //获得节点的Oid配置
  CmdConfig = parseConfig.GetCommamdConfig(CmdCode); //获得对应命令接口的配置
  Action = (String)CmdConfig.get("Action");
  if(Action.equals("get"))
  OidValue = GetValueByConfig(Ip,OidConfig,CmdConfig); //根据配置获得对应节点的值(Hashtable)
  if(Action.equals("set"))
  {
  Vector Value = (Vector)param.get("Value");
  SetValueByConfig(Ip,OidConfig,CmdConfig,Value);
  }
  }
  return OidValue;
  }
  ///////////////////SetValueByConfig//////////////////////////
  public void SetValueByConfig(String Ip,Hashtable OidConfig,Hashtable CmdConfig,Vector Data)
  {
  Vector ObjectName = (Vector)CmdConfig.get("ObjectName");
  Hashtable OidTable = (Hashtable)OidConfig.get("oidTable");
  for(int i = 0;i < ObjectName.size(); i++)
  {
  String Value = (String)Data.elementAt(i);
  String ItemName = (String)ObjectName.elementAt(i);
  String Oid = (String)OidTable.get(ItemName);
  Hashtable SetParam = new Hashtable();
  SetParam.put("remoteHost",Ip);
  SetParam.put("OID",Oid);
  SetParam.put("type","string");
  SetParam.put("value",Value);

  SetValue(SetParam);
  }//for
  }//////////////////////SetValueByConfig/////////////////////////////////
  ///////////////////////GetValueByConfig//////////////////////////
  public Hashtable GetValueByConfig(String Ip,Hashtable OidConfig,Hashtable CmdConfig)
  {
  Hashtable OidValue = new Hashtable(); //需要返回的节点值列表

  Vector ObjectName = (Vector)CmdConfig.get("ObjectName");
  Vector returnName = (Vector)CmdConfig.get("returnName");

  Hashtable TypeTable = (Hashtable)OidConfig.get("type");
  Hashtable OidTable = (Hashtable)OidConfig.get("oidTable");

  Vector TableItem = new Vector(); //存储需要操纵的表的子项
  Vector NodeItem = new Vector();//存储需要操纵的非表节点的项

  String ItemName = ""; //当前对象名称
  Vector NodeOidVector = new Vector();

  for(int i = 0; i < ObjectName.size(); i++)
  {
  ItemName = (String)ObjectName.elementAt(i);
  String Type = (String)TypeTable.get(ItemName);
  if(Type.equals("table"))
  {
  Hashtable tableOid = (Hashtable)OidTable.get(ItemName);
  TableItem.add(ItemName);  //存储表节点名称
  Hashtable tableValue = SnmpGetTableValue(Ip,returnName,tableOid);
  OidValue.put(ItemName,tableValue); //////////存储表节点的所有数据//////////
  }////////////////if
  else
  {
  String NodeOid = (String)OidTable.get(ItemName);
  NodeItem.add(ItemName);  //存储非表节点名称
  NodeOidVector.add(NodeOid);//存储非表节点的Oid
  }///////////////else
  }//for
  if(NodeOidVector.size() > 0) //如果配置中含有非表节点数据
  {//获取所有的非表节点的对应Oid的值
  Vector NodeValue = GetValueByCustom(Ip,NodeOidVector);
  OidValue.put("NodeValue",NodeValue); //Vector ////非表节点数据集合
  }
  OidValue.put("NodeName",NodeItem); //Vector //////非表节点名称集合
  OidValue.put("TableName",TableItem);//Vector ////表节点的名称集合
  return OidValue;
  }////////////////////GetValueByConfig///////////////////////////////
  /*TableItem 存储表中需要输出的项
    tableOid
  TableConfig.put("name",NameVector); //Vector 包含该表中所有列名称描述
  TableConfig.put("Oid",OidTable); //Hashtable  //每一列对应的起始Oid节点值
  */
//////////////////////SnmpGetTableValue/////////////////////////////////////////////
  public Hashtable SnmpGetTableValue(String Ip,Vector TableItem,Hashtable tableOid)
  {
  Hashtable OidTable = (Hashtable)tableOid.get("Oid");//获得配置中每一列对应的Oid节点
  Hashtable OutPutItemOid = new Hashtable(); //存储输出项对应当前表的Oid
  Vector OutPutItemName = new Vector(); //存储输出相对应当前表中的列名称

  boolean GetOid = false;
  boolean IsTableEnd = false;//判断是否到了表末尾
  Vector NameVector = new Vector(); //存储表中每一项的名称(name....)
  Vector StatusVector = new Vector();//存储表中每一项对应的状态,顺序和NameVector对应
  Vector OidVector = new Vector();//存储表中每一项的status对应的Oid值(name StatueOid)
  for(int i = 0;i < TableItem.size(); i++)
  {
  String Item = (String)TableItem.elementAt(i);
  if(Item.equals("Oid")) GetOid = true;  //是否需要返回oid列表
  if(OidTable.get(Item) != null)
  {
  String Oid = (String)OidTable.get(Item);
  OutPutItemOid.put(Item,Oid);
  OutPutItemName.add(Item);
  }//if
  }//for
  Hashtable TableValue = new Hashtable();
  String remoteHost = Ip;
  //String OID = args[1];
  // Start SNMP API
  SnmpAPI api;
  api = new SnmpAPI();
  api.start();
  api.setDebug( true );
  // Open session
  SnmpSession session = new SnmpSession(api);
  try {
  session.open();
  } catch (SnmpException e ) {
  System.err.println("打开Socket出错 "+e);
  }
  // set remote Host
  session.setPeername(remoteHost);
  // Build Get request PDU
  SnmpPDU pdu = new SnmpPDU();
  pdu.setCommand( api.GETNEXT_REQ_MSG);//GETNEXT
  for(int i = 0;i < OutPutItemName.size(); i++)
  {
  String ItemName = (String)OutPutItemName.elementAt(i); //获得输出项对应的列名称
  String OidStr = (String)OutPutItemOid.get(ItemName); //获得输出项对应的Oid
  SnmpOID oid = new SnmpOID(OidStr);
  if(oid.toValue() == null) System.err.println("错误的Oid对象 " + OidStr);
  else pdu.addNull(oid);
  }
  try {
   // Send PDU and receive response PDU
   pdu = session.syncSend(pdu);
   } catch (SnmpException e) {
   System.err.println("Error sending SNMP request: "+e);
   }
  if (pdu == null)System.out.println("Oid请求超时 ");// 超时
   // print the response pdu varbinds
  // 检察PDU的错误
  if (pdu.getErrstat() != 0)
  System.err.println(pdu.getError());
  else
  // print the response pdu varbinds
  System.out.println(pdu.printVarBinds());
/////////////////////获得表第一行的Oid和值/////////////////////////////////////////////
  /*
IsTableEnd = false;//判断是否到了表末尾
NameVector 存储表中每一项的名称(name....)
StatusVector 存储表中每一项对应的状态
OidMap 存储表中每一项的status对应的Oid值(name StatueOid)
OutPutItemName (Vector) ,顺序对应resive对象 Name Status
*/
  Vector resive = pdu.getVariableBindings();
  String CurrentName = "",CurrentStatus = "";
  while(!IsTableEnd)
  {
  SnmpPDU rowPdu = new SnmpPDU();
  rowPdu.setCommand( api.GETNEXT_REQ_MSG);//GETNEXT
  for(int i = 0; i < resive.size(); i++)
  {
  SnmpVarBind snmpVar = (SnmpVarBind)resive.elementAt(i);
  SnmpOID objectID = snmpVar.getObjectID(); //获得返回的Oid
  ////////////判断是否到表格最后一条纪录/////////////////////////
  String ComparOidStr = objectID.toString(); //用来比较
  String FieldName = (String)OutPutItemName.elementAt(i);
  String RowRootOid = (String)OutPutItemOid.get(FieldName);
  ComparOidStr = ComparOidStr.substring(0,RowRootOid.length());
  if(!ComparOidStr.equals(RowRootOid))
  {IsTableEnd = true;break;}
  //////////////存储数据值//////////////////////////////////////
  SnmpVar var = snmpVar.getVariable();
  if(FieldName.equals("Name")) //如果当前列是 name列
  NameVector.add(var.toString());
  if(FieldName.equals("Status")) //如果当前列是 status列
  {
  StatusVector.add(var.toString()); //存储status值
  OidVector.add(objectID.toString()); //存储当前Status对应的Oid
  }
  ////////////////////////////////////////////////
  rowPdu.addNull(objectID); //获取当前返回Oid节点的下一个Oid节点值
  }
  if(IsTableEnd == true) break; //是否到了表末尾
  ///////////////进行下一次getnext/////////////////////////////////
  try {
   // Send PDU and receive response PDU
   rowPdu = session.syncSend(rowPdu);
   } catch (SnmpException e) {
   System.err.println("Error sending SNMP request: "+e);
   }
  if (rowPdu == null)System.out.println("Oid请求超时 ");// 超时
  // 检察PDU的错误
  if (rowPdu.getErrstat() != 0)
  System.err.println(rowPdu.getError());
  else
  System.out.println(rowPdu.printVarBinds());
  resive = rowPdu.getVariableBindings(); //获得新的返回值
  }///while
   // close session
   session.close();
   // stop api thread
   api.close();

//NameVector 存储表中每一项的名称(name....)
//StatusVector 存储表中每一项对应的状态
for(int i = 0 ; i < OutPutItemName.size(); i++)
{
String StrCurrentOutput = (String)OutPutItemName.elementAt(i);
if(StrCurrentOutput.equals("Name"))
TableValue.put("Name",NameVector);
if(StrCurrentOutput.equals("Status"))
TableValue.put("Status",StatusVector);
if(GetOid)
TableValue.put("Oid",OidVector);
}
TableValue.put("TableItem",TableItem);
  return TableValue;
  }
//////////////////////////////////////////////////////////////////////////////////
 public Vector GetValueByCustom(String Ip,Vector OidVector) //根据确切的Oid获得值
  {
  Vector NodeValue = new Vector();
   SnmpAPI api;
   api = new SnmpAPI();
   api.start();
   api.setDebug( true );
   /* start 方法启动一个API线程来监控会话接受和发送PDU,该线程可以通过close方法来停止 */
    // 打开一个请求会话
    SnmpSession session = new SnmpSession(api);
    // set remote Host ,设置远程主机
    session.setPeername("localhost");
    session.setRemotePort(4700);
   //创建SnmpPDU实例,发送GET请求到PeerHost
   SnmpPDU pdu = new SnmpPDU();
   pdu.setCommand( api.GET_REQ_MSG ); //设置snmp命令//GETNEXT_REQ_MSG
   // add OIDs
   for(int i = 0 ; i < OidVector.size(); i++)
   {
   String StrOid = (String)OidVector.elementAt(i);
   SnmpOID oid = new SnmpOID(StrOid);
   if (oid.toValue() == null)
    System.err.println("Invalid OID argument: " + StrOid);
    else pdu.addNull(oid);
   }
  try {
  //Open session
  session.open();
  } catch (SnmpException e) {
  System.err.println("Error opening session:"+e.getMessage());
  return NodeValue;
     }
      try {
      // 发送PDU接受返回的PDU
       pdu = session.syncSend(pdu);
      } catch (SnmpException e) {
      System.err.println("Sending PDU"+e.getMessage());
      return NodeValue;
        }
       if (pdu == null) {
       // 超时
       System.out.println("请求超时");
       return NodeValue;
        }
        // print and exit
        System.out.println("Response PDU received from " +pdu.getAddress()+
                   ", community: " + pdu.getCommunity());
        // 检察PDU的错误
        if (pdu.getErrstat() != 0)
            System.err.println(pdu.getError());
        else
            // print the response pdu varbinds
            System.out.println(pdu.printVarBinds());
      Vector resive = pdu.getVariableBindings();
      for(int i = 0; i < resive.size(); i++ )
      {
      SnmpVarBind snmpVar = (SnmpVarBind)resive.elementAt(i);
      //SnmpOID objectID = snmpVar.getObjectID();
      SnmpVar var = snmpVar.getVariable();
      NodeValue.add(i,var.toString());
      }
        // close session
        session.close();
        // stop api thread
        api.close();
        return NodeValue;
  }///////////////////////////////////snmpGet//////////////

  public static void main(String[] args) {
   SnmpCommand snmpCmd = new SnmpCommand();
   String Ip = "127.0.0.1";

   snmpCmd.ResiveTrap();
/**/
   Vector Oid = new Vector();
   Oid.add(0,".1.3.6.1.4.1.188.1.1.0");
   snmpCmd.GetValueByCustom(Ip,Oid);

   Hashtable param = new Hashtable();
   param.put("remoteHost",Ip);
   param.put("OID",".1.3.6.1.4.1.188.2.1.10.0"); //set
   param.put("Value","1");//IsConnect
   param.put("type","String");

   snmpCmd.SetValue(param);



   /*
   String CmdCode = "003";


   Vector Value = new Vector();
   Value.add("responseAction");



   //snmpCommand1.snmpGet(Ip,Oid);
   //snmpCommand1.GetResponse(CmdCode,param);
   //snmpCommand1.ResiveTrap();
   //snmpCommand1.SetValue(Param);
        */
  }
}