对SNMP4J的一些封装
SNMP4J是一个开源的,用Java实现的snmp协议。其中提供了一下API,在这些API上面封装了一些方法,比如SNMP的get-request请求,get-next-request请求等
如果不了解SNMP协议的点我(不是我写的)
下面贴我封装的Java代码(后面还会封装一些其他请求,比如说请求一个表格等操作)
SNMP4J jar包或源码下载点我(不用翻墙) www.snmp4j.org
定义接口Snmp_aip_interface.java
import java.util.List; public interface Snmp_aip_interface {
/**
* 根据ip,oid返回get消息
* @param ip
* @param oid
* @return
*/
public String get(String ip, String oid_str); /**
* 根据ip,oid和新值设置oid节点的值
* @param ip
* @param oid_str
* @param value_new
*/
public void set(String ip, String oid_str, String value_new); /**
* 根据ip,oid返回getNext消息
* @param ip
* @param oid_str
* @return
*/
public String getNext(String ip, String oid_str); /**
* 根据ip,oid获取bulk消息
* @param ip
* @param oid_str
* @return
*/
public List<String> getBulk(String ip, String oid_str); /**
* snmp v3版get api
* @param ip
* @param oid_str
* @return
*/
public String getV3(String ip, String oid_str); /**
* 向ip地址发送消息,这里利用发送trap消息来发送任意消息
* @param ip
* @param message
*/
public void sendMessage(String ip, String message);
}
对接口的实现Snmp_api.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector; import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping; import com.gxf.snmpinterceptor.Snmp_aip_interface; /**
* 封装snmp v 2的消息格式,对外提供接口
* 使用开源snmp4j进行封装
* 代理端监听udp 161端口,管理端监听的是udp 162端口
* snmp2c提供的消息格式,Get,GetNext,Set,Reponse,Trap,GetBulk,
* @author Administrator
*
* PDU类型 版本(0)|共同体|PDU类型(0-3)|请求标识|差错索引|差错状态(0-5)|差错索引|名称|值|名称|值...
*
* trap
*
* |PDU类型(0-3)|企业|代理地址|trap类型(0-6)|特定代码|时间戳|名称|值..
*
*/
public class Snmp_api implements Snmp_aip_interface{
private Snmp snmp;
private TransportMapping transportMapping;
private int timeOut;
private int timesRetry; public Snmp_api(){
// Thread thread_rec = new receiveTrapThread();
// thread_rec.start();
// listen();
} private void init(){
try {
transportMapping = new DefaultUdpTransportMapping();
} catch (IOException e) {
System.out.println("init transportMapping failed!");
System.out.println(e.getMessage());
}
snmp = new Snmp(transportMapping);
timeOut = 1500;
timesRetry = 2;
} /**
* 根据ip,oid返回get消息
* @param ip
* @param oid
* @return
*/
public String get(String ip, String oid_str){
init();
String ret = "";
//构造PDU
PDU pdu = new PDU();
OID oid = new OID(oid_str);
VariableBinding vb = new VariableBinding(oid);
pdu.add(vb);
pdu.setType(PDU.GET); //构造target
String address_str = "udp:" + ip + "/161";
// String address_str = "udp:210.38.235.184/161";
Address address = GenericAddress.parse(address_str);
OctetString name_com = new OctetString("public");
CommunityTarget target = new CommunityTarget();
target.setAddress(address); //设置address
target.setRetries(timesRetry);
target.setTimeout(timeOut);
target.setVersion(SnmpConstants.version2c); //设置版本号
target.setCommunity(name_com); //设置团体名 try {
this.transportMapping.listen();
} catch (IOException e) {
System.out.println("transportMapping.listen() failed!");
System.out.println(e.getMessage());
}
ResponseEvent responseEvent = null;
//发送消息
try {
responseEvent = snmp.send(pdu, target);
} catch (IOException e) {
System.out.println("snmp.send(pdu, target) failed");
System.out.println(e.getMessage());
}
//获取结果
if(responseEvent != null){
PDU pdu_rep = responseEvent.getResponse();
for(int i = 0; i < pdu_rep.size(); i++){
VariableBinding vb_temp = pdu_rep.get(i);
Variable var_temp = vb_temp.getVariable();
ret += var_temp.toString();
}//for
}//if
try {
transportMapping.close(); //关闭正在进行的监听
} catch (IOException e) {
System.out.println("transportMapping.close() failed!");
System.out.println(e.getMessage());
}
return ret;
} /**
* 根据ip,oid和新值设置oid节点的值
* @param ip
* @param oid_str
* @param value_new
*/
public void set(String ip, String oid_str, String value_new){
init();
//构造PDU
PDU pdu = new PDU();
OID oid = new OID(oid_str);
VariableBinding vb = null; vb = new VariableBinding(oid, new OctetString(value_new)); pdu.add(vb);
pdu.setType(PDU.SET); //构造target
String address_str = "udp:" + ip + "/161";
CommunityTarget target = new CommunityTarget();
OctetString com_oct = new OctetString("public");
target.setCommunity(com_oct); //设置团体名
Address address = GenericAddress.parse(address_str);
target.setAddress(address); //设置address
target.setVersion(SnmpConstants.version2c); //设置版本号
target.setTimeout(1500);
target.setRetries(timesRetry); //发送pdu
try {
transportMapping.listen();
} catch (IOException e) {
System.out.println("listen failed in set pdu");
System.out.println(e.getMessage());
}
try {
snmp.send(pdu, target);
} catch (IOException e) {
System.out.println("send failed in send set message!");
System.out.println(e.getMessage());
} finally{
try {
transportMapping.close(); //关闭正在进行的监听
} catch (IOException e) {
System.out.println("transportMapping.close() failed!");
System.out.println(e.getMessage());
}
}
} /**
* 根据ip,oid返回getNext消息
* @param ip
* @param oid_str
* @return
*/
public String getNext(String ip, String oid_str){
init();
String ret = "";
//构造PDU
PDU pdu = new PDU();
OID oid = new OID(oid_str);
VariableBinding vb = new VariableBinding(oid);
pdu.add(vb);
pdu.setType(PDU.GETNEXT); //构造target
String address_str = "udp:" + ip + "/161"; //UDP和ip
CommunityTarget target = new CommunityTarget();
Address address = GenericAddress.parse(address_str);
target.setCommunity(new OctetString("public"));
target.setAddress(address);
target.setTimeout(timeOut);
target.setRetries(timesRetry);
target.setVersion(SnmpConstants.version2c); //设置版本号 ResponseEvent responseEvent = null; try {
this.transportMapping.listen(); //开始监听
} catch (IOException e1) {
System.out.println("transportMapping.listen() failed!");
System.out.println(e1.getMessage());
} //发送消息
try {
responseEvent = snmp.send(pdu, target);
if(responseEvent != null){ //组装返回的消息
PDU pdu_reponse = responseEvent.getResponse();
for(int i = 0; pdu_reponse != null && i < pdu_reponse.size(); i++){
VariableBinding vb_temp = pdu_reponse.get(i);
Variable var_temp = vb_temp.getVariable();
ret += var_temp.toString();
}
}
} catch (IOException e) {
System.out.println("snmp.send(pdu, target) failed! in getNext");
e.printStackTrace();
} finally{ //关闭监听
try {
this.transportMapping.close();
snmp.close();
} catch (IOException e) {
System.out.println("transportMapping.close() failed!");
System.out.println(e.getMessage());
}
}//finally return ret;
} /**
* 根据ip,oid获取bulk消息
* @param ip
* @param oid_str
* @return
*/
public List<String> getBulk(String ip, String oid_str){
init();
List<String> ret = new ArrayList<String>();
//构造PDU
PDU pdu = new PDU();
pdu.setType(PDU.GETBULK);
pdu.setMaxRepetitions(200);
pdu.setNonRepeaters(0);
OID oid = new OID(oid_str);
VariableBinding vb = new VariableBinding(oid);
pdu.add(vb); //构造target
String address_str = "udp:" + ip + "/161"; //UDP和ip
CommunityTarget target = new CommunityTarget();
Address address = GenericAddress.parse(address_str);
target.setCommunity(new OctetString("public"));
target.setVersion(SnmpConstants.version2c);
target.setAddress(address);
target.setTimeout(timeOut);
target.setRetries(timesRetry); try { //开始监听UDP端口
this.transportMapping.listen();
} catch (IOException e) {
System.out.println("transportMapping.listen() failed!");
System.out.println(e.getMessage());
} //发送消息
ResponseEvent responseEvent = null;
try {
responseEvent = this.snmp.send(pdu, target);
} catch (IOException e) {
System.out.println(".snmp.send(pdu, target) failed! in getBulk");
e.printStackTrace();
} if(responseEvent != null){
PDU pdu_rec = responseEvent.getResponse(); System.out.println(pdu_rec.size()); //输出为0,说明前面没有获取到数据
for(int i = 0; i < pdu_rec.size(); i++){
String str_temp = "";
VariableBinding vb_temp = pdu_rec.get(i);
str_temp += vb_temp.getOid() + " ";
str_temp += vb_temp.getVariable().toString();
ret.add(str_temp);
}//for
}//if try {
this.transportMapping.close();
} catch (IOException e) {
System.out.println("transportMapping.close() failed!");
System.out.println(e.getMessage());
} return ret;
} /**
* 接收trap消息线程
* @author Administrator
*
*/
private class receiveTrapThread extends Thread{
public void run(){
System.out.println("start run thread.."); try {
transportMapping.listen();
} catch (IOException e) {
System.out.println("listen failed in receiveTrapThread.run()!");
e.printStackTrace();
}
CommandResponder commandResponder = new CommandResponder(){
@Override
public void processPdu(CommandResponderEvent event) {
System.out.println("enter processPdu()...");
PDU pdu_receive = event.getPDU();
StringBuffer sb = new StringBuffer(); for(int i = 0; i < pdu_receive.size(); i++){
VariableBinding vb_temp = pdu_receive.get(i);
sb.append(vb_temp.getVariable().toString());
}//for
System.out.println(sb.toString());
} };
snmp.addCommandResponder(commandResponder);
}
} public synchronized void listen(){
System.out.println("start listen..");
try {
this.wait();
} catch (InterruptedException e) { e.printStackTrace();
}
} /* (non-Javadoc)
* @see com.gxf.snmp.interfaces.Snmp_aip_interface#getV3(java.lang.String, java.lang.String)
*/
@Override
public String getV3(String ip, String oid_str) {
Snmp snmp = null;
try {
snmp = new Snmp(new DefaultUdpTransportMapping()); USM usm = new USM(SecurityProtocols.getInstance(),
new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm); snmp.listen();
} catch (IOException e) {
e.printStackTrace();
}
UsmUser user = new UsmUser(
new OctetString("luckygxf"),
AuthMD5.ID, new OctetString("luckygxf"),
PrivDES.ID, new OctetString("luckygxf")
);
OctetString contextEngineId = new OctetString("0002651100[02]");
snmp.getUSM().addUser(new OctetString("nmsAdmin"), new OctetString("0002651100"), user);
snmp.getUSM().addUser(new OctetString("luckygxf"), user);
String address_str = ip + "/161";
// System.out.println("address_str = " + address_str);
Address address = new UdpAddress(address_str);
UserTarget target = new UserTarget();
target.setVersion(SnmpConstants.version3);
target.setAddress(address);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString("luckygxf"));
target.setTimeout(2000);
target.setRetries(1); ScopedPDU pdu = new ScopedPDU();
pdu.setType(PDU.GET);
pdu.setContextEngineID(contextEngineId);
VariableBinding vb = new VariableBinding(new OID(oid_str));
pdu.add(vb); ResponseEvent responseEvent = null;
try {
responseEvent = snmp.send(pdu, target);
} catch (IOException e) { e.printStackTrace();
}
StringBuffer sb = new StringBuffer(); //返回的字符串
if(null != responseEvent){
PDU pdu_rec = responseEvent.getResponse();
// System.out.println("pdu_rec.size() = " + pdu_rec.size());
if(pdu_rec != null){
Vector<? extends VariableBinding> vbs = pdu_rec.getVariableBindings();
for(VariableBinding vb_temp : vbs){
sb.append(vb_temp.getVariable().toString());
}//for
}
}//if try {
snmp.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString(); } /* (non-Javadoc)
* @see com.gxf.snmp.interfaces.Snmp_aip_interface#sendMessage(java.lang.String, java.lang.String)
*/
@Override
public void sendMessage(String ip, String message) {
//构造trap PDU
PDU pdu = new PDU();
VariableBinding vb = new VariableBinding(new OID("1.3.6.1.2.3377.10.1.1.1.1"), new OctetString(message));
pdu.add(vb);
pdu.setType(PDU.TRAP); //构造target
String address_str = "udp:" + ip + "/16200"; //这里发送端口为16200
CommunityTarget target = new CommunityTarget();
Address address = GenericAddress.parse(address_str);
target.setAddress(address);
target.setVersion(SnmpConstants.version2c);
target.setCommunity(new OctetString("public"));
target.setTimeout(2000);
target.setRetries(2);
TransportMapping<UdpAddress> tranportMapping = null;
try {
tranportMapping = new DefaultUdpTransportMapping();
tranportMapping.listen();
} catch (IOException e) {
System.out.println("sendTrap(String ip) failed in Snmp_api.sendTrap(String ip)!");
e.printStackTrace();
}
Snmp snmp = new Snmp(tranportMapping);
try {
ResponseEvent responseEvent = snmp.send(pdu, target); //得到回复的pdu
if(null != responseEvent){
StringBuffer sb = new StringBuffer();
PDU pdu_rec = responseEvent.getResponse();
for(int i = 0;pdu_rec != null && i < pdu_rec.size(); i++){
VariableBinding vb_temp = pdu_rec.get(i);
sb.append(vb.getVariable().toInt());
}//for System.out.println(sb.toString());
}
} catch (IOException e) {
System.out.println("snmp.send(pdu, target) failed in Snmp_api.sendTrap(String ip)!");
} try {
tranportMapping.close();
snmp.close(); //关闭tansportmapping and snmp 释放资源
} catch (IOException e) {
System.out.println("tranportMapping.close() and snmp.close() failed in Snmp_api.sendTrap(String ip)!");
e.printStackTrace();
} }
}
P.S.从google code中copy了一份到github中:https://github.com/luckygxf/flower
这个封装的功能更强大
对SNMP4J的一些封装的更多相关文章
- [C#] 简单的 Helper 封装 -- RegularExpressionHelper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- iOS开发之App间账号共享与SDK封装
上篇博客<iOS逆向工程之KeyChain与Snoop-it>中已经提到了,App间的数据共享可以使用KeyChian来实现.本篇博客就实战一下呢.开门见山,本篇博客会封装一个登录用的SD ...
- Ajax实现原理,代码封装
都知道实现页面的异步操作需要使用Ajax,那么Ajax到是怎么实现异步操作的呢? 首先需要认识一个对象 --> XMLHttpRequest 对象 --> Ajax的核心.它有许多的属性和 ...
- 用C语言封装OC对象(耐心阅读,非常重要)
用C语言封装OC对象(耐心阅读,非常重要) 本文的主要内容来自这里 前言 做iOS开发的朋友,对OC肯定非常了解,那么大家有没有想过OC中NSInteger,NSObject,NSString这些对象 ...
- 【知识必备】RxJava+Retrofit二次封装最佳结合体验,打造懒人封装框架~
一.写在前面 相信各位看官对retrofit和rxjava已经耳熟能详了,最近一直在学习retrofit+rxjava的各种封装姿势,也结合自己的理解,一步一步的做起来. 骚年,如果你还没有掌握ret ...
- 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)
前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...
- 封装集合(Encapsulate Collection)
封装就是将相关的方法或者属性抽象成为一个对象. 封装的意义: 对外隐藏内部实现,接口不变,内部实现自由修改. 只返回需要的数据和方法. 提供一种方式防止数据被修改. 更好的代码复用. 当一个类的属性类 ...
- CSharpGL(29)初步封装Texture和Framebuffer
+BIT祝威+悄悄在此留下版了个权的信息说: CSharpGL(29)初步封装Texture和Framebuffer +BIT祝威+悄悄在此留下版了个权的信息说: Texture和Framebuffe ...
- CSharpGL(7)对VAO和VBO的封装
CSharpGL(7)对VAO和VBO的封装 2016-08-13 由于CSharpGL一直在更新,现在这个教程已经不适用最新的代码了.CSharpGL源码中包含10多个独立的Demo,更适合入门参考 ...
随机推荐
- 题解 BZOJ 1002 【[FJOI2007]轮状病毒】
题目链接 emm…… 正解:矩阵树定理,但是本宝宝不会求基尔霍夫矩阵. 开始考场方法: 手动模拟$n=1--5$时的答案(数不大,~~画画就出来了~~要画上半个小时). 画出来,答案是这样的:$1$ ...
- Python3之XML模块
一.简介 xml是实现不同语言或程序之间进行数据交换的协议,可扩展标记语言,标准通用标记语言的子集.是一种用于标记电子文件使其具有结构性的标记语言.xml格式如下,是通过<>节点来区别数据 ...
- Python描述符深入理解
Python的描述符乍眼看去简单,但是细节方面如果不注意容易掉坑,总结以下几个坑,以作备忘,先看代码: class D: def __get__(self, inst, owner): if inst ...
- python学习之路---day20--面向对象--多继承和super() 函数
一:python多继承 python多继承中,当一个类继承了多个父类时候,这个类拥有多个父类的所欲非私有的属性 l例子: class A: pass class B(A): pass class C( ...
- C++_语法知识点大纲
最近在学习C++的STL和泛型编程的部分,其中涉及到很多词汇.术语.在这里做一些梳理,以便有条理性地去理解泛型编程的设计理念. 整体上来讲编程主要有两种理念: 面向对象的编程——侧重点是数据: 泛型编 ...
- JAVA数据结构--插入排序
插入排序(英语:Insertion Sort)是一种简单直观的排序算法.它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入.插入排序在实现上,通常采用in- ...
- Codeforces - 185A 简单矩阵快速幂
题意:求第n个三角形内部的上三角形个数 对每个三角形分别维护上下三角形个数,记为\(dp[1][i],dp[2][i]\) 规律很明显是 \(dp[1][i+1]=3*dp[1][i]+dp[2][i ...
- ACM浮点数相关的陷阱
误差修正 因为被计算机表示浮点数的方式所限制,CPU在进行浮点数计算时会出现误差.如执行0.1 + 0.2 == 0.3结果往往为false,在四则运算中,加减法对精度的影响较小,而乘法对精度的影响更 ...
- Selenium => Debugging “Element is not clickable at point” error
[From] http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error ...
- Q205 同构字符串
给定两个字符串 s 和 t,判断它们是否是同构的. 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的. 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序.两个字符不能映射到同一 ...