上面代码并没有收到snmp消息
时间: 2023-12-26 07:39:52 浏览: 198
抱歉,我给出的示例代码可能没有完全满足你的需求。在接收SNMP消息之前,你需要先设置SNMP引擎并定义处理接收到消息的函数。以下是一个更新的示例代码,可以帮助你实现SNMP v1、v2和v3消息的监听:
```python
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import ntfrcv
from pysnmp.proto.api import v2c
def snmp_listener():
# SNMP v1/v2c community name
community_name = 'public'
# SNMP v3 user credentials
username = 'username'
auth_key = 'authkey'
priv_key = 'privkey'
# Create SNMP engine
snmp_engine = engine.SnmpEngine()
# SNMP v1/v2c setup
config.addV1System(snmp_engine, 'my-area', community_name)
config.addTargetParams(snmp_engine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
# SNMP v3 setup
config.addV3User(snmp_engine, username,
config.usmHMACMD5AuthProtocol, auth_key,
config.usmDESPrivProtocol, priv_key)
config.addTargetParams(snmp_engine, 'my-creds', username, 'authPriv', 1)
# SNMP trap receiver
def trap_receiver(snmp_engine):
ntfrcv.NotificationReceiver(snmp_engine, handle_trap)
snmp_engine.transportDispatcher.jobStarted(1)
try:
snmp_engine.transportDispatcher.runDispatcher()
except Exception:
snmp_engine.transportDispatcher.closeDispatcher()
raise
# Handle received trap
def handle_trap(snmp_engine, state_reference, context_engine_id, context_name, var_binds, cb_ctx):
for var_bind in var_binds:
oid = var_bind[0]
value = var_bind[1]
print(f'Object type: {oid}, value: {value}')
# Start the listener
trap_receiver(snmp_engine)
snmp_listener()
```
这个示例代码会监听SNMP v1、v2和v3的消息,并通过`handle_trap`函数处理接收到的消息。你可以根据实际需求修改代码中的参数和处理逻辑。请确保你的系统上已经安装了pysnmp库,并且根据需要修改SNMP引擎的配置。
阅读全文