您的位置:首页 > 编程语言

一段snmp代码

2016-05-14 13:51 337 查看
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.Gauge32;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableListener;
import org.snmp4j.util.TableUtils;

import com.nufront.euht.util.StringUtil;
import com.nufront.euht.web.common.util.MyStringUtil;
import com.nufront.euht.web.deviceConfig.dataStruct.SnmpDataStruct;

/**
* snmp父类
* */
public class ParentSnmp {
private static Log log = LogFactory.getLog(ParentSnmp.class);
public static final int DEFAULT_VERSION = SnmpConstants.version2c;
public static final String DEFAULT_PROTOCOL = "udp";
public static final int DEFAULT_PORT = 161;
public static final long DEFAULT_TIMEOUT = 800L;   // ms
public static final int DEFAULT_RETRY = 2;
public static final String COMMUNITY_PUBLIC = "euhtpub";
public static final String COMMUNITY_PRIVATE = "euhtpri";
private static final String DEFINE_OID ="59418";
private static final int  BULK_MAX_ROWS_NUMBER = 20; // BULK每次请求最大的行数
private Snmp snmp;
/**
* 创建对象communityTarget
*
*  targetAddress
* @param community
* @param version
* @param timeOut
* @param retry
* @return C@paramommunityTarget
*/
public static CommunityTarget createTargetDefault(String ip, String community) {
if(StringUtil.isNullOrBlank(ip)){
return null ;
}
Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
+ "/" + DEFAULT_PORT);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(address);
target.setVersion(DEFAULT_VERSION);
target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
target.setRetries(DEFAULT_RETRY);
address = null;
return target;
}

public String snmpGetOne(String ip, String community, String oid){
if(ip!=null&&community!=null&&oid!=null){
//初始化CommunityTarget
CommunityTarget target = this.createTargetDefault(ip, community);
PDU pdu = null;
DefaultUdpTransportMapping transport = null;
//初始化snmp
try {
pdu = new PDU();
pdu.add(new VariableBinding(new OID(oid)));
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
pdu.setType(PDU.GET);
//发送pdu
ResponseEvent respEvent = snmp.send(pdu, target);
log.debug("PeerAddress:" + respEvent.getPeerAddress());
//得到响应信息
PDU response = respEvent.getResponse();
if (response == null) { //离线
log.debug("response is null, request time out");
} else {
//解析数据
VariableBinding vb = response.get(0);
String value = vb.getVariable().toString();
vb = null;
return 	value;
}
respEvent = null;
response = null;
log.debug("SNMP GET one OID value finished !");
} catch (Exception e) {
log.error("SNMP Get Exception:" + e);

} finally {
if (snmp != null) {
try {
snmp.close();
snmp = null;
} catch (IOException ex1) {
snmp = null;
}
}
try{
if(pdu!=null){
pdu = null;
}
if(transport!=null){
transport.close();
transport = null;
}

}catch(Exception e){
pdu = null;
transport = null;
e.printStackTrace();
}

}
target = null;

}
return null;
}
/**
* 创建对象communityTarget
*
*  targetAddress
* @param community
* @param version
* @param timeOut
* @param retry
* @return C@paramommunityTarget
*/
public static CommunityTarget createDefault(String ip, String community) {
if(StringUtil.isNullOrBlank(ip)){
return null ;
}
Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
+ "/" + DEFAULT_PORT);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(address);
target.setVersion(DEFAULT_VERSION);
target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
target.setRetries(DEFAULT_RETRY);
return target;
}
/* 获取表格 */
public static Map<String,Object> snmpWalk(String ip, String community, String targetOid) {
Map<String,Object> resultMap =  new HashMap<String,Object>();
CommunityTarget target = createDefault(ip, community);
TransportMapping transport = null;
PDU pdu = null;
Snmp snmp = null;
try {
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();

pdu = new PDU();
OID targetOID = new OID(targetOid);
pdu.add(new VariableBinding(targetOID));

boolean finished = false;
System.out.println("----> demo start <----");
while (!finished) {
VariableBinding vb = null;
ResponseEvent respEvent = snmp.getNext(pdu, target);

PDU response = respEvent.getResponse();

if (null == response) {
System.out.println("responsePDU == null");
finished = true;
break;
} else {
vb = response.get(0);
}
// check finish
finished = checkWalkFinished(targetOID, pdu, vb);
if (!finished) {
System.out.println("==== walk each vlaue :");
System.out.println(vb.getOid() + " = " + vb.getVariable());
resultMap.put(vb.getOid().toString(), vb.getVariable());
// Set up the variable binding for the next entry.
pdu.setRequestID(new Integer32(0));
pdu.set(0, vb);
} else {
System.out.println("SNMP walk OID has finished.");
snmp.close();
}
respEvent =null;
response = null;
vb = null;
}
targetOID =null;
System.out.println("----> demo end <----");
} catch (Exception e) {
e.printStackTrace();
System.out.println("SNMP walk Exception: " + e);
} finally {
target = null;
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex1) {
snmp = null;
}
}
try{
if(pdu!=null){
pdu = null;
}
if(transport!=null){
transport.close();
transport = null;
}

}catch(Exception e){
pdu = null;
transport = null;
e.printStackTrace();
}
}
return resultMap;
}

private static boolean checkWalkFinished(OID targetOID, PDU pdu,
VariableBinding vb) {
boolean finished = false;
if (pdu.getErrorStatus() != 0) {
System.out.println("[true] responsePDU.getErrorStatus() != 0 ");
System.out.println(pdu.getErrorStatusText());
finished = true;
} else if (vb.getOid() == null) {
System.out.println("[true] vb.getOid() == null");
finished = true;
} else if (vb.getOid().size() < targetOID.size()) {
System.out.println("[true] vb.getOid().size() < targetOID.size()");
finished = true;
} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
System.out.println("[true] targetOID.leftMostCompare() != 0");
finished = true;
} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
System.out
.println("[true] Null.isExceptionSyntax(vb.getVariable().getSyntax())");
finished = true;
} else if (vb.getOid().compareTo(targetOID) <= 0) {
System.out.println("[true] Variable received is not "
+ "lexicographic successor of requested " + "one:");
System.out.println(vb.toString() + " <= " + targetOID);
finished = true;
}
return finished;

}

public Map<String,Object> snmpGetAll(String ip, String community, String[] oidArray) {
Map<String,Object> map = new HashMap<String,Object>();
if(ip!=null&&community!=null&&oidArray!=null){
//初始化CommunityTarget
CommunityTarget target = this.createTargetDefault(ip, community);
PDU pdu = null;
DefaultUdpTransportMapping transport = null;

//初始化snmp
try {
pdu = new PDU();
for(int i = 0 ; i < oidArray.length ; i++){
pdu.add(new VariableBinding(new OID(oidArray[i])));
}
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
pdu.setType(PDU.GET);
//发送pdu
ResponseEvent respEvent = snmp.send(pdu, target);
log.debug("PeerAddress:" + respEvent.getPeerAddress());
//得到响应信息
PDU response = respEvent.getResponse();
if (response == null) { //离线
log.debug("response is null, request time out");
} else {
//解析数据
//					VariableBinding vb = response.get(0);
for(int i = 0 ; i < response.size() ; i ++){
VariableBinding vb = response.get(i);
String oid = vb.getOid().toString();
String value = vb.getVariable().toString();
map.put(oid, value);
vb = null;
}

}
log.debug("SNMP GET one OID value finished !");
respEvent = null;
response = null;
} catch (Exception e) {
log.error("SNMP Get Exception:" + e);

} finally {
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex1) {
snmp = null;
}
}
try{
if(pdu!=null){
pdu = null;
}
if(transport!=null){
transport.close();
transport = null;
}

}catch(Exception e){
pdu = null;
transport = null;
e.printStackTrace();
}
}
//回收内存
target = null;
pdu = null;
transport = null;
}
return map;
}

/**
* 设置信息
* type = 0 为 long
* type = 1 为 string
* */
public static String setPDU(String ip, String community, String oid , Object value,int type)
throws IOException {
String snmpTipsInfo ="";
if(!StringUtil.isNullOrBlank(ip)){
CommunityTarget target = createTargetDefault(ip, community);
Snmp snmp = null;
PDU pdu = new PDU();
if(type==0){
pdu.add(new VariableBinding(new OID(oid), new Gauge32(Long.parseLong(value+""))));
}else if(type==1){
pdu.add(new VariableBinding(new OID(oid), new OctetString((String)value)));
}

pdu.setType(PDU.SET);

DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();

log.debug("-------> setPDU single <-------");
ResponseEvent response =  snmp.send(pdu, target);
PDU responsePDU = response.getResponse();

if(responsePDU!=null){
String errorText = responsePDU.getErrorStatusText();
if(errorText.contains("Success")){
snmpTipsInfo = "成功";
}else{
snmpTipsInfo = "ip或者oid出错";
}

}else{
snmpTipsInfo = "网络不通";
}

snmp.close();
}
return snmpTipsInfo;
}

/* 设置信息 */
public static void setPDU(String ip, String community, List<SnmpDataStruct> list)
throws IOException {
if(!StringUtil.isNullOrBlank(ip)){
CommunityTarget target = createTargetDefault(ip, community);
Snmp snmp = null;
PDU pdu = new PDU();
if(list!=null){
SnmpDataStruct snmpDataStruct = null;
for(int i = 0 ; i < list.size() ; i++){
snmpDataStruct = list.get(i);
if(snmpDataStruct.getType()==0){
if( Integer.parseInt(snmpDataStruct.getValue()+"")!=-1){
pdu.add(new VariableBinding(new OID(snmpDataStruct.getOid()), new Gauge32(Long.parseLong(snmpDataStruct.getValue()+""))));
}

}else if(snmpDataStruct.getType()== 1){
if(snmpDataStruct.getValue()!=null&&!"".equals((snmpDataStruct.getValue()+"").replace(" ", "")))
pdu.add(new VariableBinding(new OID(snmpDataStruct.getOid()), new OctetString(snmpDataStruct.getValue()+"")));
}
}
}

pdu.setType(PDU.SET);
DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
log.debug("-------> setPDU list <-------");
snmp.send(pdu, target);
snmp.close();
}
}

/**
* 采用读表Oid,读取所有信息
* @throws IOException
* */
public Map<String,String> Snmp4jTableUtils(String ip,String community,String tableOid,Snmp snmp) throws IOException{
Map<String,String> map = new HashMap<String,String>();
if( MyStringUtil.strIsNullOrBlank(ip) || MyStringUtil.strIsNullOrBlank(community) || MyStringUtil.strIsNullOrBlank(tableOid)  || snmp == null ){
return map ;
}
OID[] columnOIDs = {
new OID(tableOid)
};
CommunityTarget target = createDefaultSnmpTarget(ip,community);
TableListener listener;
snmp.listen();
TableUtils utils = new TableUtils(snmp, new DefaultPDUFactory(PDU.GET));
utils.setMaxNumRowsPerPDU(BULK_MAX_ROWS_NUMBER);   // max 20 rows each BULK request
List<TableEvent> events = utils.getTable(target, columnOIDs, null, null);  //rows: all
VariableBinding[] vbs = null;
String oid = null;
String value = null;
for( TableEvent e :events ){
vbs = e.getColumns();
if(vbs!=null){
oid = vbs[0].getOid().toString();
value = vbs[0].getVariable().toString();
if( oid.contains(DEFINE_OID)){
map.put(oid, value);
}
}

}
return map;
}

private static CommunityTarget createDefaultSnmpTarget(String ip, String community) {

Address address = GenericAddress.parse("udp:" + ip + "/"
+ SnmpConstants.DEFAULT_COMMAND_RESPONDER_PORT);

CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(address);
target.setVersion( SnmpConstants.version2c  );
target.setTimeout(1000);
target.setRetries(3);
return target;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: