-
Notifications
You must be signed in to change notification settings - Fork 3
/
check_Mikrotik_OS.py
executable file
·236 lines (179 loc) · 7.86 KB
/
check_Mikrotik_OS.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/env python3
import argparse
import sys
import datetime
import urllib.request
import ssl
from packaging.version import Version, parse
#MIKROTIK-MIB::
#MIKROTIK-MIB::mtxrLicVersion.0
OID_RouterOSVersion = '.1.3.6.1.4.1.14988.1.1.4.4.0' # Current RouterOS version on device
#MIKROTIK-MIB::mtxrFirmwareVersion.0
OID_CurrentFirmwareVersion = '.1.3.6.1.4.1.14988.1.1.7.4.0' # Current RouterOS Firmware Version on device
#MIKROTIK-MIB::mtxrFirmwareUpgradeVersion.0
OID_LatestFirmwareVersion = '.1.3.6.1.4.1.14988.1.1.7.7.0' # Latest availble RouterOS Firmware Version
baseURLS = {"https://download.mikrotik.com/", "https://upgrade.mikrotik.com/" }
debug = False;
def nagios_exit(overallStatus, message):
#print(overallStatus + " : " + message)
print(overallStatus, ":", message)
if overallStatus == "Ok":
sys.exit(0)
if overallStatus == "Warning":
sys.exit(1)
if overallStatus == "Critical":
sys.exit(2)
if overallStatus == "Unknown":
sys.exit(3)
try:
from pysnmp.hlapi import *
except:
message = """This script requires the followng non standard libaries to run:
* pysnmp
"""
nagios_exit("Unknown", message)
def getLatestMikrotik(ReleaseChannel):
error = ""
for EachBaseURL in baseURLS:
# Get the lasest Version number from the Mikrotik website based on the
# supplied release channel.
# Define URLS. (Note that only RouterOS V6 is currently supported.
currentURL = "routeros/LATEST.6"
bugFixOnlyURL = "routeros/LATEST.6fix"
RCURL = "routeros/LATEST.6rc"
if ReleaseChannel == "Current":
URL = EachBaseURL + currentURL
elif ReleaseChannel == "Bugfix":
URL = EachBaseURL + bugFixOnlyURL
elif ReleaseChannel == "ReleaseCandidate":
URL = EachBaseURL + RCURL
else:
nagios_exit("Unknown", "Unknown Mikrotik Release Channel")
try:
with urllib.request.urlopen(URL) as response:
ReturnedString = response.read()
ReturnedString = ReturnedString.decode('utf-8')
ReturnedString = ReturnedString.split()
lastestVersion = ReturnedString[0]
ReleaseDate = ReturnedString[1]
return lastestVersion, ReleaseDate
except ssl.CertificateError as e:
debugMessage(URL)
error = e
debugMessage(e)
except Exception as e:
debugMessage(e.__class__)
debugMessage(e)
nagios_exit("Unknown", "Could not retrive latest RouterOS version from Mikrotik Website")
nagios_exit("Unknown", "Could not retrive latest RouterOS version from Mikrotik Website:" + str(error))
def debugMessage(message):
if debug == True:
print ("debug: " + str(message))
def getSNMP_OID(IPAddress, Version, SNMPOptions, OID):
# Gets the SNMP OID from the requested OID.
if Version == "2c":
g = getCmd(SnmpEngine(),
CommunityData(SNMPOptions['Community']),
UdpTransportTarget((IPAddress, 161)),
ContextData(),
ObjectType(ObjectIdentity(OID))
)
errorIndication, errorStatus, errorIndex, varBinds = next(g)
if errorIndication is None:
firstrow = varBinds[0] # note that any subsequent results are discarded
return firstrow[1]
else:
nagios_exit("Unknown", "SNMP Communication Error")
def process_cli():
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--hostIP',
help='Mikrotik Router IP Address',
type=str, required=True)
parser.add_argument('-v', '--snmpVersion',
help='SNMP Version (only 2c currently supported) ',
type=str, required=True)
parser.add_argument('-C', '--snmpCommunity',
help='SNMP Community String (only v1 and 2c) ', type=str, required=False)
parser.add_argument('-c', '--mikrotikReleaseChannel',
help='The mikrotik release channel to check for updates against: Bugfix, Current or \
ReleaseCandidate',
type=str, required=True)
# Parse arguments and die if error
try:
args = parser.parse_args()
except Exception:
sys.exit(3)
if not args.snmpCommunity and args.snmpVersion != 3:
print ("SNMP Community string required for SNMP Versions other than v3.")
sys.exit(3)
return args
def OutOfDate(CurrentVersionString, LatestVersionString):
try:
CurrentVersionString = str(CurrentVersionString)
CurrentVersionString = CurrentVersionString.replace('rc', 'b')
CurrentVersion = Version(str(CurrentVersionString))
except:
message = "Don't know how to handle current version number"
nagios_exit('Unknown', message)
try:
# if the length of the string is 0 then it can't be a proper version number.
if len(LatestVersionString) == 0:
raise
LatestVersionString = str(LatestVersionString)
LatestVersionString = LatestVersionString.replace('rc', 'b')
LatestVersion = Version(LatestVersionString)
except:
message = "Don't know how to handle latest number"
nagios_exit('Unknown', message)
if LatestVersion > CurrentVersion:
return True
else:
return False
def statusCheck(currentStatus, NewStatus):
# Function to take two Nagios status and return the worst case.
if currentStatus == 'Critical' or NewStatus == 'Critical':
return 'Critical'
elif currentStatus == 'Warning' or NewStatus == 'Warning':
return 'Warning'
elif currentStatus == 'Unknown' or NewStatus == 'Unknown':
return 'Unknown'
else:
return 'Ok'
def main():
args = process_cli()
SNMPOptions = {'Community': args.snmpCommunity}
# Get information from SNMP and mikrotik websites about version mumbers
LatestRouterOSVersion, LatestRouterOSVersion_ReleaseDate = (getLatestMikrotik(args.mikrotikReleaseChannel))
CurrentRouterOsVerion = str((getSNMP_OID(args.hostIP, args.snmpVersion, SNMPOptions, OID_RouterOSVersion)))
CurrentFirmwareVersion = getSNMP_OID(args.hostIP, args.snmpVersion, SNMPOptions, OID_CurrentFirmwareVersion)
LastestFirmwareVersion = getSNMP_OID(args.hostIP, args.snmpVersion, SNMPOptions, OID_LatestFirmwareVersion)
# Determine RouterOS Version Status
if OutOfDate(CurrentRouterOsVerion, LatestRouterOSVersion) is False:
RouterOSMessage = "RouterOS is up to date (" + CurrentRouterOsVerion + ")."
RouterOSStatus = 'Ok'
else:
now = datetime.datetime.now()
dateofLastRelease = datetime.datetime.fromtimestamp(float(LatestRouterOSVersion_ReleaseDate))
delta = now - dateofLastRelease
RouterOSMessage = "Router upgrade from " + CurrentRouterOsVerion + " to " + LatestRouterOSVersion + " is required"
if delta.days < 7:
RouterOSStatus = 'Warning'
else:
RouterOSStatus = 'Critical'
# Determine current Firmware Status
if OutOfDate(CurrentFirmwareVersion, LastestFirmwareVersion):
firmwareMessage = "Firmware Requires Upgrade (" + CurrentFirmwareVersion + " -> " + LastestFirmwareVersion + ")."
firmwareStatus = "Critical"
else:
firmwareMessage = "Firmware is up to date (" + CurrentFirmwareVersion + ")."
firmwareStatus = "Ok"
# Figure out overall status
overallStatus = statusCheck(RouterOSStatus, firmwareStatus)
if overallStatus == "Ok":
message = "RouterOS and Firmware is up to date" + " (" + CurrentRouterOsVerion + "/" \
+ CurrentFirmwareVersion + ")."
nagios_exit("OK", message)
else:
nagios_exit(overallStatus, RouterOSMessage + " " + firmwareMessage)
if __name__ == "__main__":
main()