-
Notifications
You must be signed in to change notification settings - Fork 0
/
bgp-monitor.py
94 lines (75 loc) · 2.32 KB
/
bgp-monitor.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from jnpr.junos import Device
from jnpr.junos.op.routes import RouteTable
import sys
import datetime
import os
import smtplib
import socket
deviceName = 'Juniper SRX'
deviceIP = 'x.x.x.x'
apiuser = 'username'
apipassword = 'password'
SMTP = 'smtp-alias'
fromName = 'BGP Monitor'
fromAddr = '[email protected]'
toName = 'networkAdmin'
toAddr = '[email protected]'
prefixDict = {
"FriendlyName": "Prefix",
"Route-to-Inet": "0.0.0.0/0"
}
hostname = socket.gethostname()
logfile = "./bgp.log"
tempfile = "./bgproutes.temp"
timestamp = datetime.datetime.now()
dev = Device(deviceIP, user=apiuser, password=apipassword)
def sendMail(oldroutes, newroutes, status):
message = """From: %s <%s>
To: %s <%s>
Subject: Change Detected by BGP Monitor
The script bgp-monitor.py has detected a change in the BGP routes being learned.
Please verify BGP peers on %s (%s).
Earlier Route List: %s
Updated Route List: %s
Status: %s
Alert triggered at %s
SENT FROM %s
""" % (fromName, fromAddr, toName, toAddr, deviceName, deviceIP,
oldroutes, newroutes, status, timestamp, hostname)
server = smtplib.SMTP(SMTP)
server.sendmail(fromAddr, toAddr, message)
def checkBGP():
with open(logfile, 'ab') as a:
a.write("Execute BGP Monitor at: %s \n" % timestamp)
try:
dev.open()
with open(logfile, 'ab') as a:
a.write("Connected to %s \n" % deviceIP)
except:
with open(logfile, 'ab') as a:
a.write("ERR: CONNECTION ERROR: FAILED TO CONNECT TO %s \n" % deviceIP)
sys.exit(0)
allroutes = RouteTable(dev)
bgp = allroutes.get(protocol="bgp").keys()
dev.close()
if not os.path.isfile(tempfile):
with open(tempfile, 'w+b') as a:
a.write(str(bgp))
sys.exit(0)
with open(tempfile, 'ab') as a:
lastroutes = a.readlines()
if str(bgp) == str(lastroutes[0]):
sys.exit(0)
if str(bgp) != str(lastroutes[0]):
pass
with open(tempfile, 'w+b') as a:
a.write(str(bgp))
status = []
for name, prefix in prefixDict.items():
if prefix in bgp:
status.append("%s - RECEIVED" % name)
if not prefix in bgp:
status.append("%s - MISSING" % name)
sendMail(str(lastroutes[0]), str(bgp), status)
if __name__ == '__main__':
checkBGP()