Java实现snmp的get和walk代码示例

2024-01-04 16:38

本文主要是介绍Java实现snmp的get和walk代码示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[color=red]blog迁移至[/color]:[url=http://www.micmiu.com]http://www.micmiu.com[/url]

[size=large]依赖于第三方SNMP4j来实现snmp的get、walk功能,主要实现了如下功能:[/size]
[color=red][b][list]
[*]一、snmp get 获取单个OID的值
[*]二、snmp get 同步和异步的方式获取多个OID的值
[*]三、snmp walk的方式
[*]四、补充SnmpUtil.java代码
[/list][/b][/color]
[color=blue][size=medium][一]、 snmp get 获取单个OID的值[/size][/color]
SnmpGet.java

package com.michael.snmp4j;

import java.io.IOException;
import java.util.Vector;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import com.michael.snmp4j.util.SnmpUtil;

/**
* @see http://sjsky.iteye.com
* @author Michael
*/
public class SnmpGet {

private static int version = SnmpConstants.version1;
private static String protocol = "udp";
private static int port = 161;

/**
*
* @param args
*/
public static void main(String[] args) {

String ip = "192.168.8.254";
String community = "public";
String oidval = "1.3.6.1.2.1.1.3.0";
SnmpGet tester = new SnmpGet();
tester.snmpGet(ip, community, oidval);

}

@SuppressWarnings("unchecked")
private void snmpGet(String ip, String community, String oid) {

String address = protocol + ":" + ip + "/" + port;
CommunityTarget target = SnmpUtil.createCommunityTarget(address,
community, version, 2 * 1000L, 3);
DefaultUdpTransportMapping udpTransportMapping = null;
Snmp snmp = null;
try {
PDU pdu = new PDU();
// pdu.add(new VariableBinding(new OID(new int[]
// {1,3,6,1,2,1,1,2})));
pdu.add(new VariableBinding(new OID(oid)));
pdu.setType(PDU.GET);

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

// 发送同步消息
ResponseEvent response = snmp.send(pdu, target);
System.out.println("PeerAddress:" + response.getPeerAddress());
PDU responsePdu = response.getResponse();

if (responsePdu == null) {
System.out.println(ip + ":Request time out");
} else {
Vector vbVect = responsePdu.getVariableBindings();
System.out.println("vb size:" + vbVect.size());
if (vbVect.size() == 0) {
System.out.println(" pdu vb size is 0 ");
} else {
Object obj = vbVect.firstElement();
VariableBinding vb = (VariableBinding) obj;
System.out.println(vb.getOid() + " = " + vb.getVariable());
}

}
System.out.println("success finish snmp get the oid!");
} catch (Exception e) {
System.out.println("SNMP Get Exception:" + e);
} finally {
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex1) {
snmp = null;
}
}
if (udpTransportMapping != null) {
try {
udpTransportMapping.close();
} catch (IOException ex2) {
udpTransportMapping = null;
}
}
}
}
}


[color=blue][size=medium][二]、snmp get 同步和异步的方式获取多个OID的值[/size][/color]
[color=red] 同步实现方法:SnmpGetList.java[/color]
package com.michael.snmp4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import com.michael.snmp4j.util.SnmpUtil;

/**
* @see http://sjsky.iteye.com
* @author Michael
*
*/
public class SnmpGetList {

private static int version = SnmpConstants.version1;
private static String protocol = "udp";
private static int port = 161;

/**
*
* @param args
*/
public static void main(String[] args) {

String ip = "192.168.8.254";
String community = "public";
SnmpGetList tester = new SnmpGetList();
List<String> oidList = new ArrayList<String>();
oidList.add(".1.3.6.1.2.1.1.1.0");
oidList.add(".1.3.6.1.2.1.1.3.0");
oidList.add(".1.3.6.1.2.1.1.5.0");
// synchronous
tester.snmpGet(ip, community, oidList);

}

/**
*
* @param ipAddress
* @param community
* @param oid
*/
private void snmpGet(String ipAddress, String community,
List<String> oidList) {
String address = protocol + ":" + ipAddress + "/" + port;
CommunityTarget target = SnmpUtil.createCommunityTarget(address,
community, version, 2 * 1000L, 3);
DefaultUdpTransportMapping transport = null;
Snmp snmp = null;
try {
PDU pdu = new PDU();
pdu.setType(PDU.GET);
for (String oid : oidList) {
pdu.add(new VariableBinding(new OID(oid)));
}

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

ResponseEvent response = snmp.send(pdu, target);
PDU resPdu = response.getResponse();
if (resPdu == null) {
System.out.println(ipAddress + ":Request time out");
} else {
System.out.println(" response pdu vb size is " + resPdu.size());
for (int i = 0; i < resPdu.size(); i++) {
VariableBinding vb = resPdu.get(i);
System.out.println(vb.getOid() + "=" + vb.getVariable());
}
}
} catch (Exception e) {
System.out.println("SNMP GetNext Exception:" + e);
} finally {
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex1) {
snmp = null;
}
}
if (transport != null) {
try {
transport.close();
} catch (IOException ex2) {
transport = null;
}
}
}

}

}

[color=red]异步实现方法:SnmpGetListAsyn.java[/color]
package michael.snmp.snmp4j;

import java.util.ArrayList;
import java.util.List;

import michael.snmp.util.SnmpUtil;

import org.snmp4j.CommunityTarget;
import org.snmp4j.MessageDispatcherImpl;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.event.ResponseListener;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
import org.snmp4j.util.WorkerPool;

/**
* asynchronous send PDU
* @see http://sjsky.iteye.com
* @author Michael
*
*/
public class SnmpGetListAsyn {

private static int version = SnmpConstants.version1;
private static String protocol = "udp";
private static int port = 161;

/**
*
* @param args
*/
public static void main(String[] args) {

String ip = "192.168.8.254";
String community = "public";
SnmpGetListAsyn tester = new SnmpGetListAsyn();
List<String> oidList = new ArrayList<String>();
oidList.add(".1.3.6.1.2.1.1.1.0");
oidList.add(".1.3.6.1.2.1.1.3.0");
oidList.add(".1.3.6.1.2.1.1.5.0");
// asynchronous
tester.snmpAsynGet(ip, community, oidList);

}

/**
*
* @param ipAddress
* @param community
* @param oid
*/
private void snmpAsynGet(String ipAddress, String community,
List<String> oidList) {
String address = protocol + ":" + ipAddress + "/" + port;
CommunityTarget target = SnmpUtil.createCommunityTarget(address,
community, version, 2 * 1000L, 3);
DefaultUdpTransportMapping transport = null;
Snmp snmp = null;
try {
WorkerPool threadPool = ThreadPool.create("TestSNMPWorkPool", 2);
MultiThreadedMessageDispatcher dispatcher = new MultiThreadedMessageDispatcher(
threadPool, new MessageDispatcherImpl());
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(dispatcher, transport);
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
snmp.listen();

PDU pdu = new PDU();
pdu.setType(PDU.GET);
for (String oid : oidList) {
pdu.add(new VariableBinding(new OID(oid)));
}

ResponseListener listener = new ResponseListener() {
public void onResponse(ResponseEvent event) {
((Snmp) event.getSource()).cancel(event.getRequest(), this);
PDU response = event.getResponse();
PDU request = event.getRequest();
System.out.println("[request]:" + request);
if (response == null) {
System.out.println("[ERROR]: response is null");
} else if (response.getErrorStatus() != 0) {
System.out.println("[ERROR]: response status"
+ response.getErrorStatus() + " Text:"
+ response.getErrorStatusText());
} else {
System.out.println("Received response Success!!!");
for (int i = 0; i < response.size(); i++) {
VariableBinding vb = response.get(i);
System.out.println(vb);
}

}
}
};

snmp.send(pdu, target, null, listener);

System.out.println("asynchronous send pdu wait for response...");
} catch (Exception e) {
System.out.println("SNMP GetNext Exception:" + e);
}

}
}

[color=blue][size=medium][三]、 SnmpWalk.java[/size][/color]
package com.michael.snmp4j;

import java.io.IOException;

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.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import com.michael.snmp4j.util.SnmpUtil;

/**
* SnmpWalk
* @see http://sjsky.iteye.com
* @author Michael
*
*/
public class SnmpWalk {
private static int version = SnmpConstants.version1;
private static String protocol = "udp";
private static int port = 161;

/**
*
* @param args
*/
public static void main(String[] args) {
String ip = "192.168.8.254";
String community = "public";
String targetOid = "1.3.6.1.2.1.2.2.1.2";
SnmpWalk tester = new SnmpWalk();
tester.snmpWalk(ip, community, targetOid);

}

/**
* 1)responsePDU == null<br>
* 2)responsePDU.getErrorStatus() != 0<br>
* 3)responsePDU.get(0).getOid() == null<br>
* 4)responsePDU.get(0).getOid().size() < targetOID.size()<br>
* 5)targetOID.leftMostCompare(targetOID.size(),responsePDU.get(0).getOid())!=0<br>
* 6)Null.isExceptionSyntax(responsePDU.get(0).getVariable().getSyntax())<br>
* 7)responsePDU.get(0).getOid().compareTo(targetOID) <= 0<br>
* @param ipAddress
* @param community
* @param oid
*/
@SuppressWarnings("unused")
private void snmpWalk(String ip, String community, String targetOid) {
String address = protocol + ":" + ip + "/" + port;

OID targetOID = new OID(targetOid);

PDU requestPDU = new PDU();
requestPDU.setType(PDU.GETNEXT);
requestPDU.add(new VariableBinding(targetOID));

CommunityTarget target = SnmpUtil.createCommunityTarget(address,
community, version, 2 * 1000L, 3);
TransportMapping transport = null;
Snmp snmp = null;
try {
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();

boolean finished = false;
while (!finished) {
VariableBinding vb = null;
ResponseEvent response = snmp.send(requestPDU, target);
PDU responsePDU = response.getResponse();

if (null == responsePDU) {
System.out.println("responsePDU == null");
finished = true;
break;
} else {
vb = responsePDU.get(0);
}
// check finish
finished = checkWalkFinished(targetOID, responsePDU, vb);
if (!finished) {
// Dump response.
System.out.println("----"+vb.toString());
System.out.println("----"+vb.getOid().toString());
System.out.println("----"+vb.getVariable().toString());

// Set up the variable binding for the next entry.
requestPDU.setRequestID(new Integer32(0));
requestPDU.set(0, vb);
}
}
System.out.println("success finish snmp walk!");
} catch (Exception e) {
System.out.println("SNMP walk Exception: " + e);
} finally {
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex1) {
snmp = null;
}
}
if (transport != null) {
try {
transport.close();
} catch (IOException ex2) {
transport = null;
}
}
}

}

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

}

}


[color=blue][size=medium][四]、SnmpUtil.java[/size][/color]


package michael.snmp.util;

import org.snmp4j.CommunityTarget;
import org.snmp4j.UserTarget;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.UdpAddress;

/**
* @see http://sjsky.iteye.com
* @author michael
*
*/
public class SnmpUtil {

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 = 3 * 1000L;
public static final int DEFAULT_RETRY = 3;

/**
* 创建共同体对象communityTarget
* @param address
* @param community
* @return CommunityTarget
*/
public static CommunityTarget createMyDefaultTarget(String address,
String community) {
Address targetAddress = GenericAddress.parse(address);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(targetAddress);
target.setVersion(DEFAULT_VERSION);
target.setTimeout(DEFAULT_TIMEOUT);// milliseconds
target.setRetries(DEFAULT_RETRY);
return target;
}

/**
* 创建共同体对象communityTarget
* @param targetAddress
* @param community
* @param version
* @return CommunityTarget
*/
public static CommunityTarget createCommunityTarget(Address targetAddress,
String community, int version) {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(targetAddress);
target.setVersion(version);
return target;
}

/**
* 创建共同体对象communityTarget
* @param targetAddress
* @param community
* @param version
* @param timeOut
* @param retry
* @return CommunityTarget
*/
public static CommunityTarget createCommunityTarget(Address targetAddress,
String community, int version, long timeOut, int retry) {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(targetAddress);
target.setVersion(version);
target.setTimeout(timeOut); // milliseconds
target.setRetries(retry);
return target;
}

/**
* 创建共同体对象communityTarget
* @param address
* @param community
* @param version
* @param timeOut
* @param retry
* @return CommunityTarget
*/
public static CommunityTarget createCommunityTarget(String address,
String community, int version, long timeOut, int retry) {
Address targetAddress = GenericAddress.parse(address);
return createCommunityTarget(targetAddress, community, version,
timeOut, retry);
}

/**
* 创建snmp Address
* @param protocol
* @param ip
* @param port
* @return Address
*/
public static Address createAddress(String protocol, String ip, int port) {
String address = protocol + ":" + ip + "/" + port;
return GenericAddress.parse(address);
}

/**
* 创建snmp udp Address
* @param ip
* @param port
* @return Address
*/
public static Address createUdpAddress(String ip, int port) {
String address = ip + "/" + port;
return new UdpAddress(address);
}

/**
* 创建snmp tcp Address
* @param ip
* @param port
* @return Address
*/
public static TcpAddress createTcpAddress(String ip, int port) {
String address = ip + "/" + port;
return new TcpAddress(address);
}

/**
* 创建 UserTarget
* @param targetAddress
* @param version
* @param timeOut
* @param level
* @param securityName
* @return UserTarget
*/
public static UserTarget createUserTarget(Address targetAddress,
int version, long timeOut, int level, String securityName) {
UserTarget target = new UserTarget();
target.setAddress(targetAddress);
target.setRetries(1);
target.setTimeout(timeOut); // milliseconds
target.setVersion(version);
target.setSecurityLevel(level);
target.setSecurityName(new OctetString(securityName));
return target;
}

/**
* 创建 UserTarget
* @param address
* @param version
* @param timeOut
* @param level
* @param securityName
* @return UserTarget
*/
public static UserTarget createUserTarget(String address, int version,
long timeOut, int level, String securityName) {
Address targetAddress = GenericAddress.parse(address);
return createUserTarget(targetAddress, version, timeOut, level,
securityName);
}
}


转载请注明来自:Michael's blog @ [url=http://sjsky.iteye.com]http://sjsky.iteye.com [/url]

-----------------------------------分 ------------------------------------隔 ------------------------------------线 --------------------------------------

这篇关于Java实现snmp的get和walk代码示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/569946

相关文章

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

SpringCloud动态配置注解@RefreshScope与@Component的深度解析

《SpringCloud动态配置注解@RefreshScope与@Component的深度解析》在现代微服务架构中,动态配置管理是一个关键需求,本文将为大家介绍SpringCloud中相关的注解@Re... 目录引言1. @RefreshScope 的作用与原理1.1 什么是 @RefreshScope1.

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

Spring Boot 配置文件之类型、加载顺序与最佳实践记录

《SpringBoot配置文件之类型、加载顺序与最佳实践记录》SpringBoot的配置文件是灵活且强大的工具,通过合理的配置管理,可以让应用开发和部署更加高效,无论是简单的属性配置,还是复杂... 目录Spring Boot 配置文件详解一、Spring Boot 配置文件类型1.1 applicatio

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Java进行文件格式校验的方案详解

《Java进行文件格式校验的方案详解》这篇文章主要为大家详细介绍了Java中进行文件格式校验的相关方案,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、背景异常现象原因排查用户的无心之过二、解决方案Magandroidic Number判断主流检测库对比Tika的使用区分zip

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义

opencv图像处理之指纹验证的实现

《opencv图像处理之指纹验证的实现》本文主要介绍了opencv图像处理之指纹验证的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录一、简介二、具体案例实现1. 图像显示函数2. 指纹验证函数3. 主函数4、运行结果三、总结一、

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3