import java.io.IOException; 
import java.net.InetAddress; 
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 test3{     public static void main(String[] args) 
    { 
       try { 
          Snmp snmp = new Snmp(new DefaultUdpTransportMapping()); 
          CommunityTarget target = new CommunityTarget();//agent对象 
           target.setCommunity(new OctetString("public"));//设置共同体名,
          target.setVersion(SnmpConstants.version2c);//设置版本 
           target.setAddress(new UdpAddress("127.0.0.1/161"));//设置IP地址和端口号
          target.setRetries(1); //设置重传次数 
           target.setTimeout(5000); //设置超时 
           snmp.listen(); //监听 
           PDU request= new PDU(); //new request PDU包 
         request.setType(PDU.GET); //设置PDU类型, 
          request.add(new VariableBinding(new OID(".1.3.6.1.2.1.1.1.0"))); //OID添加 
         System.out.println("request UDP:" + request);//请求包内内容输出, 
         PDU response = null;//定义response包 
////////////////////////////////////////////////////////////
           ResponseEvent responseEvent = snmp.send(request, target); //发出request PDU 
////////////////////////////////////////////////////////////
         //接收response PDU 
         response = responseEvent.getResponse();          //response PDU包解析 
           if(response!=null){ 
            if(response.getErrorIndex()==response.noError&&response.getErrorStatus()==response.noError){ 
                System.out.println("no error."); 
                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); 
                System.out.println(response); 
          }else{ 
              System.out.println("get error:"+response.getErrorStatusText()); 
          } 
       }else{ 
             System.out.println("get response error"); 
       } 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } 
  } 
} 这是发送请求的代码,我想在Agent 方接收和相应并返回一下PDU
ResponseEvent responseEvent = snmp.send(request, target); 
为什么responseEvent.getResponse() //返回的是null
在agent 的代码那位大侠有  传一份  谢谢

解决方案 »

  1.   

    import java.io.File;
    import java.io.IOException;
    import org.snmp4j.agent.agentx.master.AgentXMasterAgent;
    import org.snmp4j.mp.MessageProcessingModel;
    import org.snmp4j.security.AuthSHA;
    import org.snmp4j.security.UsmUser;
    import org.snmp4j.security.SecurityLevel;
    import org.snmp4j.agent.mo.snmp.SnmpNotificationMIB;
    import org.snmp4j.smi.OID;
    import org.snmp4j.agent.mo.snmp.StorageType;
    import org.snmp4j.agent.mo.snmp.SnmpTargetMIB;
    import org.snmp4j.smi.UdpAddress;
    import org.snmp4j.smi.OctetString;
    import org.snmp4j.security.SecurityModel;
    import org.snmp4j.security.PrivDES;
    import org.snmp4j.security.USM;
    import org.snmp4j.agent.mo.snmp.VacmMIB;
    import org.snmp4j.agent.mo.snmp.TransportDomains;
    import org.snmp4j.TransportMapping;
    import org.snmp4j.transport.DefaultTcpTransportMapping;
    import org.snmp4j.smi.TcpAddress;
    import org.snmp4j.smi.Variable;
    import org.snmp4j.agent.mo.MOTableRow;
    import org.snmp4j.agent.mo.snmp.RowStatus;
    import org.snmp4j.agent.mo.snmp.SnmpCommunityMIB;
    import org.snmp4j.smi.Integer32;
    import org.snmp4j.log.LogFactory;
    import java.util.Map;
    import org.snmp4j.agent.io.DefaultMOPersistenceProvider;
    import org.snmp4j.mp.MPv3;
    import org.snmp4j.agent.cfg.EngineBootsCounterFile;
    import org.snmp4j.agent.MOServer;
    import org.snmp4j.MessageDispatcher;
    import org.snmp4j.util.ThreadPool;
    import org.snmp4j.agent.DefaultMOServer;
    import java.util.List;
    import org.snmp4j.MessageDispatcherImpl;
    import java.util.Iterator;
    import org.snmp4j.smi.Address;
    import org.snmp4j.smi.GenericAddress;
    import org.snmp4j.transport.TransportMappings;
    import org.snmp4j.log.JavaLogFactory;
    import org.snmp4j.log.LogAdapter;
    import org.snmp4j.util.ArgumentParser;public class TestMasterAgent {
    static {
    LogFactory.setLogFactory(new JavaLogFactory());
    } public static LogAdapter logger = LogFactory
    .getLogger(TestMasterAgent.class); protected String address;
    protected TransportMapping masterTransport; protected AgentXMasterAgent agent;
    protected MOServer server;
    private String configFile;
    private File bootCounterFile; public TestMasterAgent(Map args) throws IOException {
    configFile = (String) ((List) args.get("c")).get(0);
    bootCounterFile = new File((String) ((List) args.get("bc")).get(0)); server = new DefaultMOServer();
    MOServer[] moServers = new MOServer[] { server };
    MessageDispatcher messageDispatcher = new MessageDispatcherImpl();
    addListenAddresses(messageDispatcher, (List) args.get("address"));
    agent = new AgentXMasterAgent(new OctetString(MPv3
    .createLocalEngineID()), messageDispatcher, null, moServers,
    ThreadPool.create("SampleAgent", 3),
    null, // by config file: configurationFactory,
    new DefaultMOPersistenceProvider(moServers, configFile),
    new EngineBootsCounterFile(bootCounterFile)) {
    public void configure() {
    super.configure();
    addCommunities(communityMIB);
    addUsmUser(usm);
    addNotificationTargets(targetMIB, notificationMIB);
    addViews(vacmMIB);
    }
    };
    } protected void addListenAddresses(MessageDispatcher md, List addresses) {
    for (Iterator it = addresses.iterator(); it.hasNext();) {
    Address address = GenericAddress.parse((String) it.next());
    TransportMapping tm = TransportMappings.getInstance()
    .createTransportMapping(address);
    if (tm != null) {
    md.addTransportMapping(tm);
    } else {
    logger.warn("No transport mapping available for address '"
    + address + "'.");
    }
    }
    } protected void addNotificationTargets(SnmpTargetMIB targetMIB,
    SnmpNotificationMIB notificationMIB) {
    targetMIB.addDefaultTDomains(); targetMIB.addTargetAddress(new OctetString("notification"),
    TransportDomains.transportDomainUdpIpv4, new OctetString(
    new UdpAddress("127.0.0.1/162").getValue()), 200, 1,
    new OctetString("notify"), new OctetString("v2c"),
    StorageType.permanent);
    targetMIB.addTargetParams(new OctetString("v2c"),
    MessageProcessingModel.MPv2c,
    SecurityModel.SECURITY_MODEL_SNMPv2c,
    new OctetString("public"), SecurityLevel.NOAUTH_NOPRIV,
    StorageType.permanent);
    notificationMIB.addNotifyEntry(new OctetString("default"),
    new OctetString("notify"),
    SnmpNotificationMIB.SnmpNotifyTypeEnum.trap,
    StorageType.permanent);
    }
      

  2.   


    protected void addViews(VacmMIB vacm) {
    vacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv1, new OctetString(
    "public"), new OctetString("v1v2group"),
    StorageType.nonVolatile);
    vacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv2c, new OctetString(
    "public"), new OctetString("v1v2group"),
    StorageType.nonVolatile);
    vacm.addGroup(SecurityModel.SECURITY_MODEL_USM, new OctetString(
    "SHADES"), new OctetString("v3group"), StorageType.nonVolatile);
    vacm.addGroup(SecurityModel.SECURITY_MODEL_USM,
    new OctetString("TEST"), new OctetString("v3test"),
    StorageType.nonVolatile);
    vacm.addGroup(SecurityModel.SECURITY_MODEL_USM, new OctetString("SHA"),
    new OctetString("v3restricted"), StorageType.nonVolatile); vacm.addAccess(new OctetString("v1v2group"), new OctetString(),
    SecurityModel.SECURITY_MODEL_ANY, SecurityLevel.NOAUTH_NOPRIV,
    VacmMIB.vacmExactMatch, new OctetString("fullReadView"),
    new OctetString("fullWriteView"), new OctetString(
    "fullNotifyView"), StorageType.nonVolatile);
    vacm.addAccess(new OctetString("v3group"), new OctetString(),
    SecurityModel.SECURITY_MODEL_USM, SecurityLevel.AUTH_PRIV,
    VacmMIB.vacmExactMatch, new OctetString("fullReadView"),
    new OctetString("fullWriteView"), new OctetString(
    "fullNotifyView"), StorageType.nonVolatile);
    vacm.addAccess(new OctetString("v3restricted"), new OctetString(),
    SecurityModel.SECURITY_MODEL_USM, SecurityLevel.AUTH_NOPRIV,
    VacmMIB.vacmExactMatch, new OctetString("restrictedReadView"),
    new OctetString("restrictedWriteView"), new OctetString(
    "restrictedNotifyView"), StorageType.nonVolatile);
    vacm.addAccess(new OctetString("v3test"), new OctetString(),
    SecurityModel.SECURITY_MODEL_USM, SecurityLevel.AUTH_PRIV,
    VacmMIB.vacmExactMatch, new OctetString("testReadView"),
    new OctetString("testWriteView"), new OctetString(
    "testNotifyView"), StorageType.nonVolatile); vacm.addViewTreeFamily(new OctetString("fullReadView"), new OID("1.3"),
    new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile);
    vacm.addViewTreeFamily(new OctetString("fullWriteView"),
    new OID("1.3"), new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile);
    vacm.addViewTreeFamily(new OctetString("fullNotifyView"),
    new OID("1.3"), new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile); vacm.addViewTreeFamily(new OctetString("restrictedReadView"), new OID(
    "1.3.6.1.2"), new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile);
    vacm.addViewTreeFamily(new OctetString("restrictedWriteView"), new OID(
    "1.3.6.1.2.1"), new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile);
    vacm.addViewTreeFamily(new OctetString("restrictedNotifyView"),
    new OID("1.3.6.1.2"), new OctetString(),
    VacmMIB.vacmViewIncluded, StorageType.nonVolatile); vacm.addViewTreeFamily(new OctetString("testReadView"), new OID(
    "1.3.6.1.2"), new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile);
    vacm.addViewTreeFamily(new OctetString("testReadView"), new OID(
    "1.3.6.1.2.1.1"), new OctetString(), VacmMIB.vacmViewExcluded,
    StorageType.nonVolatile);
    vacm.addViewTreeFamily(new OctetString("testWriteView"), new OID(
    "1.3.6.1.2.1"), new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile);
    vacm.addViewTreeFamily(new OctetString("testNotifyView"), new OID(
    "1.3.6.1.2"), new OctetString(), VacmMIB.vacmViewIncluded,
    StorageType.nonVolatile); }
      

  3.   


    protected void addCommunities(SnmpCommunityMIB communityMIB) {
    Variable[] com2sec = new Variable[] { new OctetString("public"), // community
    // name
    new OctetString("private"), // security name
    agent.getLocalEngineID(), // local engine ID
    new OctetString(), // default context name
    new OctetString(), // transport tag
    new Integer32(StorageType.nonVolatile), // storage type
    new Integer32(RowStatus.active) // row status
    };
    MOTableRow row = communityMIB.getSnmpCommunityEntry().createRow(
    new OctetString("public2public").toSubIndex(true), com2sec);
    communityMIB.getSnmpCommunityEntry().addRow(row);
    } protected void addUsmUser(USM usm) {
    UsmUser user = new UsmUser(new OctetString("SHADES"), AuthSHA.ID,
    new OctetString("SHADESAuthPassword"), PrivDES.ID,
    new OctetString("SHADESPrivPassword"));
    usm.addUser(user.getSecurityName(), usm.getLocalEngineID(), user);
    user = new UsmUser(new OctetString("TEST"), AuthSHA.ID,
    new OctetString("maplesyrup"), PrivDES.ID, new OctetString(
    "maplesyrup"));
    usm.addUser(user.getSecurityName(), usm.getLocalEngineID(), user);
    user = new UsmUser(new OctetString("SHA"), AuthSHA.ID, new OctetString(
    "SHAAuthPassword"), null, null);
    usm.addUser(user.getSecurityName(), usm.getLocalEngineID(), user);
    } public static void main(String[] args) {
    // -c ss.txt -X tcp:localhost/705 tcp:127.0.0.1/161
    ArgumentParser parser = new ArgumentParser(
    "-c[s{=SampleAgent.cfg}] -bc[s{=SampleAgent.bc}] "
    + "-X[s{=tcp:0.0.0.0/705}<tcp:.*[/[0-9]+]?>] +h +v",
    "#address[s<(udp|tcp):.*[/[0-9]+]?>] ..");
    Map commandLineParameters = null;
    try {
    commandLineParameters = parser.parse(args);
    if (commandLineParameters.containsKey("h")) {
    printUsage();
    System.exit(0);
    }
    if (commandLineParameters.containsKey("v")) {
    System.out.println("Options: " + commandLineParameters);
    }
    TestMasterAgent sampleAgent = new TestMasterAgent(
    commandLineParameters);
    String agentXAddress = ((String) ((List) commandLineParameters
    .get("X")).get(0)).substring(4);
    sampleAgent.agent
    .addAgentXTransportMapping(new DefaultTcpTransportMapping(
    new TcpAddress(agentXAddress)));
    sampleAgent.agent.run();
    while (true) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException ex1) {
    break;
    }
    }
    } catch (ArgumentParser.ArgumentParseException ax) {
    printUsage();
    System.out.println(ax.getMessage());
    } catch (Exception ex) {
    logger.fatal("Caught exception while starting the agent", ex);
    ex.printStackTrace();
    }
    } static void printUsage() {
    String[] txt = {
    "Usage: TestMasterAgent [-c <config-file>] [-bc <boot-counter-file>] [-h] [-v]",
    "                       [-X <masterAddress>] <address1> [<address2> ..]",
    "",
    "where ",
    "  <config-file>        is the file where persistent MIB data is stored/read.",
    "  <boot-counter-file>  is the file to store the SNMPv3 boot counter.",
    "  -h                   prints this usage help information and exit.",
    "  -v                   print command line parameters.",
    "  <masterAddress>      is the TCP AgentX master agent address of the local",
    "                       host following the format 'tcp:<host>/<port>'.",
    "  <address>            a listen address following the format ",
    "                       'udp|tcp:<host>/<port>', for example udp:0.0.0.0/161",
    "" };
    for (int i = 0; i < txt.length; i++) {
    System.out.println(txt[i]);
    }
    }
    }
      

  4.   

    ResponseEvent responseEvent = snmp.send(request, target); //发出request PDU 获得的一个PDU :responseEvent.getResponse();   获得的是Null吗 ??
    直接运行就行吗?  不过看起来好复杂啊?代码好多,能不能简化一下。
      

  5.   

    ArgumentParser parser = new ArgumentParser(
                    "-c[s{=SampleAgent.cfg}] -bc[s{=SampleAgent.bc}] "
                            + "-X[s{=tcp:0.0.0.0/705}<tcp:.*[/[0-9]+]?>] +h +v",
                    "#address[s<(udp|tcp):.*[/[0-9]+]?>] ..");
    不知道这匹配的是什么东西?
    然后一直在  commandLineParameters = parser.parse(args);  这一行出现异常后直接打
    印printUsage()  这个方法里面的东西!!
    在看看  谢谢了大哥!!!
      

  6.   

    我也看不懂啊,直接运行有错误,怎么弄啊
    Mandatory parameter -address1 not specified