-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpynag.py
414 lines (373 loc) · 15.9 KB
/
pynag.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
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
#!/usr/bin/python
"""
Script inspired in the nagios_commander
"""
import re
import requests
import argparse
import json
import webbrowser
from datetime import datetime
from termcolor import cprint
from PyInquirer import prompt, Separator
parser = argparse.ArgumentParser(
description='Nagios Python CLI'
)
parser.add_argument('--host', '-H',
help='list all hosts status, Send "all" to list all host status',
)
parser.add_argument('--service_status', '-S',
help='Service Status Details a specific host. '
'Send "all" to see all hosts problems services status',
action='store_true'
)
args = vars(parser.parse_args())
ACK_MESSAGE = 'Not critical or being worked on'
NAGIOS_INSTANCE = 'https://<nagios.domain.com>/nagios/cgi-bin'
http_user = '<my_user>'
http_password = '<super_secret_password>'
test_request = requests.get(NAGIOS_INSTANCE, auth=(http_user, http_password))
if test_request.status_code != 200:
print("Wrong credentials")
exit(1)
def do_post_request(url, user, password, params=None):
req = requests.get(url, auth=(user, password), params=params)
if test_request.status_code != 200:
print("Smth went wrong")
else:
return req.text
def get_all_hosts_status():
# Get hosts list
# https://nagios.domain.com/nagios/cgi-bin/status.cgi?hostgroup=all&style=hostdetail
data = {
'hostgroup': 'all',
'style': 'hostdetail',
'start': '0',
'limit': '500' # Set limit 500 hosts.
}
html_output = do_post_request(http_user, http_password, data)
# https://nagios.domain.com/nagios/cgi-bin/status.cgi?hostgroup=all&style=hostdetail
html_hosts = str.splitlines(html_output)
hosts_re = re.compile("<td align=left valign=center class='statusHOSTUP'>")
hosts_raw = list(filter(hosts_re.match, html_hosts))
host_output_hash = []
for host_line_raw in hosts_raw:
host_clean = re.sub('^<td.*title=.*\'>', '', host_line_raw)
host_clean = re.sub('</.*$', '', host_clean)
host_index = html_hosts.index(host_line_raw)
host_status_index = host_index + 15
host_status_raw = html_hosts[host_status_index]
host_status_clean = re.sub('^<td.*\'>', '', host_status_raw)
host_status_clean = re.sub('</td>$', '', host_status_clean)
host_output_hash += [host_clean + "\t\t" + host_status_clean]
print("\n".join(host_output_hash))
def nagios_request_validation(req_output, host, service, task):
ok_string = re.search(
'.*Your command request was successfully submitted to Nagios for processing.*',
req_output
)
if ok_string:
cprint(
'{host} - {task} - {service}: Your command request was successfully submitted to Nagios for'
' processing'.format(
host=host,
service=service,
task=task
),
'green'
)
else:
cprint(
'{host} - {task} - {service}: Your command request WAS NOT successfully submitted'.format(
host=host,
service=service,
task=task
),
'red',
attrs=['bold']
)
def get_all_service_status():
# https://nagios.domain.com/nagios/cgi-bin/status.cgi?host=all&servicestatustypes=28
data = {
'host': 'all',
'servicestatustypes': '28',
}
nagios_url = NAGIOS_INSTANCE + '/status.cgi'
all_service_status_request = do_post_request(nagios_url, http_user, http_password, data)
html_hosts = str.splitlines(all_service_status_request)
# <td align=left valign=center class='*'>
hosts_re = re.compile("<td align=left valign=center class='.*'>")
hosts_raw = list(filter(hosts_re.match, html_hosts))
service_hash = {}
menu = []
for host_line_raw in hosts_raw:
host_clean = re.sub('^<td.*title=.*\'>', '', host_line_raw)
host_clean = re.sub('</.*$', '', host_clean)
host_index = html_hosts.index(host_line_raw)
current_host_html = []
index = host_index
while True:
index = index + 1
# safe way to check if we have arrived at the end of the index
try:
next_line = html_hosts[index]
except IndexError:
break
# check if we got another host line
foo = hosts_re.match(next_line)
if foo:
break
else:
# print('get info from {}'.format(host_clean))
current_host_html = current_host_html + [next_line]
# <td align='left' valign=center class='statusBGWARNING'><a href='extinfo.cgi?type=2&host=web01.foo.net&service
service_re = re.compile(
"<td align='left' valign=center class='.*'><a href=.*&service"
)
services_raw = list(filter(service_re.match, current_host_html))
service_host_hash = {}
host_menu_string = '{host} (& sub services)'.format(host=host_clean)
menu = menu + [{'name': host_menu_string}]
for service_line_raw in services_raw:
service_clean = re.sub("^<td align='left' valign=center class='.*'><a.*'>", '', service_line_raw)
service_clean = re.sub('</.*$', '', service_clean)
# get service details
service_index = html_hosts.index(service_line_raw)
s_status_html = html_hosts[service_index + 11]
s_status = re.sub("^<td.*'>", '', s_status_html)
s_status = re.sub('</.*$', '', s_status)
s_last_check_html = html_hosts[service_index + 12]
s_last_check = re.sub("^<td.*nowrap>", '', s_last_check_html)
s_last_check = re.sub('</.*$', '', s_last_check)
s_duration_html = html_hosts[service_index + 13]
s_duration = re.sub("^<td.*nowrap>", '', s_duration_html)
s_duration = re.sub('</.*$', '', s_duration)
s_attempts_html = html_hosts[service_index + 14]
s_attempts = re.sub("^<td.*'>", '', s_attempts_html)
s_attempts = re.sub('</.*$', '', s_attempts)
s_info_html = html_hosts[service_index + 15]
s_info = re.sub("^<td.*'>", '', s_info_html)
s_info = re.sub('</.*$', '', s_info)
s_info = re.sub(' ', '', s_info)
s_info = re.sub('"', '', s_info)
# find out acknowledge
s_ack = False
s_mute = False
details_line = html_hosts[service_index + 6]
ack_match = re.search('.*This service problem has been acknowledged.*', details_line)
if ack_match:
s_ack = True
ack_string = '✔ ️'
else:
s_ack = False
ack_string = ' ️'
# find out disabled notif
mute_match = re.search('.*Notifications for this service have been disabled.*', details_line)
if mute_match:
s_mute = True
mute_string = '🔇'
else:
s_mute = False
mute_string = ' '
entry_suffix = ack_string + mute_string
service_host_hash[service_clean] = {
'status': s_status,
'last_check': s_last_check,
'duration': s_duration,
'attempts': s_attempts,
'info': s_info,
'ack': s_ack,
'notifications': s_mute,
}
new_menu_content = '{suffix} - {host} - {status} - {service} - {attempts} - {info}'.format(
suffix=entry_suffix,
host=host_clean,
service=service_clean,
status=s_status,
attempts=s_attempts,
info=s_info
)
menu = menu + [{'name': new_menu_content}]
service_hash[host_clean] = service_host_hash
questions = [
{
'type': 'checkbox',
'qmark': '😃',
'message': 'Service Status Details For All Hosts',
'name': 'service_status',
'choices': menu,
'validate': lambda answer: 'You must choose at least one topping.'
if len(answer) == 0 else True
}
]
answers = prompt(questions)
return answers, service_hash
def do_actions(actions_service_status, services_hash):
selected_answers = {}
for service_status in actions_service_status['service_status']:
host_match = re.search('.*sub services.*', service_status)
if host_match:
host = service_status.split(' ')[0]
service = 'all'
else:
host = service_status.split(' - ')[1]
service = service_status.split(' - ')[3]
if host in selected_answers:
selected_answers[host] = selected_answers[host] + [service]
else:
selected_answers[host] = [service]
if len(selected_answers) == 0:
print("You haven't selected any option, use <space> to mark the service you want to work with...")
exit()
print(json.dumps(selected_answers, indent=2, sort_keys=True))
# Add option
# recheck
# ack - remove ack
# disable notif - Enable notif
# open in browser
print("you have selected the following services")
question = [
{
'type': 'confirm',
'message': 'Do you want to continue?',
'name': 'continue',
'default': True,
}
]
confirm = prompt(question)
if confirm['continue']:
action_question = [
{
'type': 'list',
'name': 'action',
'message': 'What do you want to do?',
'choices': [
'Open in browser',
'Recheck',
'ACK - Remove ACK',
'Disable Notif',
'Enable Notif',
'Exit'
],
# 'filter': lambda val: val.lower()
},
]
action_selected = prompt(action_question)
if action_selected['action'] == 'Open in browser':
# NAGIOS_INSTANCE = 'https://nagios.evilcorp.com/nagios/cgi-bin'
# /extinfo.cgi?type=2&host=foo.bar.org&service=disk
for host in selected_answers:
for service in selected_answers[host]:
if service == 'all':
url = NAGIOS_INSTANCE + "/status.cgi?host={host}".format(
host=host,
service=service,
)
else:
url = NAGIOS_INSTANCE + "/extinfo.cgi?type=2&host={host}&service={service}".format(
host=host,
service=service,
)
webbrowser.open(url)
elif action_selected['action'] == 'Recheck':
now = datetime.now()
date_time = now.strftime("%y-%-m-%d %H:%M:%S")
for host in selected_answers:
for service in selected_answers[host]:
if service == 'all':
cmd_typ = '17' # CMD_SCHEDULE_HOST_SVC_CHECKS
else:
cmd_typ = '7' # CMD_SCHEDULE_SVC_CHECK
data = {
'host': host,
'cmd_typ': cmd_typ,
'cmd_mod': '2',
'btnSubmit': 'Commit',
'service': service,
'start_time': date_time,
'force_recheck': 'on',
}
nagios_url = NAGIOS_INSTANCE + '/cmd.cgi'
req_output = do_post_request(nagios_url, http_user, http_password, data)
nagios_request_validation(req_output, host, service, 'recheck')
elif action_selected['action'] == 'ACK - Remove ACK':
# FIXME ACK doesn't work when service = all
for host in selected_answers:
for service in selected_answers[host]:
# host_ack = services_hash[host]
if services_hash[host][service]['ack']:
if service == 'all':
cmd_type = '51' # CMD_REMOVE_HOST_ACKNOWLEDGEMENT
else:
cmd_type = '52' # CMD_REMOVE_SVC_ACKNOWLEDGEMENT
data = {
'host': host,
'cmd_typ': cmd_type,
'cmd_mod': '2',
'btnSubmit': 'Commit',
'service': service,
}
nagios_url = NAGIOS_INSTANCE + '/cmd.cgi'
req_output = do_post_request(nagios_url, http_user, http_password, data)
nagios_request_validation(req_output, host, service, 'remove_ack')
else:
# no ack
if service == 'all':
cmd_type = '33' # CMD_ACKNOWLEDGE_HOST_PROBLEM
else:
cmd_type = '34' # CMD_ACKNOWLEDGE_SVC_PROBLEM
data = {
'host': host,
'cmd_typ': cmd_type,
'cmd_mod': '2',
'btnSubmit': 'Commit',
'service': service,
'sticky_ack': 'on',
'send_notification': 'on',
'com_data': ACK_MESSAGE,
}
nagios_url = NAGIOS_INSTANCE + '/cmd.cgi'
req_output = do_post_request(nagios_url, http_user, http_password, data)
nagios_request_validation(req_output, host, service, 'send_ack')
elif action_selected['action'] == 'Disable Notif':
for host in selected_answers:
for service in selected_answers[host]:
if service == 'all':
cmd_type = '29' # CMD_DISABLE_HOST_SVC_NOTIFICATIONS
else:
cmd_type = '23' # CMD_DISABLE_SVC_NOTIFICATIONS
data = {
'host': host,
'cmd_typ': cmd_type,
'cmd_mod': '2',
'btnSubmit': 'Commit',
'service': service,
}
nagios_url = NAGIOS_INSTANCE + '/cmd.cgi'
req_output = do_post_request(nagios_url, http_user, http_password, data)
nagios_request_validation(req_output, host, service, 'disable_notif')
elif action_selected['action'] == 'Enable Notif':
for host in selected_answers:
for service in selected_answers[host]:
if service == 'all':
cmd_type = '28' # CMD_ENABLE_HOST_SVC_NOTIFICATIONS
else:
cmd_type = '22' # CMD_ENABLE_SVC_NOTIFICATIONS
data = {
'host': host,
'cmd_typ': cmd_type,
'cmd_mod': '2',
'btnSubmit': 'Commit',
'service': service,
}
nagios_url = NAGIOS_INSTANCE + '/cmd.cgi'
req_output = do_post_request(nagios_url, http_user, http_password, data)
nagios_request_validation(req_output, host, service, 'enable_notif')
if args['host']:
if args['host'] == 'all':
get_all_hosts_status()
else:
print("get specific {} status".format(args['host']))
if args['service_status']:
selected_service, all_service_status = get_all_service_status()
do_actions(selected_service, all_service_status)