snmp_notifier.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import time
  2. import socket
  3. from pysnmp.hlapi import *
  4. class SNMPNotifier:
  5. def __init__(self, target_host='192.168.130.170', target_port=162):
  6. self.target_host = target_host
  7. self.target_port = target_port
  8. self.user = 'zabbix_snmp'
  9. self.auth_key = 'authkey123'
  10. self.priv_key = 'privkey123'
  11. def send_alert(self, message):
  12. try:
  13. errorIndication, errorStatus, errorIndex, varBinds = next(
  14. sendNotification(
  15. SnmpEngine(),
  16. UsmUserData(self.user, self.auth_key, self.priv_key,
  17. authProtocol=usmHMACSHAAuthProtocol,
  18. privProtocol=usmAesCfb128Protocol),
  19. UdpTransportTarget((self.target_host, self.target_port)),
  20. ContextData(),
  21. 'trap',
  22. NotificationType(
  23. ObjectIdentity('1.3.6.1.4.1.8072.3.2.10') # SNMP trap OID
  24. ).addVarBinds(
  25. ('1.3.6.1.2.1.1.1.0', OctetString(f"[{socket.gethostname()}] {message}"))
  26. )
  27. )
  28. )
  29. if errorIndication:
  30. print(f"SNMP Trap Failed: {errorIndication}")
  31. except Exception as e:
  32. print(f"Failed to send SNMPv3 trap: {e}")
  33. # Singleton instance
  34. notifier = SNMPNotifier()