Network health monitoring script with MQTT reporting for Home Assistant. - Ping, HTTP, and SNMP checkers - MQTT Discovery for automatic entity creation - Configurable check intervals Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
import time
|
|
|
|
from pysnmp.hlapi import (
|
|
SnmpEngine,
|
|
CommunityData,
|
|
UdpTransportTarget,
|
|
ContextData,
|
|
ObjectType,
|
|
ObjectIdentity,
|
|
getCmd,
|
|
)
|
|
|
|
from .base import BaseChecker, CheckResult
|
|
|
|
|
|
class SnmpChecker(BaseChecker):
|
|
def check(self) -> CheckResult:
|
|
host = self.config["host"]
|
|
port = self.config.get("port", 161)
|
|
community = self.config.get("community", "public")
|
|
oid = self.config.get("oid", "1.3.6.1.2.1.1.1.0") # sysDescr
|
|
timeout_val = self.config.get("timeout", 5)
|
|
|
|
start = time.time()
|
|
try:
|
|
iterator = getCmd(
|
|
SnmpEngine(),
|
|
CommunityData(community),
|
|
UdpTransportTarget((host, port), timeout=timeout_val, retries=1),
|
|
ContextData(),
|
|
ObjectType(ObjectIdentity(oid))
|
|
)
|
|
|
|
error_indication, error_status, error_index, var_binds = next(iterator)
|
|
response_time = (time.time() - start) * 1000 # ms
|
|
|
|
if error_indication:
|
|
return CheckResult(
|
|
success=False,
|
|
message=f"SNMP error: {error_indication}",
|
|
response_time=None
|
|
)
|
|
elif error_status:
|
|
return CheckResult(
|
|
success=False,
|
|
message=f"SNMP error: {error_status.prettyPrint()}",
|
|
response_time=None
|
|
)
|
|
else:
|
|
values = {str(oid): str(val) for oid, val in var_binds}
|
|
return CheckResult(
|
|
success=True,
|
|
message="SNMP response OK",
|
|
response_time=response_time,
|
|
details=values
|
|
)
|
|
except Exception as e:
|
|
return CheckResult(
|
|
success=False,
|
|
message=f"SNMP error: {e}",
|
|
response_time=None
|
|
)
|