blog迁移至:
http://www.micmiu.com
依赖于第三方SNMP4j来实现snmp的get、walk功能,主要实现了如下功能:
- 一、snmp get 获取单个OID的值
- 二、snmp get 同步和异步的方式获取多个OID的值
- 三、snmp walk的方式
- 四、补充SnmpUtil.java代码
[一]、 snmp get 获取单个OID的值
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;
}
}
}
}
}
[二]、snmp get 同步和异步的方式获取多个OID的值
同步实现方法:SnmpGetList.java
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;
}
}
}
}
}
异步实现方法:SnmpGetListAsyn.java
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);
}
}
}
[三]、 SnmpWalk.java
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;
}
}
[四]、SnmpUtil.java
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 @
http://sjsky.iteye.com
-----------------------------------分 ------------------------------------隔 ------------------------------------线 --------------------------------------