2

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

我以为我已经使用以下代码设置了它:

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 转储中看到的那样?我对 SNMP 很陌生,所以我基本上是在运行示例。

4

1 回答 1

4

这是一个有效的 snmpset,您可以使用相同的方式编写 snmp get。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);
                }
            }
        }


    }
于 2011-08-17T19:34:41.773 回答