package com.regaltec.nma.collector.common.snmp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import uk.co.westhawk.snmp.pdu.BlockPdu;
import uk.co.westhawk.snmp.stack.AsnInteger;
import uk.co.westhawk.snmp.stack.AsnNull;
import uk.co.westhawk.snmp.stack.AsnObject;
import uk.co.westhawk.snmp.stack.AsnObjectId;
import uk.co.westhawk.snmp.stack.AsnOctets;
import uk.co.westhawk.snmp.stack.AsnUnsInteger;
import uk.co.westhawk.snmp.stack.AsnUnsInteger64;
import uk.co.westhawk.snmp.stack.PduException;
import uk.co.westhawk.snmp.stack.SnmpConstants;
import uk.co.westhawk.snmp.stack.SnmpContext;
import uk.co.westhawk.snmp.stack.SnmpContextBasisFace;
import uk.co.westhawk.snmp.stack.SnmpContextv 2c ;
import uk.co.westhawk.snmp.stack.SnmpContextv3;
import uk.co.westhawk.snmp.stack.SnmpContextv3Pool;
import uk.co.westhawk.snmp.stack.varbind;
import com.regaltec.nma.collector.common.NmaLog4jProxy;
/**
* <p>
* Title: SNMP协议驱动,版本包括SNMP v1,v 2c ,v3
* </p>
* 提供上层(SO层)访问SNMP代理时用 用到的外部包:snmp4_13.jar
*
* <p>
* Description:
* </p>
*
* <p>
* Copyright: Copyright (c) 2005
* </p>
*
* <p>
* Company:
* </p>
*
* @version 1.0
*/
public class NmaCollectorSnmp {
// 自定义SNMP数据类型变量
public final static int DTYPE_AsnInteger = 0; // AsnInteger类型
public final static int DTYPE_AsnNull = 10; // AsnNull类型
public final static int DTYPE_AsnObjectId = 20; // AsnObjectId类型
public final static int DTYPE_AsnOctets = 30; // AsnOctets类型
public final static int DTYPE_AsnPrimitive = 40; // AsnPrimitive类型
public final static int DTYPE_AsnUnsInteger = 50; // AsnUnsInteger类型
public final static int DTYPE_AsnTIMETICKS = 51; // SnmpConstants.TIMETICKS类型
public final static int DTYPE_AsnCOUNTER = 52; // SnmpConstants.COUNTER类型
public final static int DTYPE_AsnGAUGE = 53; // SnmpConstants.GAUGE类型
public final static int DTYPE_AsnUnsInteger64 = 60; // AsnUnsInteger64类型
// 内部变量
/*
* private SnmpContextPool contextv1 = null; private SnmpContextv2cPool
* contextv 2c = null; private SnmpContextv3Pool contextv3 = null;
*/
private SnmpContext contextv1 = null;
private SnmpContextv 2c contextv 2c = null;
private SnmpContextv3 contextv3 = null;
private String host = "127.0.0.1"; // SNMP主机IP地址
private int port = SnmpContextBasisFace.DEFAULT_PORT; // SNMP端口号,缺省为161
private String comm = "public"; // community 串
boolean openFlag = false;
int snmpVersion = 1; // SNMP 版本号 1-SNMPv1, 2-SNMPv 2c , 3-SNMPv3
// SNMP v3 专用参数
byte[] contextEngineId = null;
String contextName = "";
String userName = "";
boolean useAuthentication = false;
String userAuthPassw = "";
int protocol = SnmpContextv3Pool.MD5_PROTOCOL;
boolean usePrivacy = false;
String userPrivacyPassword = "";
// private org.apache.log4j.Logger log =
// org.apache.log4j.Logger.getLogger("RtsSnmpDO");
private org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass().getName());
/**
* 默认构造函数
*/
public NmaCollectorSnmp() {
}
/**
* 构造函数,适用于SNMP v1,v2
*
* @param host
* String 若host为null,则使用"127.0.0.1"
* @param port
* int 若port为0,则使用SnmpContextBasisFace.DEFAULT_PORT
* @param comm
* String 若comm为null,则使用public
*/
public NmaCollectorSnmp(int snmpVersion, String host, int port, String comm) {
if (host != null)
this.host = host;
if (port != 0)
this.port = port;
if (comm != null)
this.comm = comm;
// SNMP 版本
this.snmpVersion = snmpVersion;
}
/**
* 构造函数,适用于SNMP v3
* @param host
* String
* @param port
* int
* @param contextEngineId
* byte[]
* @param contextName
* String
* @param userName
* String
* @param useAuthentication
* boolean
* @param protocol
* int
* @param usePrivacy
* boolean
* @param userPrivacyPassword
* String
*/
public NmaCollectorSnmp(String host, int port, byte[] contextEngineId, String contextName, String userName, boolean useAuthentication, int protocol, boolean usePrivacy, String userPrivacyPassword) { //九个形参
if (host != null)
this.host = host;
if (port != 0)
this.port = port;
this.contextEngineId = contextEngineId;
this.contextName = contextName;
this.userName = userName;
this.useAuthentication = useAuthentication;
this.protocol = protocol;
this.usePrivacy = usePrivacy;
this.userPrivacyPassword = userPrivacyPassword;
// SNMP 版本v3
this.snmpVersion = 3;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getComm() {
return comm;
}
public byte[] getContextEngineId() {
return contextEngineId;
}
public String getContextName() {
return contextName;
}
public int getSnmpVersion() {
return snmpVersion;
}
public boolean isUseAuthentication() {
return useAuthentication;
}
public boolean isUsePrivacy() {
return usePrivacy;
}
public String getUserAuthPassw() {
return userAuthPassw;
}
public String getUserName() {
return userName;
}
public String getUserPrivacyPassword() {
return userPrivacyPassword;
}
/**
* 判断是否成功创建SNMP context
*
* @return boolean 返回结果: true-是,false-否
*/
public boolean isOpen() {
return openFlag;
}
private AsnObject newAsnObject(String val, int type) {
switch (type) {
case DTYPE_AsnNull:
return new AsnNull();
case DTYPE_AsnObjectId:
return new AsnObjectId(val);
case DTYPE_AsnOctets:
return new AsnOctets(val);
case DTYPE_AsnPrimitive:
return null; // return new AsnPrimitive(val.getBytes());
case DTYPE_AsnUnsInteger:
return new AsnUnsInteger(Integer.parseInt(val));
case DTYPE_AsnTIMETICKS:
return new AsnUnsInteger(Long.parseLong(val), SnmpConstants.TIMETICKS);
case DTYPE_AsnCOUNTER:
return new AsnUnsInteger(Long.parseLong(val), SnmpConstants.COUNTER);
case DTYPE_AsnGAUGE:
return new AsnUnsInteger(Long.parseLong(val), SnmpConstants.GAUGE);
case DTYPE_AsnUnsInteger64:
return new AsnUnsInteger64(Integer.parseInt(val));
case DTYPE_AsnInteger:
default:
return new AsnInteger(Integer.parseInt(val));
}
}
/**
* 建立SNMP Context,成功之后可以使用该Context进行通讯
*
* @return boolean 返回结果,true-成功,false-失败
*/
public boolean open() {
boolean ret = false;
try {
openFlag = true;
if (snmpVersion == 1) // SNMP v1
{
if (contextv1 != null) {
contextv1.destroy();
}
// contextv1 = new SnmpContextPool(host, port,
// "STANDARD_SOCKET");
contextv1 = new SnmpContext(host, port);
contextv1.setCommunity(comm);
} else if (snmpVersion == 2) // SNMP v2c
{
if (contextv2c != null) {
contextv2c.destroy();
}
// contextv2c = new SnmpContextv2cPool(host, port,
// "STANDARD_SOCKET");
contextv2c = new SnmpContextv2c(host, port);
contextv2c.setCommunity(comm);
}
/* else
{ // SNMP v3
if (contextv3 != null)
{
contextv3.destroy();
}
// contextv3 = new SnmpContextv3Pool(host, port,
// "STANDARD_SOCKET");
contextv3 = new SnmpContextv3(host, port);
contextv3.setContextEngineId(contextEngineId);
contextv3.setContextName(contextName);
contextv3.setUserName(userName);
contextv3.setUseAuthentication(useAuthentication);
contextv3.setUserAuthenticationPassword(userAuthPassw);
contextv3.setAuthenticationProtocol(protocol);
contextv3.setUsePrivacy(usePrivacy);
contextv3.setUserPrivacyPassword(userPrivacyPassword);
}*/
else if (snmpVersion == 3)// SNMP v3
{
if (contextv3 != null) {
contextv3.destroy();
}
// contextv3 = new SnmpContextv3Pool(host, port,
// "STANDARD_SOCKET");
contextv3 = new SnmpContextv3(host, port);
contextv3.setContextEngineId(contextEngineId);
contextv3.setContextName(contextName);
contextv3.setUserName(userName);
contextv3.setUseAuthentication(useAuthentication);
contextv3.setUserAuthenticationPassword(userAuthPassw);
contextv3.setAuthenticationProtocol(protocol);
contextv3.setUsePrivacy(usePrivacy);
contextv3.setUserPrivacyPassword(userPrivacyPassword);
}
//新增加的处理代码。当snmp为除1、2、3以外,就直接返回false
else {
// ret=false;
return ret;
}
//*/
ret = true;
} catch (java.io.IOException exc) {
// log.debug(exc.toString());
} catch (Exception ex) {
// log.debug(ex.toString());
}
return ret;
}
/**
* 关闭SNMP Context
*/
public void close() {
if (contextv1 != null) {
contextv1.destroy();
contextv1 = null;
}
if (contextv2c != null) {
contextv2c.destroy();
contextv2c = null;
}
if (contextv3 != null) {
contextv3.destroy();
contextv3 = null;
}
openFlag = false;
}
/**
* 根据SNMP版本产生PDU实例
* @return BlockPdu
*/
BlockPdu getPdu() {
BlockPdu pdu = null;
if (snmpVersion == 1)
pdu = new BlockPdu(contextv1);
else if (snmpVersion == 2)
pdu = new BlockPdu(contextv2c);
else
pdu = new BlockPdu(contextv3);
return pdu;
}
/**
* 发送PDU并等待返回结果
* @param pdu
* BlockPdu
* @return String
*/
private String sendRequest(BlockPdu pdu) {
String ret = "";
try {
varbind var = pdu.getResponseVariableBinding();
AsnObjectId newoid = var.getOid();
AsnObject res = var.getValue();
if (res != null) {
ret = res.toString();
//log.debug("recvoid=" + newoid.toString() + ",res=" + res.toString() + ",type=" + res.getRespTypeString() + ",type=" + res.getRespType());
// System.out.println("recvoid=" + newoid.toString() + ",res=" + res.toString() + ",type=" + res.getRespTypeString() + ",type=" + res.getRespType());
} else {
// log.debug("Received no answer!");
// System.out.println("Received no answer!");
}
} catch (PduException exc) { // exc.printStackTrace();
} catch (java.io.IOException exc) { // log.debug(exc.toString());
// exc.printStackTrace();
} catch (Exception ex) {// log.debug(ex.toString()); // ex.printStackTrace();
}
return ret;
}
/**
* 发送单个GET请求,并接收结果
*
* @param oid
* String 要GET的OID字符串
* @return String 返回结果串,若取不到,则为空串("")
*/
public String doSingleGetRequest(String oid) {
BlockPdu pdu = getPdu();
// 设置重试间隔及次数
pdu.setRetryIntervals(new int[] { 500, 1000, 2000 });
pdu.setPduType(BlockPdu.GET);
pdu.addOid(oid);
return sendRequest(pdu);
}
/**
* 以OID的值为基础取下一个oid的值,
*
* @param oidMap
* 输入参数,oidMap中的key为K_OID
* @return 下一个oid级对应的值
*/
public String[] doSingleGetNextRequest(String oid) {
BlockPdu pdu = getPdu();
// 设置重试间隔及次数
pdu.setRetryIntervals(new int[] { 500, 1000, 2000 });
pdu.setPduType(BlockPdu.GETNEXT);
pdu.addOid(oid);
// log.debug("doSingleGetNextRequest OID=" + oid);
String[] strResult = sendNextRequest(pdu);
return strResult;
}
/**
* 发送PDU并等待返回结果
*
* @param pdu
* BlockPdu
* @return String
*/
private String[] sendNextRequest(BlockPdu pdu) {
String[] ret = new String[2];
try {
varbind var = pdu.getResponseVariableBinding();
AsnObjectId newoid = var.getOid();
ret[0] = newoid.getValue();
AsnObject res = var.getValue();
if (res != null) {
ret[1] = res.toString();
// log.debug("recvoid=" + newoid.toString() + ",res=" + ret[1] + ",type=" + res.getRespTypeString() + ",type=" + res.getRespType());
} else {
// log.debug("Received no answer!");
// log.warn("Received no answer!");
}
} catch (PduException exc) {
// log.debug(exc.toString());
// exc.printStackTrace();
} catch (java.io.IOException exc) {
// log.debug(exc.toString());
// exc.printStackTrace();
} catch (Exception ex) {
// log.debug("sendRequest Exception:" + ex.toString());
// ex.printStackTrace();
}
return ret;
}
/**
* 发送多个GET请求,并接收结果
*
* @param oidArray
* String[] 要GET的OID字符串数组
* @return java.util.Map 取回的结果,是所有字段的"Key/值"对,其中Key为OID,值为该OID对应的值
*/
public java.util.Map doMultiGetRequest(String[] oidArray) {
java.util.Hashtable retMap = null;
BlockPdu pdu = getPdu();
// 设置重试间隔及次数
pdu.setRetryIntervals(new int[] { 500, 1000, 2000 });
if (oidArray.length < 1) {
return null;
}
for (int i = 0; i < oidArray.length; i++) {
pdu.setPduType(BlockPdu.GET);
// System.out.println("Multi Oid = " + oidArray[i]);
pdu.addOid(oidArray[i]);
}
try {
varbind[] var = pdu.getResponseVariableBindings();
if (var != null) {
int sz = var.length;
// System.out.println("Received answer " + sz);
if (sz > 0) {
retMap = new java.util.Hashtable();
}
for (int i = 0; i < sz; i++) {
AsnObjectId oid = var[i].getOid();
AsnObject res = var[i].getValue();
retMap.put(oid.toString(), res.toString());
/*
* System.out.println("i=" + i + "," + oid.toString() + ": " +
* res.toString());
*/
}
} else {
// log.debug("Received no answer");
// System.out.println("Received no answer");
}
} catch (PduException exc) {
// log.debug(exc.getMessage());
} catch (java.io.IOException exc) {
// log.debug(exc.getMessage());
} catch (Exception ex) {
// log.debug(ex.getMessage());
}
return retMap;
}
/**
* 发送<单个>SET请求,并接收返回结果
*
* @param oid
* String 要SET的OID字符串
* @param value
* String 要设置的值(字符串型)
* @param type
* int 要设置的值类型,如DTYPE_AsnInteger,DTYPE_AsnOctets,...
* @return String 返回结果串,若取不到,则为空串("")
*/
public String doSingleSetRequest(String oid, String val, int type) {
BlockPdu pdu = getPdu();
// 设置重试间隔及次数
pdu.setRetryIntervals(new int[] { 500, 1000, 2000 });
pdu.setPduType(BlockPdu.SET);
pdu.addOid(oid, newAsnObject(val, type));
return sendRequest(pdu);
}
/**
* 发送<多个>SET请求,并接收返回结果
*
*/
public void doMultiSetRequest(String[] oid, String[] val, int[] type) {
java.util.Hashtable retMap = null;
BlockPdu pdu = getPdu();
// 设置重试间隔及次数
pdu.setRetryIntervals(new int[] { 500, 1000, 2000 });
for (int i = 0; i < val.length; i++) {
pdu.setPduType(BlockPdu.SET);
pdu.addOid(oid[i], newAsnObject(val[i], type[i]));
}
try {
varbind[] var = pdu.getResponseVariableBindings();
if (var != null) {
int sz = var.length;
// System.out.println("Received answer " + sz);
if (sz > 0) {
retMap = new java.util.Hashtable();
}
for (int i = 0; i < sz; i++) {
AsnObjectId Repoid = var[i].getOid();
AsnObject res = var[i].getValue();
retMap.put(Repoid.toString(), res.toString());
// System.out.println("i=" + i + "," + oid.toString() + ": "
// +
// res.toString());
}
} else {
// log.debug("Received no answer");
System.out.println("Received no answer");
}
} catch (PduException exc) {
// log.debug("RtsSmnpDO.sendRequest: Catch PduException!");
// exc.printStackTrace();
} catch (java.io.IOException exc) {
// log.debug("RtsSmnpDO.sendRequest: Catch IOException!");
// exc.printStackTrace();
} catch (Exception ex) {
// log.debug("RtsSmnpDO.sendRequest: Catch Exception!");
// ex.printStackTrace();
}
}
/**
* 从表中取出一条记录<BR>
* 每个字段OID的取法:<BR>
* OID=<tableEntryOid>.<fieldIndex>.<keyArray[0]>.<keyArray[1]>.<keyArray[2]>...
* <BR>
* 其中:fieldIndex为字段序号,即第几个字段
*
* @param tableEntryOid
* String 表入口OID
* @param fieldIndex
* int[] 要取出的字段序号(int型数组)
* @param keyArray
* int[] 表的索引关键字(int型数组)
* @return String[][] 取回的记录,包括各字段值(二维字符串型数组,第一维为OID,第二维为值)
*/
/*
* public String[][] getRecordFromTable(String tableEntryOid, int[]
* fieldIndex, int[] keyArray) { StringBuffer keyBuffer = new
* StringBuffer(); String[] oidArray = new String[fieldIndex.length]; int i;
* // 先将所有Key串起来,中间用"."分开 for (i= 0; i<keyArray.length; i++) { if (i == 0)
* keyBuffer.append(keyArray[i]); else keyBuffer.append("." + keyArray[i]); }
* // 制作oidArray for (i = 0; i < fieldIndex.length; i++) { oidArray[i] =
* tableEntryOid + "." + fieldIndex[i] + "." + keyBuffer; }
* // 发送请求,并返回结果 return doMultiGetRequest(oidArray); }
*/
/**
* 从表中取出一条记录<BR>
* 每个字段OID的取法:<BR>
* OID=<tableEntryOid>.<fieldIndex>.<keyArray[0]>.<keyArray[1]>.<keyArray[2]>...
* <BR>
* 其中:fieldIndex为字段序号,即第几个字段
*
* @param tableEntryOid
* String 表入口OID
* @param fieldIndex
* int[] 要取出的字段序号(int型数组)
* @param keyArray
* int[] 表的索引关键字(int型数组)
* @return java.util.Map 取回的记录,是所有字段的"Key/值"对,其中Key为OID,值为该OID对应的值
*/
public java.util.Map getRecordFromTable(String tableEntryOid, int[] fieldIndex, int[] keyArray) {
StringBuffer keyBuffer = new StringBuffer();
String[] oidArray = new String[fieldIndex.length];
int i;
// 先将所有Key串起来,中间用"."分开
for (i = 0; i < keyArray.length; i++) {
if (i == 0)
keyBuffer.append(keyArray[i]);
else
keyBuffer.append("." + keyArray[i]);
}
// 制作oidArray
for (i = 0; i < fieldIndex.length; i++) {
oidArray[i] = tableEntryOid + "." + fieldIndex[i] + "." + keyBuffer;
}
// 发送请求,并返回结果
return doMultiGetRequest(oidArray);
}
public String[][] getBulk(String entryOid) {
String[] arry = doSingleGetNextRequest(entryOid);
if (arry == null || arry.length <= 0) {
return null;
}
String inOid = entryOid;
HashMap tmpMap = new HashMap();
int index = 0;
while (true) {
if (arry[0] == null || !arry[0].startsWith(entryOid)) {
break;
}
tmpMap.put(new Integer(index), arry);
index++;
inOid = arry[0];
arry = doSingleGetNextRequest(inOid);
}
String[][] outArry = new String[index][2];
for (index = 0; index < tmpMap.size(); index++) {
outArry[index] = (String[]) tmpMap.get(new Integer(index));
}
return outArry;
}
public String[][] getTable(String entryOID, int colMaxIndex) {
return getTable(entryOID, 0, colMaxIndex);
}
public String[][] getTable(String entryOid, int colMinIndex, int colMaxIndex) {
String[] arry = doSingleGetNextRequest(entryOid);
if (arry == null || arry.length <= 0 || colMaxIndex - colMinIndex <= 0) {
return null;
}
HashMap tmpMap = new HashMap();
int total = 0;
String inOid = entryOid;
while (true) {
if (arry[0] == null || arry[1] == null || !arry[0].startsWith(entryOid)) {
break;
}
int pos1 = arry[0].indexOf(".", entryOid.length());
if (pos1 <= 0) {
break;
}
int pos2 = arry[0].indexOf(".", pos1 + 1);
if (pos2 <= 0 || (pos2 - pos1) < 2) {
break;
}
String strCol = arry[0].substring(pos1 + 1, pos2);
int col = 0;
try {
col = Integer.parseInt(strCol);
} catch (Exception e) {
break;
}
pos1 = arry[0].indexOf(".", pos2);
if (pos1 <= 0) {
break;
}
String strIndex = "";
pos2 = arry[0].indexOf(".", pos1 + 1);
if (pos2 <= 0) {
pos2 = arry[0].length();
} else if ((pos2 - pos1) < 2) {
break;
}
strIndex = arry[0].substring(pos1 + 1, pos2);
if (arry[1] == null) {
arry[1] = "";
}
String[] row;
if (tmpMap.get(strIndex) == null || (!(tmpMap.get(strIndex) instanceof String[]))) {
row = new String[colMaxIndex - colMinIndex + 1];
row[0] = arry[0];
row[1] = arry[1];
tmpMap.put(strIndex, row);
total++;
}
if (col > colMaxIndex) {
break;
}
row = (String[]) tmpMap.get(strIndex);
row[col - colMinIndex] = arry[1];
;
inOid = arry[0];
arry = doSingleGetNextRequest(inOid);
}
String[][] outArry = new String[total][colMaxIndex - colMinIndex];
int index = 0;
Iterator it = tmpMap.keySet().iterator();
while (it.hasNext()) {
String keyName = (String) it.next();
outArry[index] = (String[]) tmpMap.get(keyName);
index++;
}
return outArry;
}
// public String[][] getTable(String entryOID, int colMinIndex, int colMaxIndex) {
// String newEntryOID = entryOID + ".";
// int len = colMaxIndex - colMinIndex + 1;
// String[][] arryMinIndex = getBulk(newEntryOID + colMinIndex);
// if (arryMinIndex == null) {
// return null;
// }
// String[][] arryOther = null;
// int total = arryMinIndex.length;
// String[][] outAry = new String[total][len + 1];
//
// for (int i = 0; i < total; i++) {
// outAry[i][0] = arryMinIndex[i][0];
// outAry[i][1] = arryMinIndex[i][1];
// }
// for (int j = 1; j < len; j++) {
// arryOther = getBulk(newEntryOID + (colMinIndex + j));
// if (arryOther == null) {
// for (int k = 0; k <= len; k++) {
// outAry[k][j + 1] = "";
// }
// continue;
// }
// int total2 = arryOther.length;
// int total3 = total2 > total ? total : total2;
// for (int k = 0; k < total3; k++) {
// outAry[k][j + 1] = arryOther[k][1];
// }
// }
// return outAry;
// }
/**
* 更新一条记录中的一个字段
*
* @param tableEntryOid
* String 表入口OID
* @param fieldIndex
* int 要更新的字段序号
* @param keyArray
* int[] 表的索引关键字(int型数组)
* @param val
* String 新的值
* @param type
* int 值的类型
* @return int 返回值:0-成功,-1-失败
*/
public int updateOneFieldFromTable(String tableEntryOid, int fieldIndex, int[] keyArray, String val, int type) {
StringBuffer keyBuffer = new StringBuffer();
String oid;
int i;
// 先将所有Key串起来,中间用"."分开
for (i = 0; i < keyArray.length; i++) {
if (i == 0)
keyBuffer.append(keyArray[i]);
else
keyBuffer.append("." + keyArray[i]);
}
// 制作oid
oid = tableEntryOid + "." + fieldIndex + "." + keyBuffer;
// 发送请求,并返回结果
doSingleSetRequest(oid, val, type);
// 再取回值
String newVal = doSingleGetRequest(oid);
// 若相等,则返回成功,否则,返回失败
if (val.compareTo(newVal) == 0) {
// log.debug("OID=" + oid + ",操作成功 successCode=0");
// System.out.println("OID=" + oid + ",操作成功 successCode=0");
return 0;
}
// log.debug("OID=" + oid + ",操作成功 errCode=-1");
// System.out.println("OID=" + oid + ",操作成功 errCode=-1");
return -1;
}
public static String toStringFormSnmpValue(String strValue) {
if (strValue == null || strValue.length() < 4 || !strValue.startsWith("0x")) {
return strValue;
}
int pos1 = 2;
int pos2 = 0;
int len = (strValue.length() - 2 + 1) / 3;
byte[] arrayByte = new byte[len];
for (int index = 0; index < len; index++) {
pos2 = strValue.indexOf(":", pos1);
if (pos2 < 0) {
if (pos1 != (strValue.length() - 2)) {
return strValue;
} else {
pos2 = pos1 + 2;
}
}
if (pos2 - pos1 > 2) {
return strValue;
}
arrayByte[index] = Integer.decode("0x" + strValue.substring(pos1, pos2)).byteValue();
pos1 = pos2 + 1;
}
// try {
// byte[] orgusernameByte = (strValue.getBytes("ISO8859_1"));
// return new String(orgusernameByte, "GB2312");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// return "";
// }
try {
return new String(arrayByte);
} catch (Exception e) {
return "";
}
}
public static String toDateStringFormSnmpValue(String strValue, String format) {
if (strValue == null || strValue.length() < 4 || !strValue.startsWith("0x")) {
return strValue;
}
if (format == null || format.equals("")) {
format = "yyyy-MM-dd HH:mm:ss";
}
int pos1 = 2;
int pos2 = 0;
int len = (strValue.length() - 2 + 1) / 3;
byte[] arrayByte = new byte[len];
StringBuffer buf = new StringBuffer();
for (int index = 0; index < len; index++) {
pos2 = strValue.indexOf(":", pos1);
if (pos2 < 0) {
if (pos1 != (strValue.length() - 2)) {
return strValue;
} else {
pos2 = pos1 + 2;
}
}
if (pos2 - pos1 > 2) {
return strValue;
}
buf.append(strValue.substring(pos1, pos2));
pos1 = pos2 + 1;
}
int year = Integer.parseInt(buf.substring(0, 4), 16);
int month = Integer.parseInt(buf.substring(4, 6), 16);
int d = Integer.parseInt(buf.substring(6, 8), 16);
int hrs = Integer.parseInt(buf.substring(8, 10), 16);
int min = Integer.parseInt(buf.substring(10, 12), 16);
int sec = Integer.parseInt(buf.substring(12, 14), 16);
Date date = null;
try {
date = new SimpleDateFormat("y-M-d H:m:s").parse("" + year + "-" + (month + 1) + "-" + d + " " + hrs + ":" + min + ":" + sec);
} catch (Exception e) {
}
try {
return new SimpleDateFormat(format).format(date);
} catch (Exception e) {
return strValue;
}
}
public static void main(String[] args) {
NmaLog4jProxy log = new NmaLog4jProxy("");
NmaCollectorSnmp snmp = new NmaCollectorSnmp(1, "199.3.8.99", 161, "public");
if (!snmp.open()) {
return;
}
// System.out.println("/r/n======================begin:/r/n");
// Hashtable rec1 = new Hashtable();
// String[][] tmp = snmp.getBulk("1.3.6.1.2.1.25.4.2.1");
// if (tmp == null) {
// return ;
// }
// for (int i = 1; i <= tmp.length; i++) {
for(int j = 0;j< tmp[i].length;j++){
System.out.print(tmp[i][j] + "/t||/t");
}
// System.out.println("/r/n============= "+ tmp[i][0] +"=========begin:/r/n");
// String[][] tmp2 = snmp.getBulk("1.3.6.1.2.1.25.4.2.1.1");
// if(tmp2 == null){
// for (int k = 0; k <= tmp2.length ; k++) {
// for(int j = 0;j< tmp2[k].length;j++){
// System.out.print(tmp2[k][j] + "/t||/t");
// }
// System.out.print("/r/n");
// }
// }
//
// System.out.println("/r/n==================kkkkkkk====end");
// System.out.print("/r/n");
// }
//
// System.out.println("/r/n======================end");
System.out.println("/r/n======================begin:/r/n");
Hashtable rec1 = new Hashtable();
String[][] tmp = snmp.getTable("1.3.6.1.2.1.25.2.3.1", 5);
snmp.close();
if (tmp == null) {
return;
}
for (int i = 0; i < tmp.length; i++) {
if (tmp[i] == null) {
continue;
}
for (int j = 0; j < tmp[i].length; j++) {
System.out.print(tmp[i][j] + "/t||/t");
}
System.out.print("/r/n");
// for (int j = 0; j < tmp[i].length; j++) {
// if(j == 5){
// System.out.print(toDateStringFormSnmpValue(tmp[i][j],null) + "/t||/t");
// }else{
// System.out.print(toStringFormSnmpValue(tmp[i][j]) + "/t||/t");
// }
// }
// System.out.print("/r/n");
}
System.out.println("/r/n======================end");
}
}
使用用列:
/**
* NmaCollectorSnmpDO<br>
* <功能>SNMP协议处理类, 其中oid可以加前面的"."也可以不加前面的".". <br>
* @version <br>
* @author * 2008-04-23 18:07:20<br>
*/
public class NmaCollectorSnmpDO extends NmaCollectorSnmp {
public NmaCollectorSnmpDO() {
super();
}
/**
* SNMP v1, v2构造函数
* @param snmpVersion
* @param host
* @param port
* @param comm
*/
public NmaCollectorSnmpDO(int snmpVersion, String host, int port, String comm) {
super(snmpVersion, host, port, comm);
}
/**
* SNMP v3构造函数
* @param host
* @param port
* @param contextEngineId
* @param contextName
* @param userName
* @param useAuthentication
* @param protocol
* @param usePrivacy
* @param userPrivacyPassword
*/
public NmaCollectorSnmpDO(String host, int port, byte[] contextEngineId, String contextName, String userName, boolean useAuthentication, int protocol, boolean usePrivacy, String userPrivacyPassword) { //九个形参
super(host, port, contextEngineId, contextName, userName, useAuthentication, protocol, usePrivacy, userPrivacyPassword);
}
/**
* 打开连接
* @return 成功则返回true, 否则返回false.
*/
public boolean openSession() {
return this.open();
}
/**
* 关闭连接
*/
public int closeSession() {
this.close();
return 0;
}
/**
* SNMP的get
* @param oid
* @return 该oid对应的值
*/
public String get(String oid) {
return this.doSingleGetRequest(oid);
}
/**
* 该oid的下一个oid对应的值
* @param oid
* @return 一维且长度为2的字符串数组, String[0]为oid, String[1]为该oid对应的值
*/
public String[] getNext(String oid) {
return this.doSingleGetNextRequest(oid);
}
/**
* 例如: 表有22列, colMaxIndex为5,则返回6列二维数组, 第一列为oid, 第二列为表的第一列值, 第六列为表的第5列值. <br>
* 如果还是不懂, 可以用一下试试, 再看结果.
* @param entryOID 表入口
* @param colMaxIndex 取表的列数, 这里是表索引的最大数, 即是从表的第一列取到表的colMaxIndex列.
* @return colMaxIndex+1列二维数组, 其中第一列为oid, 其他为对应的列值
*/
public String[][] getTable(String entryOID, int colMaxIndex) {
if (entryOID.startsWith(".")) {
entryOID=entryOID.substring(1);
}
return getTable(entryOID, 0, colMaxIndex);
}
public static void main(String[] args) {
NmaCollectorSnmp snmp = new NmaCollectorSnmp(1, "199.3.8.251", 161, "public");
if (!snmp.open()) {
return;
}
String tmpka = snmp.doSingleGetRequest(" 1.3.6 .1.2.1.1.3.0");
for (int i = 0; i < 1; i++) {
System.out.println("[" + tmpka.toString() + "]");
}
// System.out.println("/r/n======================begin:/r/n");
// Hashtable rec1 = new Hashtable();
// String[][] tmp = snmp.getBulk(" 1.3.6 .1.2.1.25.4.2.1");
// if (tmp == null) {
// return ;
// }
// for (int i = 1; i <= tmp.length; i++) {
for(int j = 0;j< tmp[i].length;j++){
System.out.print(tmp[i][j] + "/t||/t");
}
// System.out.println("/r/n============= "+ tmp[i][0] +"=========begin:/r/n");
// String[][] tmp2 = snmp.getBulk(" 1.3.6 .1.2.1.25.4.2.1.1");
// if(tmp2 == null){
// for (int k = 0; k <= tmp2.length ; k++) {
// for(int j = 0;j< tmp2[k].length;j++){
// System.out.print(tmp2[k][j] + "/t||/t");
// }
// System.out.print("/r/n");
// }
// }
//
// System.out.println("/r/n==================kkkkkkk====end");
// System.out.print("/r/n");
// }
//
// System.out.println("/r/n======================end");
System.out.println("/r/n======================begin:/r/n");
String[][] tmp = snmp.getTable(" 1.3.6 .1.2.1.2.2.1", 6);
snmp.close();
if (tmp == null) {
return;
}
for (int i = 0; i < tmp.length; i++) {
if (tmp[i] == null) {
continue;
}
for (int j = 0; j < tmp[i].length; j++) {
System.out.print(tmp[i][j] + "/t||/t");
}
System.out.print("/r/n");
// for (int j = 0; j < tmp[i].length; j++) {
// if(j == 5){
// System.out.print(toDateStringFormSnmpValue(tmp[i][j],null) + "/t||/t");
// }else{
// System.out.print(toStringFormSnmpValue(tmp[i][j]) + "/t||/t");
// }
// }
// System.out.print("/r/n");
}
System.out.println("/r/n======================end");
}
}
调用方法:
/**
* 连接SNMP
* snmpVer 版本
* ip 连接机器的ip
* snmpPort SNMP端口 默认161
* snmpComm SNMP共同体串 eg:public
*/
snmp = new NmaCollectorSnmpDO(snmpVer, ip, snmpPort, snmpComm);
/**
* 返回结果集
*/
protected Hashtable getSoftwareInfo() {
Hashtable result = new Hashtable();
String[][] szaryInsSoftware = snmp.getTable(" 1.3.6 .1.2.1.25.6.3.1", 5);
int iLen = szaryInsSoftware.length;
int iIndex = 1;
for (int i = 0; i < iLen; i++) {
Hashtable rec = new Hashtable();
rec.put("R_SoftInstallDate", NmaCollectorSnmpDO.toDateStringFormSnmpValue(szaryInsSoftware[i][5], null));
rec.put("R_SoftwareName", NmaCollectorCommonFun.toStringFormSnmpValue(szaryInsSoftware[i][2]));
result.put("software" + iIndex, rec);
if(rec != null && rec.size() != 0){
iIndex++;
}
}
return result;
}