forked from zorkian/nagios-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nagios-cli
executable file
·737 lines (562 loc) · 24 KB
/
nagios-cli
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
#!/usr/bin/env python
'''usage: %prog <config> <command> [command-options]
This script uses the JSON Nagios API to issue commands to Nagios. The
goal is to make your life easier. If it doesn't, please return it
unharmed and let me know what went wrong and I'll make it better.
Usage:
nagios-cli --host=nagios --port=6315 <command> [command-options]
This is the prefix. I recommend you stash this in an alias so you don't
have to type in the host/port every time. From now on in this page, I
will assume that 'nagios-cli' will do the right thing and leave out the
host/port arguments.
This tool operates like git, svn, and other tools you may now -- you
invoke it, tell it what command to run, and then the rest of the
arguments vary depending on the command. Some tools don't take any
options, some take a few required arguments and then some.
Status Viewing
nagios-cli hosts
nagios-cli services <host>
Notification Management
nagios-cli disable-notifications <host> [service] [--recursive|r]
nagios-cli enable-notifications <host> [service] [--recursive|r]
Active Checks Management
nagios-cli disable-checks <host> [service] [--recursive|r]
nagios-cli enable-checks <host> [service] [--recursive|r]
Downtime Management
nagios-cli schedule-downtime <host> [service] <duration>
[--recursive|-r] [--author|-a=TEXT] [--comment|-c=TEXT]
nagios-cli cancel-downtime <host> [service] [--recursive|-r]
Problem Management
nagios-cli acknowledge-problem <host> [service] <--comment|-c=TEXT>
[--sticky|-s=TRUE|false] [--notify|-n=TRUE|false]
[--persistent|-p=true|FALSE] [--author|-a=TEXT]
Copyright 2011-2013 by Bump Technologies, Inc and other authors and
contributors. See the LICENSE file for full licensing information.
'''
import re
import requests
import sys
from json import loads, dumps
from optparse import OptionParser, OptionGroup
URL = None # To the Nagios API "http://foo:6315"
NAGIOS = {} # Host => [ Service, Service, Service, ... ]
def time_to_seconds(inp):
'''Possibly convert a time written like "2h" or "50m" into seconds.
'''
match = re.match(r'^(\d+)([wdhms])?$', inp)
if match is None:
return None
val, denom = match.groups()
if denom is None:
return int(val)
multiplier = {'w': 604800, 'd': 86400, 'h': 3600, 'm': 60, 's': 1}[denom]
return int(val) * multiplier
def consume_host_service(args):
'''Given a list of arguments, attempt to consume a host and service
off of the front and return a list containing host=X service=X args
that you can send to the API.
'''
global NAGIOS
if args is None or len(args) <= 0:
return None
if args[0] not in NAGIOS:
return None
host = args[0]
selargs = ['host=%s' % host]
del args[0]
if len(args) > 0 and args[0].decode('utf-8') in NAGIOS[host]:
selargs += ['service=%s' % args[0].decode('utf-8')]
del args[0]
return selargs
def api(args):
'''Send a call out to the API. Returns the response object (dict) or
an integer exit code on failure.
'''
global URL, NAGIOS
# The rest of the data is now in args, build the URL
verb = args[0]
objid = args[1] if len(args) >= 2 and args[1].isdigit() else ''
url = '%s/%s/%s' % (URL, verb, objid)
# Now build the reqobj
obj = {}
for kv in args[2 if objid else 1:]:
if not '=' in kv:
return critical('Parameter "%s" does not conform to expected key=value format' % kv)
key, value = kv.split('=', 1)
obj[key] = value
# Set the method to POST if we recognize the verb or if there is a payload
method = 'POST' if len(obj) > 0 else 'GET'
if verb in ('cancel_downtime'):
method = 'POST'
payload = dumps(obj) if method == 'POST' else None
try:
if payload is None:
if AUTH :
res = requests.get(url, auth=(USER,PASSWORD))
else:
res = requests.get(url)
else:
if AUTH :
res = requests.post(url, data=payload, auth=(USER,PASSWORD),
headers={'Content-Type': 'application/json'})
else:
res = requests.post(url, data=payload,
headers={'Content-Type': 'application/json'})
except (requests.ConnectionError, requests.Timeout):
return critical('Failed connecting to nagios-api server')
if res is None:
return critical('Failed requesting resource')
if res.status_code == 401:
return critical('User and or password provided are incorrect')
# Probably a JSON response, get it
try:
if (res.headers['content-encoding'] == "gzip"):
resobj = loads(res.content)
else:
resobj = loads(res.text)
except ValueError:
return critical('Failed parsing server response')
except TypeError:
return critical('Failed parsing JSON in server response')
return resobj
def do_schedule_downtime(cmd, args, opts):
'''Create a scheduled downtime for a host or service. Usage:
%prog schedule-downtime <host> [service] <duration> [opts]
host must be a hostname that Nagios knows about. If specified,
service is a service that exists on that host. This combination of
host and optional service indicates what you want the downtime to be
scheduled on.
The duration must be of the format like "2h". You can use w, d, h,
m, or s as units. Seconds are assumed if you don't specify the units.
Available options:
--recursive Schedule downtime for all services on this host.
You must not specify a specific service.
--author=NAME Specify an author to record this downtime for.
--comment=TEXT Leave descriptive text about the downtime.
Example:
%prog schedule-downtime web01 2h
# schedule two hours of downtime for web01
%prog schedule-downtime web01 "PING Check" 1w
# schedule one week of downtime for PING Check on web01
%prog schedule-downtime web03 1d --recursive
# schedule one day of downtime for web03 and ALL services on it
NOTE: This command schedules a fixed downtime that starts
immediately and lasts for the specified duration.
'''
p = OptionParser(usage=trim(do_schedule_downtime.__doc__))
p.disable_interspersed_args()
p.add_option('-a', '--author', dest='author', metavar='NAME',
help='Author to blame for this downtime')
p.add_option('-c', '--comment', dest='comment', metavar='TEXT',
help='Explanatory comment to leave on the downtime')
p.add_option('-r', '--recursive', dest='recursive', action='store_true',
help='Schedule for all services on the given host')
p.set_defaults(recursive=False, author=None, comment=None)
selargs = consume_host_service(args)
if selargs is None:
p.error('Failed to locate host/service to schedule downtime for')
if len(args) <= 0:
p.error('Must specify a duration in a format like "2h"')
secs = time_to_seconds(args[0])
if secs is None:
p.error('Invalid duration, must be in a format like "2h"')
selargs += ['duration=%d' % secs]
(options, args) = p.parse_args(opts)
if options.recursive:
selargs += ['services_too=true']
if options.author is not None:
selargs += ['author=%s' % options.author]
if options.comment is not None:
selargs += ['comment=%s' % options.comment]
res = api(['schedule_downtime'] + selargs)
if isinstance(res, int):
return res
if not isinstance(res, dict):
return critical('API returned unknown object type')
if not res['success']:
return critical('Failed: %s' % res['content'])
return 0
def do_cancel_downtime(cmd, args, opts):
'''Cancel a scheduled downtime for a host or service. Usage:
%prog cancel-downtime <host> [service] [opts]
host must be a hostname that Nagios knows about. If specified,
service is a service that exists on that host. This combination of
host and optional service indicates what you want the downtime to be
cancelled from.
Available options:
--recursive Cancel downtime for all services on this host.
You must not specify a specific service.
Example:
%prog cancel-downtime web01
# cancel downtime for web01
%prog cancel-downtime web01 "PING Check"
# cancel downtime for PING Check on web01
%prog cancel-downtime web03 --recursive
# cancel downtime for web03 and ALL services on it
NOTE: If you have just scheduled the downtime through the API, note
that it may take a little while before you can cancel it. Nagios
is not instant and it may not write out the status file (with the
downtime id) for some time.
'''
p = OptionParser(usage=trim(do_cancel_downtime.__doc__))
p.disable_interspersed_args()
p.add_option('-r', '--recursive', dest='recursive', action='store_true',
help='Cancel for all services on the given host')
p.set_defaults(recursive=False, author=None, comment=None)
selargs = consume_host_service(args)
if selargs is None:
p.error('Failed to locate host/service to cancel downtime for')
(options, args) = p.parse_args(opts)
if options.recursive:
selargs += ['services_too=true']
res = api(['cancel_downtime'] + selargs)
if isinstance(res, int):
return res
if not isinstance(res, dict):
return critical('API returned unknown object type')
if not res['success']:
return critical('Failed: %s' % res['content'])
return 0
def do_disable_notifications(cmd, args, opts):
'''Disable notifications for a host or service. Usage:
%prog disable-notifications <host> [service] [opts]
host must be a hostname that Nagios knows about. If specified,
service is a service that exists on that host.
Available options:
--recursive Target the host and all services on this host.
You must not specify a specific service.
Example:
%prog disable-notifications web01
# disable for for web01
%prog disable-notifications web01 "PING Check"
# disable for PING Check on web01
%prog disable-notifications web03 --recursive
# disable for web03 and ALL services on it
'''
p = OptionParser(usage=trim(do_disable_notifications.__doc__))
p.disable_interspersed_args()
p.add_option('-r', '--recursive', dest='recursive', action='store_true',
help='Disable for all services on the given host')
p.set_defaults(recursive=False, author=None, comment=None)
selargs = consume_host_service(args)
if selargs is None:
p.error('Failed to locate host/service to act on')
(options, args) = p.parse_args(opts)
if options.recursive:
selargs += ['services_too=true']
res = api(['disable_notifications'] + selargs)
if isinstance(res, int):
return res
if not isinstance(res, dict):
return critical('API returned unknown object type')
if not res['success']:
return critical('Failed: %s' % res['content'])
return 0
def do_enable_notifications(cmd, args, opts):
'''Re-enable notifications for a host or service. Usage:
%prog enable-notifications <host> [service] [opts]
host must be a hostname that Nagios knows about. If specified,
service is a service that exists on that host.
Available options:
--recursive Target the host and all services on this host.
You must not specify a specific service.
Example:
%prog enable-notifications web01
# enable for for web01
%prog enable-notifications web01 "PING Check"
# enable for PING Check on web01
%prog enable-notifications web03 --recursive
# enable for web03 and ALL services on it
'''
p = OptionParser(usage=trim(do_enable_notifications.__doc__))
p.disable_interspersed_args()
p.add_option('-r', '--recursive', dest='recursive', action='store_true',
help='Enable for all services on the given host')
p.set_defaults(recursive=False, author=None, comment=None)
selargs = consume_host_service(args)
if selargs is None:
p.error('Failed to locate host/service to act on')
(options, args) = p.parse_args(opts)
if options.recursive:
selargs += ['services_too=true']
res = api(['enable_notifications'] + selargs)
if isinstance(res, int):
return res
if not isinstance(res, dict):
return critical('API returned unknown object type')
if not res['success']:
return critical('Failed: %s' % res['content'])
return 0
def do_disable_checks(cmd, args, opts):
'''Disable checks for a host or service. Usage:
%prog disable-checks <host> [service] [opts]
host must be a hostname that Nagios knows about. If specified,
service is a service that exists on that host.
Available options:
--recursive Target the host and all services on this host.
You must not specify a specific service.
Example:
%prog disable-checks web01
# disable for for web01
%prog disable-checks web01 "PING Check"
# disable for PING Check on web01
%prog disable-checks web03 --recursive
# disable for web03 and ALL services on it
'''
p = OptionParser(usage=trim(do_disable_checks.__doc__))
p.disable_interspersed_args()
p.add_option('-r', '--recursive', dest='recursive', action='store_true',
help='Disable for all services on the given host')
p.set_defaults(recursive=False, author=None, comment=None)
selargs = consume_host_service(args)
if selargs is None:
p.error('Failed to locate host/service to act on')
(options, args) = p.parse_args(opts)
if options.recursive:
selargs += ['services_too=true']
res = api(['disable_checks'] + selargs)
if isinstance(res, int):
return res
if not isinstance(res, dict):
return critical('API returned unknown object type')
if not res['success']:
return critical('Failed: %s' % res['content'])
return 0
def do_enable_checks(cmd, args, opts):
'''Re-enable checks for a host or service. Usage:
%prog enable-checks <host> [service] [opts]
host must be a hostname that Nagios knows about. If specified,
service is a service that exists on that host.
Available options:
--recursive Target the host and all services on this host.
You must not specify a specific service.
Example:
%prog enable-checks web01
# enable for for web01
%prog enable-checks web01 "PING Check"
# enable for PING Check on web01
%prog enable-checks web03 --recursive
# enable for web03 and ALL services on it
'''
p = OptionParser(usage=trim(do_enable_checks.__doc__))
p.disable_interspersed_args()
p.add_option('-r', '--recursive', dest='recursive', action='store_true',
help='Enable for all services on the given host')
p.set_defaults(recursive=False, author=None, comment=None)
selargs = consume_host_service(args)
if selargs is None:
p.error('Failed to locate host/service to act on')
(options, args) = p.parse_args(opts)
if options.recursive:
selargs += ['services_too=true']
res = api(['enable_checks'] + selargs)
if isinstance(res, int):
return res
if not isinstance(res, dict):
return critical('API returned unknown object type')
if not res['success']:
return critical('Failed: %s' % res['content'])
return 0
def do_acknowledge_problem(cmd, args, opts):
'''Acknowledge problem for a host or service. Usage:
%prog acknowledge-problem <host> [service] --comment=TEXT [opts]
host must be a hostname that Nagios knows about. If specified,
service is a service that exists on that host. Comment must be specified.
Available options:
--comment=TEXT Comment on the acknowledged problem.
--sticky=TRUE/FALSE [defaults to TRUE] If sticky, an acknowledgement hangs around
until a host reaches "OK" - otherwise, it goes away on next
state change.
--notify=TRUE/FALSE [defaults to TRUE] If TRUE, sends notification that an
acknowledgement has occurred.
--persistent=TRUE/FALSE [defaults to FALSE] If TRUE, the comment will remain after the
host returns to "OK" state.
--author=STR [defaults to "nagios-api"] Who is doing the acknowledging.
Example:
%prog acknowledge-problem web01 --comment="Critical Failure"
# acknowledge problem for web01 with comment "Critical Failure"
%prog acknowledge-problem web03 "HTTP" --comment="Critical Failure"
# acknowledge problem on HTTP service for web03 with comment "Critical Failure"
'''
p = OptionParser(usage=trim(do_acknowledge_problem.__doc__))
p.disable_interspersed_args()
p.add_option('-c', '--comment', dest='comment', action='store',
help="Comment on the acknowledged problem.")
p.add_option('-s', '--sticky', dest='sticky', action='store_false',
help='Does acknowledgement hang around until "OK" reached by host?')
p.add_option('-n', '--notify', dest='notify', action='store_false',
help='Should we send a notification of the acknowledgment?')
p.add_option('-p', '--persistent', dest='persistent', action='store_true',
help='Should the comment hang around after the problem expires?')
p.add_option('-a', '--author', dest='author', action='store',
help='Name appearing for who does the acknowledgment.')
p.set_defaults(sticky=True,notify=True,persistent=False,author=None)
selargs = consume_host_service(args)
if selargs is None:
p.error('Failed to locate host/service to act on')
(options, args) = p.parse_args(opts)
if options.comment:
selargs += ['comment=%s' % options.comment]
else:
return critical('Did not include comment when required!')
if options.sticky is not True:
selargs += ['sticky=FALSE']
if options.notify is not True:
selargs += ['notify=FALSE']
if options.persistent:
selargs += ['persistent=TRUE']
if options.author:
selargs += ['author=%s' % options.author]
res = api(['acknowledge_problem'] + selargs)
if isinstance(res, int):
return res
if not isinstance(res, dict):
return critical('API returned unknown object type')
if not res['success']:
return critical('Failed: %s' % res['content'])
return 0
def do_hosts(cmd, args, opts):
'''Return a plain list of all hosts.
'''
global NAGIOS
for host in NAGIOS:
print host
return 0
def do_services(cmd, args, opts):
'''For a given host, return all services. Usage:
%prog services <host>
Specify the host you wish to view the services of.
'''
global NAGIOS
p = OptionParser(usage=trim(do_services.__doc__))
if len(args) <= 0 or args[0] not in NAGIOS:
p.error('First argument must be a valid hostname')
for svc in NAGIOS[args[0]]:
print svc
return 0
def critical(msg, retval=1):
'''Print a message to STDERR and return a failure code.
'''
print >>sys.stderr, msg
return retval
def do_raw(args):
'''Allows the user to interact with the API directly and use this
CLI as a JSON generator. Please know what you're doing.
'''
resobj = api(args)
if isinstance(resobj, int):
return resobj
if not isinstance(resobj, dict):
return critical('API returned unknown object type')
# Protocol failure check
if not resobj['success']:
return critical('Failure: %s' % resobj['content'])
# These are simple responses, we can handle them here
if type(resobj['content']) is str:
print resobj['content']
else:
print dumps(resobj['content'])
return 0
def trim(docstring):
'''This is taken from PEP 257 for docstring usage. I'm duplicating
it here so I can use it to preparse docstrings before sending them
to OptionParser. Otherwise, I can either not indent my docstrings
(in violation of the PEP) or I can have the usage outputs be
indented.
'''
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
def main(argv):
'''Where the fun begins. Actually do something useful.
'''
global URL, NAGIOS, AUTH, USER, PASSWORD
# Parse out command line options
p = OptionParser(usage=trim(__doc__))
p.disable_interspersed_args()
p.add_option('-H', '--host', dest='host', default='localhost',
help='Host to connect to', metavar='HOST')
p.add_option('-p', '--port', dest='port', type='int', default=6315,
help='Port to connect to', metavar='PORT')
p.add_option('-U', '--user', dest='user',
help='User to connect with', metavar='USER')
p.add_option('-P', '--password', dest='password',
help='Password to connect with', metavar='PASSWORD')
p.add_option('-u', '--url', dest='url',
help='URL to use instead of host:port', metavar='URL')
p.add_option('--raw', dest='raw', action='store_true',
help='Enable raw mode for the CLI')
(opts, args) = p.parse_args(argv[1:])
if opts.url:
URL = opts.url
else:
URL = 'http://%s:%d' % (opts.host, opts.port)
if opts.user is not None and opts.password is not None:
AUTH = True
USER = opts.user
PASSWORD = opts.password
else:
AUTH = False
# If no more arguments, show usage
if len(args) <= 0:
p.error('No command specified')
# Now load the state of the world (cache this locally?)
temp = api(['objects'])
if isinstance(temp, dict):
if not temp['success']:
return critical('Failed to load objects from nagios-api')
NAGIOS = temp['content']
else:
return temp
# If we're in raw mode, bail out for that now
if opts.raw:
return do_raw(args)
# args will now contain the subcommand, some positional arguments,
# and then the dashed options. Split them.
command, posargs, otherargs = args[0], [], []
for arg in args[1:]:
if len(otherargs) > 0:
otherargs.append(arg)
continue
if arg[0] == '-':
otherargs.append(arg)
else:
posargs.append(arg)
# Dispatch table and then dispatch
dispatch = {
'schedule-downtime': do_schedule_downtime,
'cancel-downtime': do_cancel_downtime,
'enable-notifications': do_enable_notifications,
'disable-notifications': do_disable_notifications,
'enable-checks': do_enable_checks,
'disable-checks': do_disable_checks,
'acknowledge-problem': do_acknowledge_problem,
'hosts': do_hosts,
'services': do_services,
}
for cmd in dispatch:
if re.match(r'^' + command, cmd):
return dispatch[cmd](command, posargs, otherargs)
p.error('Command not found, see the usage')
if __name__ == '__main__':
sys.exit(main(sys.argv[0:]))