-
Notifications
You must be signed in to change notification settings - Fork 1
/
pysnmp_list_BGP_neighbor_and_status
68 lines (51 loc) · 2.29 KB
/
pysnmp_list_BGP_neighbor_and_status
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/home/repos/public/Python/bin/python3.6
#
import re
from pysnmp.hlapi import *
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def construct_snmp_iterator(device, snmp_oid):
iterator = f"nextCmd(SnmpEngine(), UsmUserData('{snmp_username}', '{snmp_password}'), UdpTransportTarget(('{device}', 161)), ContextData(), ObjectType(ObjectIdentity('{snmp_oid}')), loo
kupMib=False, lexicographicMode=False)"
return eval(iterator)
def snmpwalk(device, iterator):
snmpwalk_response_list = []
for (errorIndication, errorStatus, errorIndex, varBinds) in iterator:
if errorIndication:
print(device, "ERROR: ", errorIndication)
break
elif errorStatus:
print('ERROR STATUS: %s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
break
else:
for varBind in varBinds:
snmp_response = ' = '.join([x.prettyPrint() for x in varBind])
snmpwalk_response_list.append([device, snmp_response])
return snmpwalk_response_list
def list_bgp_status(devices):
cbgpPeer2State = "1.3.6.1.4.1.9.9.187.1.2.5.1.3"
print()
print("Listing BGP Neighbors and Status:")
print("----------------------------------------------------------------------")
for device in devices:
iterator = construct_snmp_iterator(device, cbgpPeer2State)
bgp_status = snmpwalk(device, iterator)
for item in bgp_status:
if (item[-1].split("=")[-1].strip()) != "6":
bgp_neighbor = re.findall(r'(\d+\.\d+\.\d+\.\d+)$', item[-1].split("=")[0].strip())[0]
print(f"{device : <32} BGP Neighbor {bgp_neighbor : <15} is {bcolors.FAIL}DOWN{bcolors.ENDC}")
elif (item[-1].split("=")[-1].strip()) == "6":
bgp_neighbor = re.findall(r'(\d+\.\d+\.\d+\.\d+)$', item[-1].split("=")[0].strip())[0]
print(f"{device : <32} BGP Neighbor {bgp_neighbor : <15} is {bcolors.OKGREEN}UP{bcolors.ENDC}")
snmp_username = "<snmp_username>"
snmp_password = "<snmp_password>"
devices = ["device1", "device2"]
list_bgp_status(devices)