snmp4j获取数据实例

 

import  java.io.IOException;
import  java.net.InetAddress;
import  java.util.Vector;
import  org.snmp4j.AbstractTarget;
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.UdpAddress;
import  org.snmp4j.smi.VariableBinding;
import  org.snmp4j.transport.DefaultUdpTransportMapping;

public   class  SNMP_oper
{
    
    
public static void main(String[] args)
    
{
        
try
        
{
            Address targetAddress 
= GenericAddress.parse("udp:127.0.0.1/161");
            TransportMapping transport 
= new DefaultUdpTransportMapping();
            Snmp snmp 
= new Snmp(transport);
            transport.listen();
//监听
            
            
            CommunityTarget target 
= new CommunityTarget();
            target.setCommunity(
new OctetString("public"));//设置共同体名
            target.setAddress(targetAddress);//设置目标Agent地址
            target.setRetries(2);//重试次数
            target.setTimeout(5000);//超时设置
            target.setVersion(1);//版本
            
            PDU request 
= new PDU();
            request.setType(PDU.GET);
//操作类型GET
            request.add(new VariableBinding(new OID(".1.3.6.1.2.1.1.1.0")));//OID_sysDescr
            request.add(new VariableBinding(new OID(".1.3.6.1.2.1.1.2.0")));//OID_sysObjectID
            request.add(new VariableBinding(new OID(".1.3.6.1.2.1.1.3.0")));//OID_sysUpTime

            System.out.println(
"Request UDP:" + request);
            
            ResponseEvent respEvt 
= snmp.send(request, target);
            
            
//读取得到的绑定变量
            if (respEvt != null && respEvt.getResponse()!=null)
            
{
                Vector 
<VariableBinding> revBindings = respEvt.getResponse().getVariableBindings();
                
for (int i=0; i<revBindings.size();i++)
                
{
                    VariableBinding vbs 
= revBindings.elementAt(i);
                    System.out.println(vbs.getOid()
+":"+vbs.getVariable());
                }

            }


        }

        
catch (IOException e)
        
{
            e.printStackTrace();
        }

    }

}

你可能感兴趣的:(snmp4j获取数据实例)