资源描述:
《java实现snmp的get和walk代码示例》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、依赖于第三方SNMP4j来实现snmp的get、walk功能,主要实现了如下功能:目录一、snmpget获取单个OID的值二、snmpget同步和异步的方式获取多个OID的值三、snmpwalk的方式四、补充SnmpUtil.java代码[一]、snmpget获取单个OID的值SnmpGet.javaJava代码packagecom.michael.snmp4j;importjava.io.IOException;importjava.util.Vector;importorg.snmp4j.CommunityTarget;impo
2、rtorg.snmp4j.PDU;importorg.snmp4j.Snmp;importorg.snmp4j.event.ResponseEvent;importorg.snmp4j.mp.SnmpConstants;importorg.snmp4j.smi.OID;importorg.snmp4j.smi.VariableBinding;importorg.snmp4j.transport.DefaultUdpTransportMapping;importcom.michael.snmp4j.util.SnmpUtil;/***
3、@seehttp://sjsky.iteye.com*@authorMichael*/publicclassSnmpGet{privatestaticintversion=SnmpConstants.version1;privatestaticStringprotocol="udp";privatestaticintport=161;/****@paramargs*/publicstaticvoidmain(String[]args){Stringip="192.168.8.254";Stringcommunity="public"
4、;Stringoidval="1.3.6.1.2.1.1.3.0";SnmpGettester=newSnmpGet();tester.snmpGet(ip,community,oidval);}@SuppressWarnings("unchecked")privatevoidsnmpGet(Stringip,Stringcommunity,Stringoid){Stringaddress=protocol+":"+ip+"/"+port;CommunityTargettarget=SnmpUtil.createCommunityT
5、arget(address,community,version,2*1000L,3);DefaultUdpTransportMappingudpTransportMapping=null;Snmpsnmp=null;try{PDUpdu=newPDU();//pdu.add(newVariableBinding(newOID(newint[]//{1,3,6,1,2,1,1,2})));pdu.add(newVariableBinding(newOID(oid)));pdu.setType(PDU.GET);udpTransport
6、Mapping=newDefaultUdpTransportMapping();udpTransportMapping.listen();snmp=newSnmp(udpTransportMapping);//发送同步消息ResponseEventresponse=snmp.send(pdu,target);System.out.println("PeerAddress:"+response.getPeerAddress());PDUresponsePdu=response.getResponse();if(responsePdu=
7、=null){System.out.println(ip+":Requesttimeout");}else{VectorvbVect=responsePdu.getVariableBindings();System.out.println("vbsize:"+vbVect.size());if(vbVect.size()==0){System.out.println("pduvbsizeis0");}else{Objectobj=vbVect.firstElement();VariableBindingvb=(VariableBin
8、ding)obj;System.out.println(vb.getOid()+"="+vb.getVariable());}}System.out.println("successfinishsnmpgettheoid!");}ca