SNMP4j.java
资源名称:SNMP4j.rar [点击查看]
上传用户:weishen1
上传日期:2021-09-15
资源大小:1k
文件大小:3k
源码类别:
SNMP编程
开发平台:
Java
- package com.ultrapower.cruiser.snmp;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Hashtable;
- import java.util.List;
- import javax.management.ObjectName;
- 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.OctetString;
- import org.snmp4j.smi.UdpAddress;
- import org.snmp4j.smi.VariableBinding;
- import org.snmp4j.transport.DefaultUdpTransportMapping;
- public class SNMP4j{
- public static String connectSnmpServer(int port, String hostname,
- String community,String oid_) {
- try {
- Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
- CommunityTarget target = new CommunityTarget();// agent对象
- target.setCommunity(new OctetString(community));// 设置共同体名,没发现设置RWCommnity的方法,大概只能设一个.
- target.setVersion(SnmpConstants.version1);// 设置版本
- target.setAddress(new UdpAddress(hostname+"/"+port));// 设置IP地址和端口号,这里竟然用'/'来分隔,当初确实没有料到,JDOC的说明等于没有.
- target.setRetries(1); // 设置重试次数
- target.setTimeout(5000); // 设置超时
- snmp.listen(); // 监听
- String m_oid =oid_;
- // set pud type and set oid
- PDU request = new PDU(); // new request PDU包
- request.setType(PDU.GETNEXT); // 设置PDU类型,
- request.add(new VariableBinding(new OID(m_oid)));
- PDU response = null;// 定义response包
- ResponseEvent responseEvent = snmp.send(request, target); // 发出request
- // PDU
- // 接收response PDU
- response = responseEvent.getResponse();
- // response PDU包解析
- if (response != null) {
- System.out.println("response : " + response.toString());
- if (response.getErrorIndex() == response.noError
- && response.getErrorStatus() == response.noError) {
- String pause = responseEvent.getResponse()
- .getVariableBindings().toString();
- String getvalue = pause.substring(
- pause.indexOf("= ") + 2, pause.indexOf(']'));
- String oid = pause.substring(pause.indexOf("VBS[") + 2,
- pause.indexOf("=") - 1);
- System.out.println("oid : " + oid);
- System.out.println(getvalue);
- return getvalue;
- } else {
- System.out.println("get error:"
- + response.getErrorStatusText());
- }
- } else {
- System.out.println("get response error");
- }
- snmp.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- public static void main(String s[]){
- SNMP4j snmp = new SNMP4j();
- String ss = snmp.connectSnmpServer(161,"192.168.5.122","public",".1.3.6.1.4.1.140.625.10.1");
- // String ss = snmp.connectSnmpServer(161,"192.168.0.181","public",".1.3.6.1.4.1.9.2.1.59");
- System.out.println("the ss is ; "+ss);
- SnmpTool smt = new SnmpTool();
- smt.setPduType(PDU.GETNEXT);
- System.out.println(smt.getMibValue(161,"public","192.168.5.122",".1.3.6.1.4.1.140.625.105.1.5"));
- }
- }