-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_asusrouterweb
572 lines (516 loc) · 23.2 KB
/
check_asusrouterweb
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
import requests
import base64
import json
import time
import argparse
import os
import sys
import pathlib
#-------------------------------------------------------------------------------
_candebug = False
def candebug():
global _candebug
return _candebug
def setcandebug(value):
global _candebug
_candebug = value
def infomsg(msg):
if candebug() == True:
print(msg, flush=True)
def exitnagios(status,message):
if status=="OK":
exitcode = 0
elif status=="WARNING":
exitcode = 1
elif status=="CRITICAL":
exitcode = 2
elif status=="UNKNOWN":
exitcode = 3
else:
exitcode = 4
print(status+": "+message, flush=True)
sys.exit(exitcode)
#-------------------------------------------------------------------------------
original_getaddrinfo = socket.getaddrinfo
def forced_ipv6_gai_family(*args, **kwargs):
global original_getaddrinfo
responses = original_getaddrinfo(*args, **kwargs)
return [response
for response in responses
if response[0] == socket.AF_INET6]
def forced_ipv4_gai_family(*args, **kwargs):
global original_getaddrinfo
responses = original_getaddrinfo(*args, **kwargs)
return [response
for response in responses
if response[0] == socket.AF_INET]
#-------------------------------------------------------------------------------
class RouterInfo:
def __init__(self, ipaddress, username, password):
"""
Create the object and connect with the router
Parameters:
ipaddress : IP Address of the router
username : Root user name
password : Password required to login
"""
self.url = 'http://{}/appGet.cgi'.format(ipaddress)
self.headers = None
self.__authenticate(ipaddress, username, password)
def __authenticate(self, ipaddress, username, password):
"""
Authenticate the object with the router
Parameters:
username : Root user name
password : Password required to login
"""
auth = "{}:{}".format(username, password).encode('ascii')
logintoken = base64.b64encode(auth).decode('ascii')
payload = "login_authorization={}".format(logintoken)
headers = {
'user-agent': "asusrouter-Android-DUTUtil-1.0.0.245"
}
try:
r = requests.post(url='http://{}/login.cgi'.format(ipaddress), data=payload, headers=headers).json()
except:
return False
if "asus_token" in r:
token = r['asus_token']
self.headers = {
'user-agent': "asusrouter-Android-DUTUtil-1.0.0.245",
'cookie': 'asus_token={}'.format(token)
}
return True
else:
return False
def __get(self, command):
"""
Private get method to execute a hook on the router and return the result
Parameters:
command : Command to send to the return
:returns: string result from the router
"""
if self.headers:
payload = "hook={}".format(command)
try:
r = requests.post(url=self.url, data=payload, headers=self.headers)
except:
return None
return r.text
else:
return None
def get_uptime(self):
"""
Return uptime of the router
Format: {'since': 'Thu, 22 Jul 2021 14:32:38 +0200', 'uptime': '375001'}
:returns: JSON with last boot time and uptime in seconds
"""
r = self.__get('uptime()')
if r==None:
return None
else:
temp = json.loads(r)["uptime"]
parts = temp.replace("(","¶").replace(")","¶").split("¶")
since = parts[0]
up = parts[1].split()[0]
return json.loads('{' + '"since":"{}", "uptime":"{}"'.format(since, up) + '}')
def get_uptime_secs(self):
"""
Return uptime of the router in seconds
:returns: integer - uptime in seconds
"""
r = self.get_uptime()
if r==None:
return None
else:
return int(r['uptime'])
def get_memory_usage(self):
"""
Return memory usage of the router
Format: {'mem_total': '262144', 'mem_free': '107320', 'mem_used': '154824'}
:returns: JSON with memory variables
"""
r = self.__get('memory_usage()')
if r==None:
return None
else:
return json.loads('{' + r[17:])
def get_cpu_usage(self):
"""
Return CPU usage of the router
Format: {'cpu1_total': '38106047', 'cpu1_usage': '3395512',
'cpu2_total': '38106008', 'cpu2_usage': '2384694'}
:returns: JSON with CPU load statistics
"""
r = self.__get('cpu_usage()')
if r==None:
return None
else:
return json.loads('{' + r[14:])
def get_clients_fullinfo(self):
"""
Obtain a list of all clients
Format: {"get_clientlist":{"AC:84:C6:6C:A7:C0":{"type": "2", "defaultType": "0", "name": "Archer_C1200",
"nickName": "Router Forlindon", "ip": "192.168.2.175",
"mac": "AC:84:C6:6C:A7:C0", "from": "networkmapd",
"macRepeat": "1", "isGateway": "0", "isWebServer": "0",
"isPrinter": "0", "isITunes": "0", "dpiType": "",
"dpiDevice": "", "vendor": "TP-LINK", "isWL": "0",
"isOnline": "1", "ssid": "", "isLogin": "0", "opMode": "0",
"rssi": "0", "curTx": "", "curRx": "", "totalTx": "",
"totalRx": "", "wlConnectTime": "", "ipMethod": "Manual",
"ROG": "0", "group": "", "callback": "", "keeparp": "",
"qosLevel": "", "wtfast": "0", "internetMode": "allow",
"internetState": "1", "amesh_isReClient": "1",
"amesh_papMac": "04:D4:C4:C4:AD:D0"
},
"maclist": ["AC:84:C6:6C:A7:C0"],
"ClientAPILevel": "2" }}
:returns: JSON with list of clents and a list of mac addresses
"""
r = self.__get('get_clientlist()')
if r==None:
return None
else:
return json.loads(r)
# Total traffic in Mb/s
def get_traffic_total(self):
"""
Get total amount of traffic since last restart (Megabit format)
Format: {'sent': '15901.92873764038', 'recv': '10926.945571899414'}
:returns: JSON with sent and received Megabits since last boot
"""
r = self.__get('netdev(appobj)')
if r==None:
return None
else:
meas_2 = json.loads(r)
tx = int(meas_2['netdev']['INTERNET_tx'], base=16) * 8 / 1024 / 1024 / 2
rx = int(meas_2['netdev']['INTERNET_rx'], base=16) * 8 / 1024 / 1024 / 2
return json.loads('{' + '"sent":"{}", "recv":"{}"'.format(tx, rx) + '}')
# Traffic in Mb/s . Megabit per second
# Note this method has a 2 second delay to calculate current throughput
def get_traffic(self):
"""
Get total and current amount of traffic since last restart (Megabit format)
Note there is a two second delay to determine current traffic
Format: {"speed": {"tx": 0.13004302978515625, "rx": 4.189826965332031},
"total": {"sent": 15902.060073852539, "recv": 10931.135665893555}}
:returns: JSON with current up and down stream in Mbit/s and totals since last reboot
"""
meas_1 = self.__get('netdev(appobj)')
time.sleep(2)
meas_2 = self.__get('netdev(appobj)')
meas_1 = json.loads(meas_1)
meas_2 = json.loads(meas_2)
persec = {}
totaldata = {}
tx = int(meas_2['netdev']['INTERNET_tx'], base=16) * 8 / 1024 / 1024 / 2
totaldata['sent'] = tx
tx -= int(meas_1['netdev']['INTERNET_tx'], base=16) * 8 / 1024 / 1024 / 2
persec['tx'] = tx
rx = int(meas_2['netdev']['INTERNET_rx'], base=16) * 8 / 1024 / 1024 / 2
totaldata['recv'] = rx
rx -= int(meas_1['netdev']['INTERNET_rx'], base=16) * 8 / 1024 / 1024 / 2
persec['rx'] = rx
return json.dumps({'speed': persec, 'total': totaldata})
def get_status_wan(self):
"""
Get the status of the WAN connection
Format: {"status": "1", "statusstr": "'Connected'", "type": "'dhcp'", "ipaddr": "'192.168.1.2'",
"netmask": "'255.255.255.0'", "gateway": "'192.168.1.1'", "dns": "1.1.1.1'",
"lease": "86400", "expires": "81967", "xtype": "''", "xipaddr": "'0.0.0.0'",
"xnetmask": "'0.0.0.0'", "xgateway": "'0.0.0.0'", "xdns": "''", "xlease": "0",
"xexpires": "0"}
:returns: JSON with status information on the WAN connection
"""
r = self.__get('wanlink()')
if r==None:
return None
else:
status = {}
for f in r.split('\n'):
if 'return' in f:
if 'wanlink_' in f:
key = f.partition('(')[0].partition('_')[2]
value = f.rpartition(' ')[-1][:-2]
status[key] = value
return json.loads(json.dumps(status))
def is_wan_online(self):
"""
Returns if the WAN connection in onlise
:returns: True if WAN is connected
"""
r = self.get_status_wan()
if r==None:
return None
else:
return r['status'] == '1'
def get_settings(self):
"""
Get settings from the router
Format:{'time_zone': 'MEZ-1DST', 'time_zone_dst': '1', 'time_zone_x': 'MEZ-1DST,M3.2.0/2,M10.2.0/2',
'time_zone_dstoff': 'M3.2.0/2,M10.2.0/2', 'ntp_server0': 'pool.ntp.org', 'acs_dfs': '1',
'productid': 'RT-AC68U', 'apps_sq': '', 'lan_hwaddr': '04:D4:C4:C4:AD:D0',
'lan_ipaddr': '192.168.2.1', 'lan_proto': 'static', 'x_Setting': '1',
'label_mac': '04:D4:C4:C4:AD:D0', 'lan_netmask': '255.255.255.0', 'lan_gateway': '0.0.0.0',
'http_enable': '2', 'https_lanport': '8443', 'wl0_country_code': 'EU', 'wl1_country_code': 'EU'}
:returns: JSON with Router settings
"""
settings = {}
for s in ['time_zone', 'time_zone_dst', 'time_zone_x', 'time_zone_dstoff', 'time_zone',
'ntp_server0', 'acs_dfs', 'productid', 'apps_sq', 'lan_hwaddr', 'lan_ipaddr',
'lan_proto', 'x_Setting', 'label_mac', 'lan_netmask', 'lan_gateway',
'http_enable', 'https_lanport', 'wl0_country_code', 'wl1_country_code']:
r = self.__get("nvram_get(" + s + ")")
if r!=None:
settings[s] = json.loads(r)[s]
return settings
def get_lan_ip_address(self):
"""
Obtain the IP address of the router
:return: IP address
"""
r = self.__get("nvram_get(lan_ipaddr)")
if r==None:
return None
else:
return json.loads(r)['lan_ipaddr']
def get_lan_netmask(self):
"""
Obtain the Netmask for the LAN network
:return: Netmask
"""
r = self.__get("nvram_get(lan_netmask)")
if r==None:
return None
else:
return json.loads(r)['lan_netmask']
def get_lan_gateway(self):
"""
Obtain the gateway for the LAN network
:return: IP address of gateay
"""
r = self.__get("nvram_get(lan_gateway)")
if r==None:
return None
else:
return json.loads(r)['lan_gateway']
def get_dhcp_list(self):
"""
Obtain a list of DHCP leases
Format: { "dhcpLeaseMacList":[["00:00:00:00:00:00", "name"], ...]
:returns: JSON with a list of DHCP leases
"""
r = self.__get("dhcpLeaseMacList()")
if r==None:
return None
else:
return json.loads(r)
def get_online_clients(self):
"""
Obtain a list of MAC-addresses from online clients
Format: [{"mac": "00:00:00:00:00:00"}, ...]
:returns: JSON list with MAC addresses
"""
clnts = self.get_clients_fullinfo()
if clnts==None:
return None
else:
infomsg(clnts)
lst = []
for c in clnts['get_clientlist']:
if (len(c) == 17) and ("isOnline" in clnts['get_clientlist'][c]) and (clnts['get_clientlist'][c]['isOnline'] == '1'):
lst.append({"mac": c})
return json.dumps(lst)
def get_clients_info(self):
"""
Obtain info on all clients (limited list of datafields)
Format: [{"name": "Archer_C1200", "nickName": "Router Forlindon", "ip": "192.168.2.175",
"mac": "AC:84:C6:6C:A7:C0", "isOnline": "1", "curTx": "", "curRx": "", "totalTx": ""}, ...]
:return: JSON list of clients with main characteristics
"""
clnts = self.get_clients_fullinfo()
if clnts==None:
return None
else:
lst = []
for c in clnts['get_clientlist']:
# Only walk through the mac-addresses, not the additional datafields
if (len(c) == 17) and ("isOnline" in clnts['get_clientlist'][c]) and (clnts['get_clientlist'][c]['isOnline'] == '1'):
lst.append(
{
"name": clnts['get_clientlist'][c]['name'],
"nickName": clnts['get_clientlist'][c]['nickName'],
"ip": clnts['get_clientlist'][c]['ip'],
"mac": clnts['get_clientlist'][c]['mac'],
"isOnline": clnts['get_clientlist'][c]['isOnline'],
"curTx": clnts['get_clientlist'][c]['curTx'],
"curRx": clnts['get_clientlist'][c]['curRx'],
"totalTx": clnts['get_clientlist'][c]['totalTx'],
"totalRx": clnts['get_clientlist'][c]['totalRx'],
}
)
return json.loads(json.dumps(lst))
def get_client_info(self, clientid):
"""
Get info on a single client
:param clientid: MAC address of the client requested
:return: JSON with clientinfo (see get_clients_info() for description)
"""
clnts = self.get_clients_fullinfo()['get_clientlist']
if clnts==None:
return None
else:
if clientid in clnts:
return clnts[clientid]
else:
return None
#-------------------------------------------------------------------------------
def doasusroutercall(host,username,password,timeoutvalue):
try:
ri = RouterInfo(host,username,password)
infomsg(ri)
infomsg("Uptime : " + str(ri.get_uptime_secs()))
infomsg("Memory : " + str(ri.get_memory_usage()))
infomsg("CPU : " + str(ri.get_cpu_usage()))
infomsg("Data : " + str(ri.get_traffic_total()))
infomsg("Settings : " + str(ri.get_settings()))
infomsg("Uptime : " + str(ri.get_uptime()))
infomsg("Online : " + str(ri.is_wan_online()))
infomsg("Clients : " + str(ri.get_clients_fullinfo()))
infomsg("Clients : " + str(ri.get_clients_info()))
infomsg("Online : " + str(ri.get_online_clients()))
infomsg("IP addr : " + str(ri.get_lan_ip_address()))
infomsg("Netmask : " + str(ri.get_lan_netmask()))
infomsg("Gateway : " + str(ri.get_lan_gateway()))
infomsg("DHCP : " + str(ri.get_dhcp_list()))
infomsg("Bandwidth : " + str(ri.get_traffic()))
infomsg("WAN : " + str(ri.get_status_wan()))
infomsg("Client : " + str(ri.get_client_info('B8:2C:A0:5F:37:52')))
#status = "dummy"
#exitnagios("OK","the result '"+status+"' is as expected")
except Exception as e:
exitnagios("CRITICAL","unexpected error during the check "+str(e)+" | value=-1")
return ri
#-------------------------------------------------------------------------------
def check_status(value,warn_low,warn_high,crit_low,crit_high):
if ((crit_low!=None) and (crit_high!=None)) and ((value<crit_low) or (value>crit_high)):
exitnagios("CRITICAL","value "+str(value)+" is critical | value="+str(value))
elif ((warn_low!=None) and (warn_high!=None)) and ((value<warn_low) or (value>warn_high)):
exitnagios("WARNING","value "+str(value)+" is warning | value="+str(value))
else:
exitnagios("OK","value "+str(value)+" is as expected | value="+str(value))
#-------------------------------------------------------------------------------
def douptimecall(host,username,password,warn_low,warn_high,crit_low,crit_high,timeoutvalue,timeoutstatus):
ri = doasusroutercall(host,username,password,timeoutvalue)
uptime = ri.get_uptime_secs()
if uptime!=None:
infomsg(uptime)
check_status(uptime,warn_low,warn_high,crit_low,crit_high)
else:
exitnagios(timeoutstatus,"unable to retrieve the value | value=-1")
def domemorycall(host,username,password,warn_low,warn_high,crit_low,crit_high,timeoutvalue,timeoutstatus):
ri = doasusroutercall(host,username,password,timeoutvalue)
memory = ri.get_memory_usage()
if memory!=None:
value = (int(memory["mem_used"])/int(memory["mem_total"]))*100
infomsg(value)
check_status(round(value,2),warn_low,warn_high,crit_low,crit_high)
else:
exitnagios(timeoutstatus,"unable to retrieve the value | value=-1")
def docpucall(host,username,password,warn_low,warn_high,crit_low,crit_high,timeoutvalue,timeoutstatus):
ri = doasusroutercall(host,username,password,timeoutvalue)
cpu = ri.get_cpu_usage()
if cpu!=None:
infomsg(cores)
cores = int(len(cpu)/2)
counter = 1
values = []
while counter <= cores:
temp = (int(cpu["cpu"+str(counter)+"_usage"])/int(cpu["cpu"+str(counter)+"_total"]))*100
values.append(temp)
counter = counter+1
infomsg(values)
added = 0
for value in values:
added = added+value
average = added/len(values)
infomsg(average)
check_status(round(average,2),warn_low,warn_high,crit_low,crit_high)
else:
exitnagios(timeoutstatus,"unable to retrieve the value | value=-1")
#-------------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-4", "--ipv4", action="store_true", dest="ipv4", default=False, help="use ipv4 (exclusive with ipv6)")
parser.add_argument("-6", "--ipv6", action="store_true", dest="ipv6", default=False, help="use ipv6 (exclusive with ipv4)")
parser.add_argument("-0", "--ipv0", action="store_true", dest="ipv0", default=False, help="do not specify ip protocol version")
parser.add_argument("-H", "--hostname", dest="hostname", help="server to check")
parser.add_argument("-t", "--timeout", dest="timeout", default="10:CRITICAL", help="timeout value:STATUS")
parser.add_argument("-f", "--filecred", dest="filecred", default="", help="file containing the management credentials")
parser.add_argument("-m", "--mode", dest="mode", default="", help="value to check")
parser.add_argument("-w", "--warning", dest="warning", default="", help="warning level %")
parser.add_argument("-c", "--critical", dest="critical", default="", help="critical level %")
parser.add_argument("-®", "--debug", action="store_true", dest="debug", default=False, help="be more verbose")
args = parser.parse_args()
setcandebug(args.debug)
protocol = None
exclist = 0
if args.ipv0 == True :
protocol = ""
exclist = exclist+1
if args.ipv4 == True :
protocol = "-4"
exclist = exclist+1
socket.getaddrinfo = forced_ipv4_gai_family
if args.ipv6 == True :
protocol = "-6"
exclist = exclist+1
socket.getaddrinfo = forced_ipv6_gai_family
if (exclist>1) :
exitnagios("CRITICAL","select ip protocol version 4 or 6, or 0 to relay on OS handling")
elif (exclist<1) :
exitnagios("CRITICAL","no protocol selected")
if args.hostname==None or args.hostname=="":
exitnagios("CRITICAL","please specify a target hostname")
if args.filecred == "":
exitnagios("CRITICAL","filecred is not specified")
elif args.mode not in ["uptime","memory","cpu"]:
exitnagios("CRITICAL","mode must be uptime, memory, cpu")
else:
filecontentslines=pathlib.Path(args.filecred).read_text().splitlines()
username=filecontentslines[0]
password=filecontentslines[1]
parts = args.timeout.split(":")
timeoutvalue = int(parts[0])
if len(parts)>1:
timeoutstatus = parts[1]
else:
timeoutstatus = "CRITICAL"
if args.warning != "":
warnparts = args.warning.split(":")
warn_low = int(warnparts[0])
warn_high = int(warnparts[1])
else:
warn_low = None
warn_high = None
if args.critical != "":
critparts = args.critical.split(":")
crit_low = int(critparts[0])
crit_high = int(critparts[1])
else:
crit_low = None
crit_high = None
if args.mode=="uptime":
douptimecall(args.hostname,username,password,warn_low,warn_high,crit_low,crit_high,timeoutvalue,timeoutstatus)
elif args.mode=="memory":
domemorycall(args.hostname,username,password,warn_low,warn_high,crit_low,crit_high,timeoutvalue,timeoutstatus)
elif args.mode=="cpu":
docpucall(args.hostname,username,password,warn_low,warn_high,crit_low,crit_high,timeoutvalue,timeoutstatus)
exitnagios("CRITICAL","unexpected case")
if __name__ == "__main__":
main()
#-------------------------------------------------------------------------------