-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_reacheable
281 lines (250 loc) · 11.5 KB
/
check_reacheable
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
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
import sys
import os
import argparse
import subprocess
import socket
import concurrent.futures
import netifaces
import time
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)
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 interface_to_address(interface,protocol):
primary_ip = None
if interface!="":
try:
infomsg("protocol is "+protocol)
addresses = netifaces.ifaddresses(interface)
ip_info = []
if protocol in ["-4","4"]:
ip_info4 = addresses.get(netifaces.AF_INET)
if ip_info4!=None:
ip_info.append(ip_info4[0]["addr"])
elif protocol in ["-6","6"]:
ip_info6 = addresses.get(netifaces.AF_INET6)
if ip_info6!=None:
ip_info.append(ip_info6[0]["addr"])
else:
ip_info4 = addresses.get(netifaces.AF_INET)
if ip_info4!=None:
ip_info.append(ip_info4[0]["addr"])
ip_info6 = addresses.get(netifaces.AF_INET6)
if ip_info6!=None:
ip_info.append(ip_info6[0]["addr"])
random.shuffle(ip_info)
infomsg("------> "+str(ip_info))
if ip_info!=None and len(ip_info)>0:
primary_ip = ip_info[0]
else:
infomsg("could not get interface ip for "+interface)
except Exception as e:
infomsg("exception - "+str(e))
infomsg("The ip for interface "+interface+" is "+str(primary_ip))
return primary_ip
def dopingtestsingle(protocol, interface, packets, timeout, hostname, warningms, warningpercent, criticalms, criticalpercent):
source = interface_to_address(interface,protocol)
cmdline = ["/usr/bin/ping"]
if protocol not in ["",None]:
cmdline = cmdline + [protocol]
if source!=None:
cmdline = cmdline + ["-I", source]
elif interface!="":
cmdline = cmdline + ["-I", interface]
cmdline = cmdline + ["-c", str(packets)]
cmdline = cmdline + ["-W", str(2)]
cmdline = cmdline + [hostname]
infomsg(cmdline)
try:
completedproc = subprocess.run(cmdline,capture_output=True,timeout=timeout)
output = completedproc.stdout.decode("utf-8")
errors = completedproc.stderr.decode("utf-8")
exitcode = completedproc.returncode
except:
output = ""
errors = ""
exitcode = 2
infomsg(output)
if exitcode!=0:
return [2,-1,100,"error"]
else:
alllines = output.splitlines()
linems = alllines[-1]
linepercent = alllines[-2]
avgms = float(linems.split("=")[1].strip().split()[0].split("/")[1])
percent = float(linepercent.split(",")[2].strip().split()[0].replace("%",""))
reason = "undefinded"
if avgms >= criticalms:
reason = "critical latency"
infomsg(reason)
return [2,avgms,percent,reason]
elif percent >= criticalpercent:
reason = "critical ping loss"
infomsg(reason)
return [2,avgms,percent,reason]
elif avgms >= warningms:
reason = "warning latency"
infomsg(reason)
return [1,avgms,percent,reason]
elif percent >= warningpercent:
reason = "warning ping loss"
infomsg(reason)
return [1,avgms,percent,reason]
else:
reason = "no issues"
infomsg(reason)
return [0,avgms,percent,reason]
def dopingtestmulti(protocol, interface, packets, timeoutvalue, timeoutstatus, hostname, minimun, warningms, warningpercent, criticalms, criticalpercent):
hosts = hostname.replace(","," ").split()
valid = 0
warning = 0
average = 0
percentloss = 0
okreasons = []
warnreasons = []
critreasons = []
if protocol=="":
protocolslist = ["-4","-6"]
elif protocol=="-4":
protocolslist = ["-4"]
elif protocol=="-6":
protocolslist = ["-6"]
else:
protocolslist = []
executor = concurrent.futures.ThreadPoolExecutor()
futures = []
for hostsingle in hosts:
for protocol in protocolslist:
future = executor.submit(dopingtestsingle, protocol, interface, packets, timeoutvalue, hostsingle, warningms, warningpercent, criticalms, criticalpercent)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
result = future.result()
if isinstance(result, list):
average = average+result[1]
percentloss = percentloss+result[2]
reason = result[3]
if result[0] == 0:
valid = valid+1
if reason not in okreasons:
okreasons.append(reason)
elif result[0] == 1:
warning = warning+1
if reason not in warnreasons:
warnreasons.append(reason)
else:
if reason not in critreasons:
critreasons.append(reason)
infomsg(result)
average = float(average)/len(hosts)
percentloss = float(percentloss)/len(hosts)
percent = 100-percentloss
valid = float(valid)/len(protocolslist)
if valid >= minimun:
return ("OK",hostname+" - "+str(valid)+" of at lest "+str(minimun)+" entries are reacheable - "+str(okreasons)+" | valid="+str(valid)+" warning="+str(warning)+" average="+str(average)+" percent="+str(percent))
elif valid+warning >= minimun:
return ("WARNING",hostname+" - "+str(valid)+" of at lest "+str(minimun)+" entries are reacheable - "+str(warnreasons)+" | valid="+str(valid)+" warning="+str(warning)+" average="+str(average)+" percent="+str(percent))
else:
return (timeoutstatus,hostname+" - only "+str(valid)+" of at least "+str(minimun)+" entries are reacheable - "+str(critreasons)+" | valid="+str(valid)+" warning="+str(warning)+" average=-1 percent=0")
def dopingtestretry(retries, protocol, interface, packets, timeoutvalue, timeoutstatus, hostname, minimun, warningms, warningpercent, criticalms, criticalpercent):
counter = 0
while True:
exitlevel,message = dopingtestmulti(protocol, interface, packets, timeoutvalue, timeoutstatus, hostname, minimun, warningms, warningpercent, criticalms, criticalpercent)
if (exitlevel=="OK") or (counter>=retries):
exitnagios(exitlevel, message)
else:
counter = counter+1
time.sleep(5)
exitnagios("CRITICAL","unexpected state")
#-------------------------------------------------------------------------------
def parse_args():
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", action="store", help="target IP or hostname")
parser.add_argument("-i", "--interface", action="store", default="", help="interface to use")
parser.add_argument("-m", "--minimun", action="store", type=float, default=0.5 , help="at least, how many targets should be alive")
parser.add_argument("-p", "--packets", action="store", type=int, default=1, help="number of pings")
parser.add_argument("-t", "--timeout", action="store", default="10:CRITICAL", help="timeout value:STATUS")
parser.add_argument("-w", "--warning", action="store", default="600,20%", help="ms,percent%")
parser.add_argument("-c", "--critical", action="store", default="1000,40%", help="ms,percent%")
parser.add_argument("-r", "--retries", action="store", default="3", help="number of times to retry the logic")
parser.add_argument("-®", "--debug", action="store_true", dest="debug", default=False, help="be more verbose")
args = parser.parse_args()
return args
def main():
args = 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 == ""):
exitnagios("CRITICAL","hostname not defined")
timeoutparts = args.timeout.split(":")
timeoutvalue = int(timeoutparts[0])
timeoutstatus = "CRITICAL"
if len(timeoutparts)>1:
timeoutstatus = timeoutparts[1]
warningparts = args.warning.split(",")
warningms = int(float(warningparts[0]))
warningpercent = int(float(warningparts[1].replace("%","")))
criticalparts = args.critical.split(",")
criticalms = int(float(criticalparts[0]))
criticalpercent = int(float(criticalparts[1].replace("%","")))
retries = int(args.retries)
dopingtestretry(retries, protocol, args.interface, args.packets, timeoutvalue, timeoutstatus, args.hostname, args.minimun, warningms, warningpercent, criticalms, criticalpercent)
if __name__ == "__main__":
main()
#-------------------------------------------------------------------------------