我一直在做一些非常基本的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);
我是以错误的方式去做的吗?如果没有,我如何设置在get-request的wireshark转储中看到的msgUserName?我是SNMP的新手,所以我实际上是在运行示例。
答案 0 :(得分: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);
}
}
}
}