我是靠谱客的博主 悦耳白昼,最近开发中收集的这篇文章主要介绍java+snmp调用(测试有效),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

建议 先去了解 snmp常识 ,不了解也不影响(替换oid就行)

1.环境(jdk1.8 +maven3)

主要jar包   snmp4j

 <modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xu</groupId>
<artifactId>xu</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>xu</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--SNMP简单网络协议-->
<dependency>
<groupId>org.snmp4j</groupId>
<artifactId>snmp4j</artifactId>
<version>2.8.3</version>
</dependency>
<!--SNMP简单网络协议-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

2.代码(测试代码,成功)

背景: 华三交换机  ,版本v2c有效(v3测试不成功)

常用oid  (百度以下都能找到,不常用的不清楚)

两种方式  ( 常量 的 **** 值替换成实际值,由于v2c版本有效,所以 把 

//get 地址 
//trap 地址

注释处修改就ok,还有 团体名 修改成实际值

1.get方式

/**
* @description: get方式获取数据
* @author: yghhz
* @create: 2020-11-15 10:14
**/
public class MultiThreadedGetDemo {
private static final Logger LOGGER = LogManager.getLogger(MultiThreadedGetDemo.class);
//用户名
private String username = "***************";
//鉴权密码
private String authPassword = "************!";
//数据加密密码
private String privPassword = "************!";
//trap地址
private String address = "udp:************/162";
//get 地址
private String addressGet = "udp:************/161";
private MultiThreadedMessageDispatcher dispatcher;
private Snmp snmp = null;
private Address listenAddress;
private ThreadPool threadPool;
public MultiThreadedGetDemo() {
}
public void
initSnmp() throws IOException {
//1、初始化多线程消息转发类
MessageDispatcher messageDispatcher = new MessageDispatcherImpl();
//其中要增加三种处理模型。如果snmp初始化使用的是Snmp(TransportMapping<? extends Address> transportMapping) ,就不需要增加
messageDispatcher.addMessageProcessingModel(new MPv1());
messageDispatcher.addMessageProcessingModel(new MPv2c());
//当要支持snmpV3版本时,需要配置user
OctetString localEngineID = new OctetString(MPv3.createLocalEngineID());
USM usm = new USM(SecurityProtocols.getInstance().addDefaultProtocols(), localEngineID, 0);
OctetString userName1 = new OctetString(username);
OctetString authPass = new OctetString(authPassword);
OctetString privPass = new OctetString(privPassword);
UsmUser user = new UsmUser(userName1, AuthMD5.ID, authPass, PrivAES128.ID, privPass);
usm.addUser(user.getSecurityName(), user);
messageDispatcher.addMessageProcessingModel(new MPv3(usm));
//2、创建transportMapping
ip为本地ip,可以不设置
TransportMapping<?> transportMapping = new DefaultUdpTransportMapping();
//3、正式创建snmp
snmp = new Snmp(messageDispatcher, transportMapping);
//开启监听
snmp.listen();
}
private
Target createTarget(String oid) {
Target target = null;
int version = 1;
if (!(version == SnmpConstants.version3 || version == SnmpConstants.version2c || version == SnmpConstants.version1)) {
//log.error("参数version异常");
return target;
}
if (version == SnmpConstants.version3) {
target = new UserTarget();
//snmpV3需要设置安全级别和安全名称,其中安全名称是创建snmp指定user设置的new OctetString("SNMPV3")
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString(this.username));
} else {
//snmpV1和snmpV2需要指定团体名名称
target = new CommunityTarget();
((CommunityTarget) target).setCommunity(new OctetString("******"));
if (version == SnmpConstants.version2c) {
target.setSecurityModel(SecurityModel.SECURITY_MODEL_SNMPv2c);
}
}
target.setVersion(version);
//必须指定,没有设置就会报错。
target.setAddress(GenericAddress.parse(this.addressGet));
target.setRetries(3);
target.setTimeout(2000);
return target;
}
private static PDU createPDU(int version, int type, String oid) {
PDU pdu = null;
if (version == SnmpConstants.version3) {
pdu = new ScopedPDU();
} else {
pdu = new PDUv1();
}
pdu.setType(type);
//可以添加多个变量oid
/*for(String oid:oids){
pdu.add(new VariableBinding(new OID(oid)));
}*/
pdu.add(new VariableBinding(new OID(oid)));
return pdu;
}
/**
* GET方式请求
* @param oid
*/
public
List<Map> snmpGet(String oid) {
try {
LOGGER.info("getfangshi");
List<Map> list = new ArrayList<Map>();
//1、初始化snmp,并开启监听
initSnmp();
//2、创建目标对象
Target target = this.createTarget(oid);
//3、创建报文
PDU pdu = createPDU(1, PDU.GET, oid);
//4、发送报文,并获取返回结果
ResponseEvent responseEvent = snmp.send(pdu, target);
PDU response = responseEvent.getResponse();
if (response == null) {
System.out.println("TimeOut...");
} else {
if (response.getErrorStatus() == PDU.noError) {
//get方式获取到的返回值
Vector<? extends VariableBinding> vbs = response.getVariableBindings();
for (VariableBinding vb : vbs) {
Map map = new HashMap();
map.put("value",vb.getVariable());
System.out.println("vb.getVariable():"
+ vb.getVariable());
System.out.println("OID:"
+ vb.getVariable());
LOGGER.info("OIDvALUE"
+ vb.getVariable());
list.add(map);
}
return list;
} else {
System.out.println("Error:" + response.getErrorStatusText());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//开启监控的main方法。
public static void main(String[] args) throws IOException {
MultiThreadedGetDemo multithreadedtrapreceiver = new MultiThreadedGetDemo();
multithreadedtrapreceiver.run();
}
public void run() {
try {
System.out.println("开始监听get信息!");
LOGGER.info("内存");
//
String devOid = "1.3.6.1.4.1.25506.2.6.1.1.1.1.8";
String devOid = "1.3.6.1.2.1.1.5.0";
this.snmpGet(devOid);
LOGGER.info("接口");
String devOid2 = "1.3.6.1.2.1.2.1.0";
//
this.snmpGet(devOid2);
//
LOGGER.info("cpu");
//
String devOid1 = "1.3.6.1.4.1.25506.2.6.1.1.1.1.6";
//
this.snmpGet(devOid1);
//
LOGGER.info("运行时间");
//
String data1 = "1.3.6.1.2.1.1.3.0";
//
this.snmpGet(data1);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

2.walk

@Slf4j
public class MultiThreadedWalkDemo {
private static final Logger LOGGER = LogManager.getLogger(MultiThreadedWalkDemo.class);
//用户名
private String username = "m********er";
//鉴权密码
private String authPassword = "Te****************";
//数据加密密码
private String privPassword = "T********!";
//trap地址
private String address = "udp:********/162";
//get 地址
private String addressGet = "udp:********/161";
//get 地址
private String publicName = "*********";
//
private String publicName = "********";
public Snmp snmp;
public MultiThreadedWalkDemo() {
}
public void
initSnmp() throws IOException {
//1、初始化多线程消息转发类
MessageDispatcher messageDispatcher = new MessageDispatcherImpl();
//其中要增加三种处理模型。如果snmp初始化使用的是Snmp(TransportMapping<? extends Address> transportMapping) ,就不需要增加
messageDispatcher.addMessageProcessingModel(new MPv1());
messageDispatcher.addMessageProcessingModel(new MPv2c());
//当要支持snmpV3版本时,需要配置user
OctetString localEngineID = new OctetString(MPv3.createLocalEngineID());
USM usm = new USM(SecurityProtocols.getInstance().addDefaultProtocols(), localEngineID, 0);
OctetString userName1 = new OctetString(username);
OctetString authPass = new OctetString(authPassword);
OctetString privPass = new OctetString(privPassword);
UsmUser user = new UsmUser(userName1, AuthMD5.ID, authPass, PrivAES128.ID, privPass);
usm.addUser(user.getSecurityName(), user);
messageDispatcher.addMessageProcessingModel(new MPv3(usm));
//2、创建transportMapping
ip为本地ip,可以不设置
TransportMapping<?> transportMapping = new DefaultUdpTransportMapping();
//
UdpAddress updAddr = (UdpAddress) GenericAddress.parse("udp:172.29.12.95/161");
//
TransportMapping<?> transportMapping = new DefaultUdpTransportMapping(updAddr);
//3、正式创建snmp
snmp = new Snmp(messageDispatcher, transportMapping);
//开启监听
snmp.listen();
}
private Target createTarget(String oid,int version) {
Target target = null;
//
int version = 1;
if (!(version == SnmpConstants.version3 || version == SnmpConstants.version2c || version == SnmpConstants.version1)) {
//log.error("参数version异常");
return target;
}
if (version == SnmpConstants.version3) {
target = new UserTarget();
//snmpV3需要设置安全级别和安全名称,其中安全名称是创建snmp指定user设置的new OctetString("SNMPV3")
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString(this.username));
} else {
//snmpV1和snmpV2需要指定团体名名称
target = new CommunityTarget();
//
((CommunityTarget) target).setCommunity(new OctetString(this.username));
((CommunityTarget) target).setCommunity(new OctetString(publicName));
if (version == SnmpConstants.version2c) {
target.setVersion(SnmpConstants.version2c);
target.setSecurityModel(SecurityModel.SECURITY_MODEL_SNMPv2c);
}
}
target.setVersion(version);
//必须指定,没有设置就会报错。
target.setAddress(GenericAddress.parse(this.addressGet));
target.setRetries(3);
target.setTimeout(2000);
return target;
}
private static PDU createPDU(int version, int type, String oid) {
PDU pdu = null;
if (version == SnmpConstants.version3) {
pdu = new ScopedPDU();
} else {
pdu = new PDUv1();
}
pdu.setType(type);
//可以添加多个变量oid
/*for(String oid:oids){
pdu.add(new VariableBinding(new OID(oid)));
}*/
pdu.add(new VariableBinding(new OID(oid)));
return pdu;
}
/**
* WALK方式请求
* @param oid
*/
public void snmpWalk(String oid,int version) {
try {
LOGGER.info("walkfangshi");
List<Map> list = new ArrayList<Map>();
//1、初始化snmp,并开启监听
initSnmp();
//2、创建目标对象
Target target = createTarget(oid,version);
//3、创建报文
//
PDU pdu = createPDU(1, PDU.GETNEXT, oid);
PDU pdu = createPDU(version, PDU.GETNEXT, oid);
//4、发送报文,并获取返回结果
boolean matched = true;
while (matched) {
ResponseEvent responseEvent = snmp.send(pdu, target);
//
ResponseEvent responseEvent = snmp.getNext(pdu, target);
if (responseEvent == null || responseEvent.getResponse() == null) {
System.out.println("TimeOut...");
break;
}
PDU response = responseEvent.getResponse();
String nextOid = null;
Vector<? extends VariableBinding> variableBindings = response.getVariableBindings();
for (int i = 0; i < variableBindings.size(); i++) {
Map map = new HashMap();
VariableBinding variableBinding = variableBindings.elementAt(i);
Variable variable = variableBinding.getVariable();
nextOid = variableBinding.getOid().toDottedString();
//
System.out.println("oid:" + nextOid + ",value:"
+ variable);
//如果不是这个节点下的oid则终止遍历,否则会输出很多,直到整个遍历完。
if (!nextOid.startsWith(oid)) {
matched = false;
break;
}
map.put("oid", nextOid);
map.put("value",variable);
list.add(map);
System.out.println("oid:" + nextOid + ",value:"
+ variable);
LOGGER.info("oid:" + nextOid + ",value:"
+ variable);
}
if (!matched) {
break;
}
pdu.clear();
pdu.add(new VariableBinding(new OID(nextOid)));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//开启监控的main方法。
public static void main(String[] args) throws IOException, InterruptedException {
MultiThreadedWalkDemo multithreadedtrapreceiver = new MultiThreadedWalkDemo();
multithreadedtrapreceiver.run();
//
Thread.sleep(5000);
//
multithreadedtrapreceiver.run();
}
public void run() {
try {
LOGGER.info("开始监听walk信息!");
//
LOGGER.info("开始获取端口名称!");
//
String healthOID1 = "1.3.6.1.2.1.2.2.1.2.0";
String healthOID1 = "1.3.6.1.2.1.2.2.1.2";
//
this.snmpWalk(healthOID1);
//
LOGGER.info("网口流量");
//
String healthOID2 = "1.3.6.1.2.1.2.2.1.10.0";
//
this.snmpWalk(healthOID2);
//
LOGGER.info("网口状态");
//
String healthOID3 = "1.3.6.1.2.1.2.2.1.16.0";
//
this.snmpWalk(healthOID3);
//
LOGGER.info("网口速率");
String healthOID4 = "1.3.6.1.2.1.2.2.1.16";
//
String healthOID4 = "1.3.6.1.2.1.2.2.1.5";
//
String healthOID4 = "1.3.6.1.2.1.2.2.1.16";
//
String healthOID4 = "1.3.6.1.2.1.2.2.1.3";
this.snmpWalk(healthOID4,1);
//
LOGGER.info("网口速率");
//
String healthOID5 = "1.3.6.1.2.1.31.1.1.1.15";
//
this.snmpWalk(healthOID5);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

最后

以上就是悦耳白昼为你收集整理的java+snmp调用(测试有效)的全部内容,希望文章能够帮你解决java+snmp调用(测试有效)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部