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

相关文章

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

JAVA中整型数组、字符串数组、整型数和字符串 的创建与转换的方法

《JAVA中整型数组、字符串数组、整型数和字符串的创建与转换的方法》本文介绍了Java中字符串、字符数组和整型数组的创建方法,以及它们之间的转换方法,还详细讲解了字符串中的一些常用方法,如index... 目录一、字符串、字符数组和整型数组的创建1、字符串的创建方法1.1 通过引用字符数组来创建字符串1.2

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

el-select下拉选择缓存的实现

《el-select下拉选择缓存的实现》本文主要介绍了在使用el-select实现下拉选择缓存时遇到的问题及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录项目场景:问题描述解决方案:项目场景:从左侧列表中选取字段填入右侧下拉多选框,用户可以对右侧

SpringCloud集成AlloyDB的示例代码

《SpringCloud集成AlloyDB的示例代码》AlloyDB是GoogleCloud提供的一种高度可扩展、强性能的关系型数据库服务,它兼容PostgreSQL,并提供了更快的查询性能... 目录1.AlloyDBjavascript是什么?AlloyDB 的工作原理2.搭建测试环境3.代码工程1.

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python

SpringBoot操作spark处理hdfs文件的操作方法

《SpringBoot操作spark处理hdfs文件的操作方法》本文介绍了如何使用SpringBoot操作Spark处理HDFS文件,包括导入依赖、配置Spark信息、编写Controller和Ser... 目录SpringBoot操作spark处理hdfs文件1、导入依赖2、配置spark信息3、cont

springboot整合 xxl-job及使用步骤

《springboot整合xxl-job及使用步骤》XXL-JOB是一个分布式任务调度平台,用于解决分布式系统中的任务调度和管理问题,文章详细介绍了XXL-JOB的架构,包括调度中心、执行器和Web... 目录一、xxl-job是什么二、使用步骤1. 下载并运行管理端代码2. 访问管理页面,确认是否启动成功

Java中的密码加密方式

《Java中的密码加密方式》文章介绍了Java中使用MD5算法对密码进行加密的方法,以及如何通过加盐和多重加密来提高密码的安全性,MD5是一种不可逆的哈希算法,适合用于存储密码,因为其输出的摘要长度固... 目录Java的密码加密方式密码加密一般的应用方式是总结Java的密码加密方式密码加密【这里采用的