Update PySNMP (Slim is now deprecated)
This commit is contained in:
43
snmp2mqtt.py
43
snmp2mqtt.py
@@ -1,7 +1,9 @@
|
||||
#!/bin/env python3
|
||||
import asyncio
|
||||
from pysnmp.hlapi.asyncio.slim import Slim
|
||||
from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType
|
||||
from pysnmp.hlapi.asyncio import (
|
||||
get_cmd, CommunityData, UdpTransportTarget, ContextData,
|
||||
SnmpEngine, ObjectIdentity, ObjectType
|
||||
)
|
||||
import logging
|
||||
import random
|
||||
from paho.mqtt import client as mqtt_client
|
||||
@@ -204,25 +206,34 @@ def publish(topic, client, data, retain, qos):
|
||||
|
||||
|
||||
async def get_snmp(req):
|
||||
"""Asynchronously retrieve SNMP data from device using new pysnmp API"""
|
||||
data = {}
|
||||
|
||||
# Create SNMP engine and transport target
|
||||
snmpEngine = SnmpEngine()
|
||||
authData = CommunityData(req["snmp_community"])
|
||||
transportTarget = UdpTransportTarget((req["ip"], 161))
|
||||
contextData = ContextData()
|
||||
|
||||
for oid in req["oids"]:
|
||||
with Slim(1) as slim:
|
||||
errorIndication, errorStatus, errorIndex, varBinds = await slim.get(
|
||||
req["snmp_community"],
|
||||
req["ip"],
|
||||
161,
|
||||
ObjectType(ObjectIdentity(oid["oid"])),
|
||||
try:
|
||||
# Perform async SNMP GET operation
|
||||
errorIndication, errorStatus, errorIndex, varBinds = await get_cmd(
|
||||
snmpEngine,
|
||||
authData,
|
||||
transportTarget,
|
||||
contextData,
|
||||
ObjectType(ObjectIdentity(oid["oid"]))
|
||||
)
|
||||
|
||||
if errorIndication:
|
||||
logging.error(errorIndication)
|
||||
logging.error(f"{req['device_name']} SNMP error indication: {errorIndication}")
|
||||
continue
|
||||
elif errorStatus:
|
||||
logging.error(
|
||||
"{} at {}".format(
|
||||
errorStatus.prettyPrint(),
|
||||
errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
|
||||
)
|
||||
f"{req['device_name']} SNMP error status: {errorStatus.prettyPrint()} at {errorIndex and varBinds[int(errorIndex) - 1][0] or '?'}"
|
||||
)
|
||||
continue
|
||||
else:
|
||||
for varBind in varBinds:
|
||||
logging.debug(f"{req['device_name']} {oid['name']} => {oid['type'](varBind[1])}")
|
||||
@@ -233,7 +244,11 @@ async def get_snmp(req):
|
||||
data.update({oid["name"]: "OFF"})
|
||||
else:
|
||||
data.update({oid["name"]: oid["type"](varBind[1])})
|
||||
logging.debug(f"JSON : {json.dumps(data)}")
|
||||
except Exception as e:
|
||||
logging.error(f"{req['device_name']} Exception getting OID {oid['oid']}: {e}")
|
||||
continue
|
||||
|
||||
logging.debug(f"{req['device_name']} JSON : {json.dumps(data)}")
|
||||
return data
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user