-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_dns
655 lines (600 loc) · 33.6 KB
/
check_dns
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
import os
import sys
import io
import time
import socket
import argparse
import dns.query
import dns.zone
import dns.resolver
import dns.exception
import difflib
import ipaddress
import socks
import traceback
import random
#-------------------------------------------------------------------------------
_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]
#-------------------------------------------------------------------------------
def resolvewithretries(customresolver, zone, field, useTcp, retries=3):
responses = None
# [] means that the record does not exists
# None means error contacting the server
for i in range(retries):
try:
responses = customresolver.resolve(zone, field, tcp=useTcp, raise_on_no_answer=True)
except dns.resolver.NXDOMAIN as e:
# The DNS query name does not exist:
infomsg("returning [] - "+type(e).__name__+" - "+str(e))
responses = []
except dns.resolver.NoAnswer as e:
# The DNS query name does not exist:
infomsg("returning [] - "+type(e).__name__+" - "+str(e))
responses = []
except Exception as e:
infomsg("returning None - "+type(e).__name__+" - "+str(e))
responses = None
infomsg("responses for type "+str(field)+" -> "+str(responses))
if responses == None:
time.sleep(i*5)
else:
break
infomsg(zone+" -> "+str(responses))
return responses
def build_name(entry, zone):
if entry.endswith("."):
return entry[0:-1]
else:
return entry+"."+zone
def get_address(protocol, serverinfo):
infomsg("get_address using "+protocol+" for "+str(serverinfo))
parts = serverinfo.split("@")
server = parts[0]
if len(parts)>1:
port = int(parts[1])
else:
port = 53
if server == ".":
result = "."+"@"+str(port)
else:
address = ""
try:
if protocol == "-6":
address = ipaddress.IPv6Address(server).compressed
elif protocol == "-4":
address = ipaddress.IPv4Address(server).compressed
else:
address = ipaddress.ip_address(server).compressed
return address+"@"+str(port)
except Exception as e:
pass
try:
if protocol == "-6":
address = socket.getaddrinfo(server, None, socket.AF_INET6)[0][4][0]
elif protocol == "-4":
address = socket.getaddrinfo(server, None, socket.AF_INET)[0][4][0]
else:
address = socket.getaddrinfo(server, None)[0][4][0]
except Exception as e:
exitnagios("CRITICAL","error during address resolution - "+str(e))
result = address+"@"+str(port)
infomsg("evaluated as "+result)
return result
def get_zone(useTcp, addressinfo, timeoutvalue, zone):
parts = addressinfo.split("@")
address = parts[0]
text = ""
for i in range(3):
text = ""
try:
xfr = dns.zone.from_xfr(dns.query.xfr(address, zone, relativize=True, timeout=timeoutvalue, use_udp=(not useTcp)), relativize=True)
names = list(xfr.keys())
names.sort()
for item in names:
node = xfr[item]
line = node.to_text(item, origin=xfr.origin, relativize=True, sorted=True)
parts = line.splitlines()
parts.sort()
line = os.linesep.join(parts)
text = text+os.linesep+line
except:
text = ""
pass
if text == "":
time.sleep(0.1)
else:
break
return text
def get_mname(useTcp, addressinfo, timeoutvalue, zone):
customresolver = get_resolver(addressinfo, timeoutvalue)
responses = resolvewithretries(customresolver, zone, "SOA", useTcp, retries=9)
if responses == None:
return ""
else:
return (responses[0]).mname.to_text()
def get_serial(useTcp, addressinfo, timeoutvalue, zone):
customresolver = get_resolver(addressinfo, timeoutvalue)
responses = resolvewithretries(customresolver, zone, "SOA", useTcp)
if responses == None:
return ""
else:
return (responses[0]).serial
def get_retry(useTcp, addressinfo, timeoutvalue, zone):
customresolver = get_resolver(addressinfo, timeoutvalue)
responses = resolvewithretries(customresolver, zone, "SOA", useTcp)
if responses == None:
return ""
else:
return (responses[0]).retry
def get_ns(useTcp, addressinfo, timeoutvalue, zone):
customresolver = get_resolver(addressinfo, timeoutvalue)
responses = resolvewithretries(customresolver, zone, "NS", useTcp)
if responses == None:
return ""
else:
result = []
if len(responses)>0:
for response in responses:
finalname = response.target.to_text()
if finalname not in result:
result.append(finalname)
return result
def get_records(useTcp, addressinfo, timeoutvalue, record, kind):
customresolver = get_resolver(addressinfo,timeoutvalue)
responses = resolvewithretries(customresolver, record, kind, useTcp)
if responses == None:
#server is not responding
return None
else:
#server is responding, maybe it returns an empty string is len(responses) is zero
temp = []
if len(responses)>0:
for rdata in responses:
if kind=="TXT":
joint = ""
for parttxt in rdata.strings:
joint = joint+parttxt.decode()
temp.append("\""+joint+"\"")
else:
temp.append(rdata.to_text())
result = ",".join(temp)
return result
def get_query(useTcp, protocol, addressinfo, timeoutvalue, entry):
customresolver = get_resolver(addressinfo,timeoutvalue)
canonical_name = entry
counter = 0
infomsg(canonical_name)
while True:
counter = counter+1
if counter>30:
# loop?
canonical_name = ""
break
else:
answer = resolvewithretries(customresolver, canonical_name, "CNAME", useTcp)
infomsg(answer)
if answer == None:
canonical_name = ""
break
elif len(answer)>0:
canonical_name = answer[0].to_text()
else:
# not None and not CNAME answer, ready to resolve A/AAAA
break
alternatives = []
if protocol == "-6":
responses = resolvewithretries(customresolver, canonical_name, "AAAA", useTcp)
if responses!=None:
for response in responses:
alternatives.append(response)
elif protocol == "-4":
responses = resolvewithretries(customresolver, canonical_name, "A", useTcp)
if responses!=None:
for response in responses:
alternatives.append(response)
else:
responses = resolvewithretries(customresolver, canonical_name, "AAAA", useTcp)
if responses!=None:
for response in responses:
alternatives.append(response)
responses = resolvewithretries(customresolver, canonical_name, "A", useTcp)
if responses!=None:
for response in responses:
alternatives.append(response)
if alternatives==None:
return ""
else:
result = ""
if len(alternatives)>0:
randpos = random.randrange(len(alternatives))
result = alternatives[randpos].to_text()
return result
def get_resolver(addressinfo, timeoutvalue):
parts = addressinfo.split("@")
address = parts[0]
if len(parts)>1:
port = int(parts[1])
else:
port = 53
if address == ".":
customresolver = dns.resolver.get_default_resolver()
else:
customresolver = dns.resolver.Resolver(configure=False)
for counter in range(5):
validparsing = False
try:
stream = io.StringIO("nameserver "+address)
customresolver.read_resolv_conf(stream)
except:
pass
if len(customresolver.nameservers) == 1:
if customresolver.nameservers[0] == address:
validparsing = True
if validparsing:
break
else:
time.sleep(1)
customresolver.port = port
customresolver.timeout = timeoutvalue
infomsg("found resolver "+str(customresolver._nameservers))
return customresolver
#-------------------------------------------------------------------------------
def check_record(useTcp, protocol, server, timeoutvalue, timeoutstatus, authoritative, record, kind, expected, alternativeslogic, recmissingwarn, recmissingcrit, recmincountwarn, recmincountcrit):
try:
addressinfo = get_address(protocol, server)
try:
found = get_records(useTcp, addressinfo, timeoutvalue, record, kind)
#infomsg(found)
if found == None:
#server not responding
exitnagios(timeoutstatus,"no response when trying to resolve records")
elif found=="":
#server responding, but no results
if expected==".":
exitnagios("OK","the query of record "+record+" to "+addressinfo+" did not return any value")
else:
exitnagios("CRITICAL","the server is not returning any value for the record")
else:
if expected == "":
exitnagios("OK","the query of record "+record+" to "+addressinfo+" was successful with value "+found+" - no specific result was expected")
else:
listexpected = sorted(expected.split(","))
listfound = sorted(found.split(","))
if (",".join(listexpected) == ",".join(listfound)):
exitnagios("OK","the query of record "+record+" to "+addressinfo+" was successful with value "+found+" as expected | found="+str(len(listfound)))
else:
listunexpected = []
for test in listfound:
if test not in listexpected:
listunexpected.append(test)
msgunexpected = "there were issues with the query of record "+record+" to "+addressinfo+" - Result "+" ".join(listunexpected)+" were not in expected "+expected+" | found="+str(len(listfound))+" unexpected="+str(len(listunexpected))
if len(listunexpected)>0:
exitnagios("CRITICAL",msgunexpected)
listmissing = []
for test in listexpected:
if test not in listfound:
listmissing.append(test)
msgmissing = "the query of record "+record+" to "+addressinfo+" was successful with value "+found+" but is missing "+" ".join(listmissing)+" as in "+expected+" | found="+str(len(listfound))+" missing="+str(len(listmissing))
if alternativeslogic == True:
exitnagios("OK",msgmissing)
if len(listmissing)>recmissingcrit:
exitnagios("CRITICAL",msgmissing)
if len(listmissing)>recmissingwarn:
exitnagios("WARNING",msgmissing)
msgfound = "the query of record "+record+" to "+addressinfo+" was successful with value "+found+" but is not reaching the minimum count of values | found="+str(len(listfound))+" unexpected=0 missing=0"
if len(listfound)<recmincountcrit:
exitnagios("CRITICAL",msgfound)
if len(listfound)<recmincountwarn:
exitnagios("WARNING",msgfound)
exitnagios("CRITICAL","unexpected situation")
except dns.exception.Timeout as e:
exitnagios(timeoutstatus,"timeout reaching "+addressinfo)
except dns.resolver.NoNameservers as e:
if str(e).endswith("No route to host"):
exitnagios(timeoutstatus,"error during check record - noroute - "+str(e))
else:
exitnagios("CRITICAL","error during check record - "+type(e).__name__+" - "+str(e))
except Exception as e:
if (expected == "."):
exitnagios("OK","the query of record "+record+" to "+addressinfo+" did not return any value")
else:
exitnagios("CRITICAL","error during check record - "+type(e).__name__+" - "+str(e))
def check_consistency(useTcp, protocol, server, timeoutvalue, timeoutstatus, authoritative, zone, mincountwarn, mincountcrit):
try:
addressinfo = get_address(protocol, server)
try:
mname = get_mname(useTcp, addressinfo, timeoutvalue, zone)
if mname == "":
exitnagios(timeoutstatus,"no response when trying to resolve mname for zone '"+zone+"' using server "+addressinfo)
text_mname = get_zone(useTcp, get_query(useTcp, protocol, addressinfo, timeoutvalue, build_name(mname, zone)), timeoutvalue, zone)
if text_mname=="":
exitnagios(timeoutstatus,"no response when trying to transfer zone '"+zone+"' from mname")
text_server = get_zone(useTcp, addressinfo, timeoutvalue, zone)
if text_server=="":
exitnagios(timeoutstatus,"no response when trying to transfer zone '"+zone+"' from server")
if text_mname != text_server:
exitnagios("CRITICAL","zone '"+zone+"' in target server "+server+" and MNAME server "+mname+" are different.")
infomsg(os.linesep.join(difflib.unified_diff(text_server.splitlines(),text_mname.splitlines())))
else:
ns = get_ns(useTcp, addressinfo, timeoutvalue, zone)
if ns == "":
exitnagios(timeoutstatus,"no response when trying to resolve ns")
#infomsg(ns)
validservers = []
errorservers = []
for test in ns:
#infomsg(test)
try:
text_test = get_zone(useTcp, get_query(useTcp, protocol, addressinfo, timeoutvalue, build_name(test, zone)), timeoutvalue, zone)
if text_test=="":
if test not in errorservers:
errorservers.append(test)
elif text_test == text_server:
validservers.append(test)
else:
#zonediff = os.linesep.join(difflib.unified_diff(text_server.splitlines(),text_test.splitlines()))
exitnagios("CRITICAL","zone '"+zone+"' in target server "+server+" and NS server "+test+" are different.")
except Exception as e:
if test not in errorservers:
errorservers.append(test)
if len(validservers)<mincountcrit and mincountcrit>=0 and len(errorservers)>0:
exitnagios("CRITICAL","zone '"+zone+"' match, but too many servers are not responding - errors: "+" ".join(errorservers)+" - valid: "+" ".join(validservers)+" | valid="+str(len(validservers))+" errors="+str(len(errorservers)))
elif len(validservers)<mincountwarn and mincountwarn>=0 and len(errorservers)>0:
exitnagios("WARNING","zone '"+zone+"' match, but too many servers are not responding - errors: "+" ".join(errorservers)+" - valid: "+" ".join(validservers)+" | valid="+str(len(validservers))+" errors="+str(len(errorservers)))
else:
exitnagios("OK","zone '"+zone+"' in target server matches the transfer from the MNAME and NS entries - errors "+" ".join(errorservers)+" - valid: "+" ".join(validservers)+" | valid="+str(len(validservers))+" errors="+str(len(errorservers)))
except dns.exception.Timeout as e:
exitnagios(timeoutstatus,"timeout reaching "+addressinfo)
except dns.resolver.NoNameservers as e:
if str(e).endswith("No route to host"):
infomsg(traceback.format_exc())
exitnagios(timeoutstatus,"error during check consistency - noroute - "+str(e))
else:
infomsg(traceback.format_exc())
exitnagios("CRITICAL","error during check consistency - "+type(e).__name__+" - "+str(e))
except Exception as e:
infomsg(traceback.format_exc())
exitnagios("CRITICAL","error during check consistency - "+type(e).__name__+" - "+str(e))
def check_serial(useTcp, protocol, server, timeoutvalue, timeoutstatus, authoritative, zone, tolerancewarn, tolerancecrit, mincountwarn, mincountcrit):
try:
addressinfo = get_address(protocol, server)
try:
automode = tolerancewarn<0 or tolerancecrit<0
serial_server = get_serial(useTcp, addressinfo, timeoutvalue, zone)
if serial_server == "":
exitnagios(timeoutstatus,"no response when trying to resolve serial_server "+addressinfo)
if automode:
retry_server = get_retry(useTcp, addressinfo, timeoutvalue, zone)
if retry_server == "":
exitnagios(timeoutstatus,"no response when trying to resolve retry_server "+addressinfo)
#infomsg(serial_server)
mname = get_mname(useTcp, addressinfo, timeoutvalue, zone)
if mname == "":
exitnagios(timeoutstatus,"no response when trying to resolve mname for zone "+zone+" using server "+addressinfo)
principalserver = get_query(useTcp, protocol, addressinfo, timeoutvalue, build_name(mname, zone))
#infomsg(principalserver)
serial_mname = get_serial(useTcp, principalserver, timeoutvalue, zone)
if serial_mname == "":
exitnagios(timeoutstatus,"no response when trying to resolve serial_mname for zone "+zone+" using found domain main server "+principalserver)
if automode:
retry_mname = get_retry(useTcp, principalserver, timeoutvalue, zone)
if retry_mname == "":
exitnagios(timeoutstatus,"no response when trying to resolve retry_mname")
#infomsg(serial_mname)
difference = abs(serial_mname-serial_server)
if automode:
commonretry = max(retry_server,retry_mname)
infomsg("the biggest retry time is "+str(commonretry))
tolerancewarn = commonretry
tolerancecrit = commonretry*2
identical = True
if (difference > tolerancecrit) or (difference > tolerancewarn):
identical = False
if difference > tolerancecrit:
exitnagios("CRITICAL","zone in target server "+server+":"+str(serial_server)+" and MNANE server "+mname+":"+str(serial_mname)+" have different serial (diff="+str(difference)+") | diff="+str(difference))
elif difference > tolerancewarn:
exitnagios("WARNING","zone in target server "+server+":"+str(serial_server)+" and MNAME server "+mname+":"+str(serial_mname)+" have different serial (diff="+str(difference)+") | diff="+str(difference))
else:
if difference > 0:
identical = False
ns = get_ns(useTcp, addressinfo, timeoutvalue, zone)
if ns == "":
exitnagios(timeoutstatus,"no response when trying to resolve ns")
#infomsg(ns)
validservers = []
errorservers = []
maxdifference = -1
for test in ns:
#infomsg(test)
try:
serial_test = get_serial(useTcp, get_query(useTcp, protocol, addressinfo, timeoutvalue, build_name(test, zone)), timeoutvalue, zone)
if serial_test == "":
if test not in errorservers:
errorservers.append(test)
#infomsg(str(serial_test))
difference = abs(serial_test-serial_server)
if difference > maxdifference:
maxdifference = difference
if (difference > tolerancecrit) or (difference > tolerancewarn):
identical = False
if difference > tolerancecrit:
exitnagios("CRITICAL","zone in target server "+server+":"+str(serial_server)+" and NS server "+test+":"+str(serial_test)+" have different serial (diff="+str(difference)+") | diff="+str(difference))
elif difference > tolerancewarn:
exitnagios("WARNING","zone in target server "+server+":"+str(serial_server)+" and NS server "+test+":"+str(serial_test)+" have different serial (diff="+str(difference)+") | diff="+str(difference))
if difference > 0:
identical = False
validservers.append(test)
except Exception as e:
if test not in errorservers:
errorservers.append(test)
if len(validservers)<mincountcrit and mincountcrit>=0 and len(errorservers)>0:
exitnagios("CRITICAL","serials match, but too many servers are not responding - errors: "+" ".join(errorservers)+" - valid: "+" ".join(validservers))
elif len(validservers)<mincountwarn and mincountwarn>=0 and len(errorservers)>0:
exitnagios("WARNING","serials match, but too many servers are not responding - errors: "+" ".join(errorservers)+" - valid: "+" ".join(validservers))
if identical == True:
exitnagios("OK","zone in target server has identical serial "+str(serial_server)+" than the MNAME and NS entries - errors "+" ".join(errorservers)+" - valid: "+" ".join(validservers)+" (maxdiff="+str(maxdifference)+") | maxdiff="+str(maxdifference)+" valid="+str(len(validservers))+" errors="+str(len(errorservers)))
else:
exitnagios("OK","zone in target server withing the tolerance "+str(tolerancewarn)+" of the serial "+str(serial_server)+" from the MNAME and NS entries - errors: "+" ".join(validservers)+" (maxdiff="+str(maxdifference)+") | maxdiff="+str(maxdifference)+" valid="+str(len(validservers))+" errors="+str(len(errorservers)))
except dns.exception.Timeout as e:
exitnagios(timeoutstatus,"timeout reaching "+addressinfo)
except dns.resolver.NoNameservers as e:
if str(e).endswith("No route to host"):
exitnagios(timeoutstatus,"error during check serial - noroute - "+str(e))
else:
exitnagios("CRITICAL","error during check serial - "+type(e).__name__+" - "+str(e))
except Exception as e:
exitnagios("CRITICAL","error during check serial - "+type(e).__name__+" - "+str(e))
def check_transfer(useTcp, protocol, server, timeoutvalue, timeoutstatus, authoritative, zone):
try:
addressinfo = get_address(protocol, server)
try:
start = datetime.datetime.now(datetime.UTC)
text = get_zone(useTcp, addressinfo, timeoutvalue, zone)
elapsed = datetime.datetime.now(datetime.UTC)-start
duration = elapsed.total_seconds()
if text!="":
exitnagios("OK","transfer of zone "+zone+" from "+addressinfo+" successful | duration="+str(duration))
else:
exitnagios("CRITICAL","there were issues with the transfer of zone "+zone+" from "+addressinfo)
except dns.exception.Timeout as e:
infomsg(timeoutstatus+": timeout reaching "+addressinfo)
except dns.resolver.NoNameservers as e:
if str(e).endswith("No route to host"):
exitnagios(timeoutstatus,"error during check transfer - "+type(e).__name__+" - "+str(e))
else:
raise
except Exception as e:
exitnagios("CRITICAL","error during check transfer - "+type(e).__name__+" - "+str(e))
def check_zone(useTcp, protocol, server, timeoutvalue, timeoutstatus, authoritative, zone, consistency, serial, transfer, tolerancewarn, tolerancecrit, mincountwarn, mincountcrit):
if consistency:
check_consistency(useTcp,protocol,server,timeoutvalue,timeoutstatus,authoritative,zone,mincountwarn,mincountcrit)
elif serial:
check_serial(useTcp,protocol,server,timeoutvalue,timeoutstatus,authoritative,zone,tolerancewarn,tolerancecrit,mincountwarn,mincountcrit)
elif transfer:
check_transfer(useTcp,protocol,server,timeoutvalue,timeoutstatus,authoritative,zone)
else:
exitnagios("CRITICAL","unknown check for zone")
#-------------------------------------------------------------------------------
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("-j", "--proxy", dest="proxy", default="", help="use a proxy")
parser.add_argument("-H", "--hostname", dest="hostname", help="server to check")
parser.add_argument("-m", "--mode", dest="mode", default="", help="mode TCP/UDP")
parser.add_argument("-r", "--record", dest="record", default="", help="record to query (exclusive with zone)")
parser.add_argument("-p", "--type", dest="kind", default="A", help="query type for the record")
parser.add_argument("-e", "--expected", dest="expected", default="", help="expected record value")
parser.add_argument("-A", "--alternativeslogic", action="store_true", dest="alternativeslogic",default=False, help="there is no need to match all the expected values")
parser.add_argument("-z", "--zone", dest="zone", default="", help="zone to test (exclusive with record)")
parser.add_argument("-y", "--consistency", action="store_true", dest="consistency", default=False, help="test full consistency for zone at server with MNAME and NS")
parser.add_argument("-l", "--serial" , action="store_true", dest="serial", default=False, help="test same serial for zone at server with MNAME and NS")
parser.add_argument("-f", "--transfer", action="store_true", dest="transfer", default=False, help="test transfer of zone at server")
parser.add_argument("-a", "--authoritative", action="store_true", dest="authoritative", default=False, help="the reply must be authoritative (not implemented)")
parser.add_argument("-o", "--sertolerancewarn", dest="sertolerancewarn", default="auto", help="tolerance in zone serial before considering warning (integer or 'auto')")
parser.add_argument("-n", "--sertolerancecrit", dest="sertolerancecrit", default="auto", help="tolerance in zone serial before considering critical (integer or 'auto')")
parser.add_argument("-u", "--sermincountwarn", dest="sermincountwarn", default="3", help="minimun number of responding servers before considering warning")
parser.add_argument("-i", "--sermincountcrit", dest="sermincountcrit", default="2", help="minimun number of responding servers before considering critical")
parser.add_argument("-O", "--recmissingwarn", dest="recmissingwarn", default="0", help="tolerance in missing values in record before considering warning")
parser.add_argument("-N", "--recmissingcrit", dest="recmissingcrit", default="0", help="tolerance in missing values in record before considering critical")
parser.add_argument("-U", "--recmincountwarn", dest="recmincountwarn", default="0", help="minimun number of values in record before considering warning")
parser.add_argument("-I", "--recmincountcrit", dest="recmincountcrit", default="0", help="minimun number of values in record servers before considering critical")
parser.add_argument("-t", "--timeout", dest="timeout", default="10:CRITICAL", help="timeout value:STATUS")
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.proxy != "":
# proxyparts = args.proxy.split("://",1)
# if proxyparts[0] == "socks5":
# proxydetails = proxyparts[1].split(":")
# socks.set_default_proxy(proxy_type=socks.SOCKS5, addr=proxydetails[0], port=int(proxydetails[1]))
# dns.query.socket_factory = socks.socksocket
if (args.record != "") and (args.zone != ""):
exitnagios("CRITICAL","parameters zone, record and consistency are exclusive")
if (args.consistency == False) and (args.serial == False) and (args.transfer == False) and (args.zone != ""):
exitnagios("CRITICAL","choose consistency serial or transfer when using a zone")
if args.mode == "tcp":
useTcp=True
else:
useTcp=False
if args.sertolerancewarn == "auto":
sertolerancewarn = -1
else:
sertolerancewarn = int(args.sertolerancewarn)
if args.sertolerancecrit == "auto":
sertolerancecrit = -1
else:
sertolerancecrit = int(args.sertolerancecrit)
parts = args.timeout.split(":")
timeoutvalue = int(parts[0])
if len(parts)>1:
timeoutstatus = parts[1]
else:
timeoutstatus = "CRITICAL"
if timeoutstatus in ["OK", "WARNING", "CRITICAL", "UNKNOWN"]:
if (args.zone != ""):
check_zone(useTcp,protocol,args.hostname,timeoutvalue,timeoutstatus,args.authoritative,args.zone,args.consistency,args.serial,args.transfer,sertolerancewarn,sertolerancecrit,int(args.sermincountwarn),int(args.sermincountcrit))
if (args.record != ""):
check_record(useTcp,protocol,args.hostname,timeoutvalue,timeoutstatus,args.authoritative,args.record,args.kind,args.expected,args.alternativeslogic,int(args.recmissingwarn),int(args.recmissingcrit),int(args.recmincountwarn),int(args.recmincountcrit))
else:
exitnagios("CRITICAL","timeout status is not valid")
exitnagios("CRITICAL","no zone or record defined")
if __name__ == "__main__":
main()
#-------------------------------------------------------------------------------