1.说明
简单网络管理协议(SNMP),由一组网络管理的标准组成,
包含一个应用层协议(application layer protocol)、数据库模型(database schema)和一组资源对象。
该协议能够支持网络管理系统,用以监测连接到网络上的设备是否有任何引起管理上关注的情况。
snmp4j官网:http://www.snmp4j.org/
2.实现get操作
实现获取设备的名称
源码如下:
import java.io.IOException; import java.util.Vector; 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.Address; import org.snmp4j.smi.GenericAddress; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping; public class SnmpTest { private Snmp snmp = null; private Address targetAddress = null; public void initComm() throws IOException { // 设置Agent方的IP和端口 targetAddress = GenericAddress.parse("udp:127.0.0.1/161"); TransportMapping transport = new DefaultUdpTransportMapping(); snmp = new Snmp(transport); transport.listen(); } public ResponseEvent sendPDU(PDU pdu) throws IOException { // 设置 target CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString("public")); target.setAddress(targetAddress); // 通信不成功时的重试次数 target.setRetries(2); // 超时时间 target.setTimeout(1500); target.setVersion(SnmpConstants.version1); // 向Agent发送PDU,并返回Response return snmp.send(pdu, target); } public void setPDU() throws IOException { // set PDU PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 5, 0 }), new OctetString("SNMPTEST"))); pdu.setType(PDU.SET); sendPDU(pdu); } public void getPDU() throws IOException { // get PDU PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 5, 0 }))); pdu.setType(PDU.GET); readResponse(sendPDU(pdu)); } public void readResponse(ResponseEvent respEvnt) { // 解析Response if (respEvnt != null && respEvnt.getResponse() != null) { Vector<VariableBinding> recVBs = (Vector<VariableBinding>) respEvnt.getResponse().getVariableBindings(); for (int i = 0; i < recVBs.size(); i++) { VariableBinding recVB = recVBs.elementAt(i); System.out.println(recVB.getOid() + " : " + recVB.getVariable()); } } } public static void main(String[] args) { try { SnmpTest util = new SnmpTest(); util.initComm(); util.setPDU(); util.getPDU(); } catch (IOException e) { e.printStackTrace(); } } }
其中
targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
IP地址是网络设备的IP地址,如果没有设备,可以在自己的机器上安装SNMP服务。
把IP地址该成思科的设备后,运行结果如下:
1.3.6.1.2.1.1.5.0 : Cisco6248-A