首页 > 代码库 > snmp4j 编程
snmp4j 编程
从www.snmp4j.org下载snmp4j的jar包,用eclipse新建一个java项目。将jar包导入工程(只有一个jar包),开始编程
一个简单的测试程序
//create target
//create pdu
//snmp.send
okay,上代码
package com.gxf.snmp;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.Address;import org.snmp4j.smi.GenericAddress;import org.snmp4j.smi.OID;import org.snmp4j.smi.OctetString;import org.snmp4j.smi.Variable;import org.snmp4j.smi.VariableBinding;import org.snmp4j.transport.DefaultUdpTransportMapping;//create target//create pdu//snmp sendpublic class SNMP { public static void main(String[] args) { //create target Address address = GenericAddress.parse("udp:210.38.235.186/161"); CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString("public")); target.setAddress(address); target.setTimeout(10000);//10s target.setVersion(SnmpConstants.version2c); //create pdu PDU pduSet = createSetPdu(); PDU pudGet = createGetPdu(); sendPdu(pudGet, target); sendPdu(pduSet, target); sendPdu(pudGet, target); } //1.3.6.1.2.1.1.5.0 sysName //create set pdu public static PDU createSetPdu(){ PDU pduReturn = new PDU(); pduReturn.setType(PDU.SET); VariableBinding variable = new VariableBinding(new OID("1.3.6.1.2.1.1.5.0"), new OctetString("testname")); pduReturn.add(variable); return pduReturn; } //create get pdu public static PDU createGetPdu(){ PDU pduReturn = new PDU(); pduReturn.setType(PDU.GET); VariableBinding variableBinding = new VariableBinding(new OID("1.3.6.1.2.1.1.5.0")); pduReturn.add(variableBinding); return pduReturn; } //send pdu public static void sendPdu(PDU pdu, CommunityTarget communityTarget){ try { TransportMapping transportMapping = new DefaultUdpTransportMapping(); transportMapping.listen(); Snmp snmp = new Snmp(transportMapping); ResponseEvent responseEvent = snmp.send(pdu, communityTarget); //get reponse pdu if(null != responseEvent){ PDU pduResponse = responseEvent.getResponse(); System.out.println("size : " + pduResponse.size()); for(int i = 0; i < pduResponse.size(); i++){ VariableBinding variableBinding = pduResponse.get(i); Variable variable = variableBinding.getVariable(); System.out.println(variable.toString()); } System.out.println("error:" + pduResponse.getErrorStatusText()); } else{ System.out.println("timeout ..."); } } catch (IOException e) { e.printStackTrace(); System.out.println(e.getMessage()); } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。