from pysnmp.hlapi import *
from prtg.sensor.result import CustomSensorResult
from prtg.sensor.units import ValueUnit
import sys
import re
import json
prtg_params = json.loads(sys.argv[1])
def bgp_peer_walk(host):
oid = '.1.3.6.1.2.1.15.3.1.2'
reg_ex = re.compile('[0-9]+.[0-9]+.[0-9]+.[0-9]+ = [1-6]')
bgp_peer_dict = {}
for (errorIndication,
errorStatus,
errorIndex,
varBinds) in nextCmd(SnmpEngine(),
CommunityData(prtg_params['snmpcommv2']),
UdpTransportTarget((host, 161)),
ContextData(),
ObjectType(ObjectIdentity(oid)),
lexicographicMode=False):
if errorIndication:
csr = CustomSensorResult(text="Python Script pysnmp error")
csr.error = f"Python Script pysnmp error: {errorIndication}"
print(csr.json_result)
sys.exit()
elif errorStatus:
csr = CustomSensorResult(text="Python Script pysnmp error")
csr.error = f"Python Script pysnmp error: {errorStatus}"
print(csr.json_result)
sys.exit()
else:
for varBind in varBinds:
bgp_peers = reg_ex.search(str(varBind))
ip, state = str(bgp_peers.group(0)).split(' = ')
bgp_peer_dict[ip] = state
return(bgp_peer_dict)
def build_csr(peer_dict):
try:
csr = CustomSensorResult()
for peer in peer_dict:
if peer_dict[peer] is '6':
csr.add_channel(name = peer, value = 6, unit = ValueUnit.CUSTOM, is_warning = 0, value_lookup="customsensor.bgp4.peerstatus")
if peer_dict[peer] is '5':
csr.add_channel(name = peer, value = 5, unit = ValueUnit.CUSTOM, is_warning = 1, value_lookup="customsensor.bgp4.peerstatus")
if peer_dict[peer] is '4':
csr.add_channel(name = peer, value = 4, unit = ValueUnit.CUSTOM, is_warning = 1, value_lookup="customsensor.bgp4.peerstatus")
if peer_dict[peer] is '3':
csr.add_channel(name = peer, value = 3, unit = ValueUnit.CUSTOM, is_warning = 1, value_lookup="customsensor.bgp4.peerstatus")
if peer_dict[peer] is '2':
csr.add_channel(name = peer, value = 2, unit = ValueUnit.CUSTOM, is_warning = 1, value_lookup="customsensor.bgp4.peerstatus")
if peer_dict[peer] is '1':
csr.add_channel(name = peer, value = 1, unit = ValueUnit.CUSTOM, is_warning = 1, value_lookup="customsensor.bgp4.peerstatus")
print(csr.json_result)
except Exception as e:
csr = CustomSensorResult(text="Python build_csr execution error")
csr.error = f"Python Script execution error: {e}"
print(csr.json_result)
build_csr(bgp_peer_walk(prtg_params['host']))