2011-07-26 56 views
2

我一直在做一些非常基本的SNMP4J编程。我想要做的只是发送一个简单的“获取”请求,但到目前为止,我的回复为空。我打开wireshark,发现在简单网络管理协议下,我的msgUserName是空白的,我需要填充它。SNMP4J添加用户

我以为我已经使用下面的代码设置:

Snmp snmp = new Snmp(transport); 
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); 
SecurityModels.getInstance().addSecurityModel(usm); 
transport.listen(); 

UsmUser user = new UsmUser(new OctetString("SNMPManager"), AuthSHA.ID,new OctetString("password"),null,null); 
// add user to the USM 
snmp.getUSM().addUser(user.getSecurityName(), user); 

我要对错误的方式?如果没有,我如何设置msgUserName在我的wireshark转储的get-request中看到?我对SNMP非常陌生,所以我基本上运行了一些示例。

回答

4

这是一个工作的snmpset,你可以用snmp写同样的方法.Snmp4j v2和v3不使用相同的api类。

private void snmpSetV3(VariableBinding[] bindings) throws TimeOutException, OperationFailed { 
     Snmp snmp = null; 
     try { 
      PDU pdu = new ScopedPDU(); 
      USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); 
      SecurityModels.getInstance().addSecurityModel(usm); 
      snmp = new Snmp(new DefaultUdpTransportMapping()); 
      snmp.getUSM().addUser(new OctetString(Username), new UsmUser(new OctetString(Username), AuthMD5.ID, new OctetString(Password), AuthMD5.ID, null)); 


      ScopedPDU scopedPDU = (ScopedPDU) pdu; 
      scopedPDU.setType(PDU.SET); 
      scopedPDU.addAll(bindings); 
      UserTarget target = new UserTarget(); 
      target.setAddress(new UdpAddress(IPAddress + "/" + Port)); 
      target.setVersion(version); //SnmpConstants.version3 
      target.setRetries(retries); 
      target.setTimeout(timeout); 
      target.setSecurityLevel(securityLevel); //SecurityLevel.AUTH_NOPRIV 
      target.setSecurityName(new OctetString(Username)); 
      snmp.listen(); 
      ResponseEvent response = snmp.send(pdu, target); 
      if (response.getResponse() != null) { 
       PDU responsePDU = response.getResponse(); 
       if (responsePDU != null) { 
        if (responsePDU.getErrorStatus() == PDU.noError) { 
         return; 
        } 
        throw new OperationFailed("Error: Request Failed, " 
          + "Error Status = " + responsePDU.getErrorStatus() 
          + ", Error Index = " + responsePDU.getErrorIndex() 
          + ", Error Status Text = " + responsePDU.getErrorStatusText()); 
       } 
      } 
      throw new TimeOutException("Error: Agent Timeout... "); 
     } catch (IOException e) { 
      throw new OperationFailed(e.getMessage(), e); 

     } finally { 
      if (snmp != null) { 
       try { 
        snmp.close(); 
       } catch (IOException ex) { 
        _logger.error(ex.getMessage(), ex); 
       } 
      } 
     } 


    } 
+0

我设法让它工作。原来这实际上是一个超时问题。 – Otra