如何使用snmp4j

时间:2016-06-05 06:54:24

标签: java snmp snmp4j

我试图创建snmp管理器和代理的简单示例。 我需要做的就是从给定的OID中读取当前值,写一些新值来替换它,并将其读回。

我的get函数运行良好,但我的设置没有。 在行中:PDU responsePDU = event.getResponse(); responsePDU等于null,我不明白为什么? 我们非常欢迎任何帮助!

    public ResponseEvent set(OID oid,String val) throws IOException 
{
    PDU pdu = new PDU();
    VariableBinding varBind = new VariableBinding(oid,new OctetString(val));
    pdu.add(varBind);
    pdu.setType(PDU.SET);
    pdu.setRequestID(new Integer32(1));
    Target target=getTargetForWrite();

    ResponseEvent event = snmp.set(pdu, target);
    if(event != null)
    {
      System.out.println("\nResponse:\nGot Snmp Set Response from Agent");
      System.out.println("Snmp Set Request = " + event.getRequest().getVariableBindings());
      PDU responsePDU = event.getResponse();
      System.out.println("\nresponsePDU = "+responsePDU);
      if (responsePDU != null)
      {
        int errorStatus = responsePDU.getErrorStatus();
        int errorIndex = responsePDU.getErrorIndex();
        String errorStatusText = responsePDU.getErrorStatusText();
        System.out.println("\nresponsePDU = "+responsePDU);
        if (errorStatus == PDU.noError)
        {
          System.out.println("Snmp Set Response = " + responsePDU.getVariableBindings());
        }
        else
        {
          System.out.println("errorStatus = "+responsePDU);
          System.out.println("Error: Request Failed");
          System.out.println("Error Status = " + errorStatus);
          System.out.println("Error Index = " + errorIndex);
          System.out.println("Error Status Text = " + errorStatusText);
        }
       }

      return event;
    }
    throw new RuntimeException("GET timed out");
}



    private Target getTargetForWrite()
{
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("private"));
    target.setVersion(SnmpConstants.version2c);
    target.setAddress(GenericAddress.parse(address));
    target.setRetries(2);
    target.setTimeout(1500);

    return target;
}

1 个答案:

答案 0 :(得分:0)

需要将社区设置为公共

private Target getTargetForWrite()
{
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));\\<--- 
    target.setVersion(SnmpConstants.version2c);
    target.setAddress(GenericAddress.parse(address));
    target.setRetries(2);
    target.setTimeout(1500);

    return target;
}