forked from LarsMichelsen/nagios_downtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nagios_downtime.vbs
executable file
·1176 lines (1007 loc) · 49.5 KB
/
nagios_downtime.vbs
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
' ##############################################################################
' nagios_downtime.vbs
'
' Copyright (c) 2005-2015 Lars Michelsen <lm@larsmichelsen.com>
' http://larsmichelsen.com/
'
' Permission is hereby granted, free of charge, to any person
' obtaining a copy of this software and associated documentation
' files (the "Software"), to deal in the Software without
' restriction, including without limitation the rights to use,
' copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the
' Software is furnished to do so, subject to the following
' conditions:
'
' The above copyright notice and this permission notice shall be
' included in all copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
' EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
' OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
' NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
' HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
' WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
' FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
' OTHER DEALINGS IN THE SOFTWARE.
' ##############################################################################
' SCRIPT: nagios_downtime
' AUTHOR: Lars Michelsen <lars@vertical-visions.de>
' DECRIPTION: Sends a HTTP(S)-GET to the nagios web server to
' enter a downtime for a host or service.
' CHANGES:
' 2005-07-11 v0.1 First creation of the script
' |
' |
' changes not tracked in details
' |
' V
' 2006-03-22 v0.6 - Added basic auth support
' - Several doc changes
'
' 2009-10-20 v0.7 - Complete recode according to current perl script
' - Reworked command line parameters
' - Script can handle different Nagios date formats now
' - Script can now delete downtimes when downtime id has been
' saved while scheduling the downtime before
'
' 2009-11-04 v0.8 - Default http/https ports are not added to the url anymore
' - Added option to ignore certificate problems
' - Fixed problem deleting service downtimes
'
' 2010-12-02 v0.8.1 - Fixed / in to \ in path definitions (Thx Ronny Bunke)
' - Modify Messages for Icinga (Thx Ronny Bunke)
'
' 2011-01-26 v0.8.2 - Applied changes to better handle nagios response texts.
' Might fix a problem with deleting downtims (Thx Rob Sampson)
' 2012-03-14 v0.8.3 Big thanks to Olaf Morgenstern for the following points:
' - Added the logEvt procedure to write messages to the
' Windows eventlog
' - Added the -e switch to enable Windows event logging
' - Added logEvt calls for relevant Wscript.echo's
' - Better handling of expired downtimes: If the downtime was
' not found on the nagios server, delete it from the local
' downtime ID savefile. To prevent from deleting downtimes
' on nagios server errors, the procedure getNagiosDowntimeId
' was changed to exit the script on errors.
' - Added the cleanupDowntimeIds procedure to cleanup the
' internal downtime ID savefile
' - Added an additional "clean" mode
' - Reindented code to 4 spaces for each level
' 2012-03-22 v0.8.4 Again thanks to Olaf Morgenstern for improving the script
' - Added clean mode to some remarks and an error message
' - Changed about() function to show "cscript WScript.ScriptName"
' - Corrected indenting of one line
' - In del mode, print more details if downtime could not be
' found on nagios server
' 2012-12-05 v0.9 - Added support for scheduling downtimes via the JSON API of
' Check_MK Multisite
' - Internal recode of variables
' 2013-07-31 v0.10 - Added support for deleting downtimes via Check_MK multisite
' 2015-08-25 v0.11 - Fixed downtime deletion with Check_MK newer than 1.2.7
' ##############################################################################
Option Explicit
Dim ty, webProto, server, webServer, webPort, basePath
Dim user, userPw, authName, nagiosDateFormat, proxyAddress
Dim storeDowntimeIds, downtimePath, downtimeId, downtimeType, downtimeDuration
Dim downtimeComment, debug, version, ignoreCertProblems, evtlog
' ##############################################################################
' Configuration (-> Here you have to set some values!)
' ##############################################################################
' Interface/API to use to set downtimes. Can be set to "nagios" to use the
' default CGI based webinterface or "multisite" to set downtimes via Check_MK
' Multisite
ty = "nagios"
' Protocol for the GET Request, In most cases "http", "https" is also possible
webProto = "http"
' IP or FQDN of Nagios server (example: nagios.domain.de)
server = "localhost"
' IP or FQDN of Nagios web server. In most cases same as $server, if
' empty automaticaly using $server
webServer = ""
' Port of Nagios webserver
' This option is only being recognized when it is not the default port for the
' choosen protocol in "webProto" option
webPort = 80
' Web path to Nagios cgi-bin (example: /nagios/cgi-bin) (NO trailing slash!)
' In case of Icinga this would be "/icinga/cgi-bin" by default
' Or if type is multisite, path to multisite (e.g. /check_mk)
basePath = "/nagios/cgi-bin"
' User to take for authentication and author to enter the downtime (example:
' nagiosadmin). In case of Icinga this would be "icingaadmin" by default
user = "nagiosadmin"
' Password for above user
userPw = "nagiosadmin"
' Name of authentication realm, set in the Nagios .htaccess file
' (example: "Nagios Access")
authName = "Nagios Access"
'
' Nagios CGI specific options
' (only needed when $ty is set to "nagios")
'
' Nagios date format (same like set in value "date_format" in nagios.cfg)
nagiosDateFormat = "us"
' When you have to use a proxy server for access to the nagios server, set the
' URL here. The proxy will be set for this script for the choosen web protocol
' When this is set to 'env', the proxy settings will be read from IE settings
' When this is set to '', the script will use a direct connection
proxyAddress = ""
' When using ssl it may be ok for you to ignore untrusted/expired certificats
' Setting this to 1 all ssl certificate related problems should be ignored
ignoreCertProblems = 0
' Enable fetching and storing the downtime ids for later downtime removal
' The downtime IDs will be stored in a defined temp directory
storeDowntimeIds = 1
' The script will generate temporary files named (<host>.txt or
' <host>-<service>.txt). The files will contain the script internal
' downtime ids and/or the nagios downtime ids.
' These files are needed for later downtime removal
downtimePath = "%temp%"
' Some default options (Usualy no changes needed below this)
' Script internal downtime id for a new downtime
' Using the current timestamp as script internal downtime identifier
' Not important to have the real timestamp but having a uniq counter
' which increases
downtimeId = CLng(DateDiff("s", "01/01/1970 00:00:00", Now) - 3600)
' Default downtime type (1: Host Downtime, 2: Service Downtime)
downtimeType = 1
' Default Downtime duration in minutes
downtimeDuration = 10
' Default Downtime text
downtimeComment = "Downtime-Script"
' Default mode for Windows event logging: off => 0 or on => 1
evtlog = 0
' Default Debugmode: off => 0 or on => 1
debug = 0
' Script version
version = "0.10"
' ##############################################################################
' Don't change anything below, except you know what you are doing.
' ##############################################################################
Dim arg, p, i, oBrowser, oResponse, hostname, service, timeStart, timeEnd, url
Dim help, timeNow, timezone, mode, oFs, oFile, oNetwork, oShell, baseUrl, params
Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0
Const HTTPREQUEST_PROXYSETTING_DIRECT = 1
Const HTTPREQUEST_PROXYSETTING_PROXY = 2
Const FOR_READING = 1
Const FOR_WRITING = 2
Const FOR_APPENDING = 8
Const CREATE_IF_NOT_EXISTS = True
Const HTTPREQUEST_SSLERROR_IGNORE_FLAG = 4
Const HTTPREQUEST_SECURITY_IGNORE_ALL = 13056
' Constants for type of event log entry
const EVENTLOG_SUCCESS = 0
const EVENTLOG_ERROR = 1
const EVENTLOG_WARNING = 2
const EVENTLOG_INFORMATION = 4
const EVENTLOG_AUDIT_SUCCESS = 8
const EVENTLOG_AUDIT_FAILURE = 16
Set oShell = CreateObject("WScript.Shell")
Set oFS = CreateObject("Scripting.FilesystemObject")
hostname = ""
service = ""
url = ""
timeNow = Now
timezone = "local"
mode = "add"
help = 0
Dim urls
Set urls = CreateObject("Scripting.Dictionary")
urls.Add "nagios", CreateObject("Scripting.Dictionary")
urls.Item("nagios").Add "host_downtime", "[baseUrl]/cmd.cgi?cmd_typ=55&cmd_mod=2" & _
"&host=[hostname]&com_author=[user]&com_data=[comment]" & _
"&trigger=0&start_time=[start_time]&end_time=[end_time]" & _
"&fixed=1&childoptions=1&btnSubmit=Commit"
urls.Item("nagios").Add "service_downtime", "[baseUrl]/cmd.cgi?cmd_typ=56&cmd_mod=2" & _
"&host=[hostname]&service=[service]" & _
"&com_author=[user]&com_data=[comment]" & _
"&trigger=0&start_time=[start_time]&end_time=[end_time]" & _
"&fixed=1&btnSubmit=Commit"
urls.Item("nagios").Add "del_host_downtime", "[baseUrl]/cmd.cgi?cmd_typ=78&cmd_mod=2&down_id=[downtime_id]&btnSubmit=Commit"
urls.Item("nagios").Add "del_service_downtime", "[baseUrl]/cmd.cgi?cmd_typ=79&cmd_mod=2&down_id=[downtime_id]&btnSubmit=Commit"
urls.Item("nagios").Add "all_downtimes", "[baseUrl]/extinfo.cgi?type=6"
urls.Add "multisite", CreateObject("Scripting.Dictionary")
urls.Item("multisite").Add "host_downtime", "[baseUrl]/view.py?output_format=json&_transid=-1&" & _
"_do_confirm=yes&_do_actions=yes&_username=[user]&_secret=[password]&" & _
"view_name=hoststatus&host=[hostname]&_down_comment=[comment]&" & _
"_down_from_now=yes&_down_minutes=[duration]"
urls.Item("multisite").Add "service_downtime", "[baseUrl]/view.py?output_format=json&_transid=-1&" & _
"_do_confirm=yes&_do_actions=yes&_username=[user]&_secret=[password]&" & _
"view_name=service&host=[hostname]&service=[service]&" & _
"_down_comment=[comment]&_down_from_now=yes&_down_minutes=[duration]"
urls.Item("multisite").Add "del_host_downtime", "[baseUrl]/view.py?output_format=json&_transid=-1" & _
"&_do_confirm=yes&_do_actions=yes&_username=[user]&_secret=[password]" & _
"&view_name=api_downtimes&_remove_downtimes=Remove&downtime_id=[downtime_id]"
urls.Item("multisite").Add "del_service_downtime", "[baseUrl]/view.py?output_format=json&_transid=-1" & _
"&_do_confirm=yes&_do_actions=yes&_username=[user]&_secret=[password]" & _
"&view_name=api_downtimes&_remove_downtimes=Remove&downtime_id=[downtime_id]"
urls.Item("multisite").Add "all_downtimes", "[baseUrl]/view.py?output_format=json&_transid=-1" & _
"&_do_confirm=yes&_do_actions=yes&_username=[user]&_secret=[password]" & _
"&view_name=api_downtimes"
Dim messages
Set messages = CreateObject("Scripting.Dictionary")
messages.Add "nagios", CreateObject("Scripting.Dictionary")
messages.Item("nagios").Add "success", "Your command request was successfully submitted to Nagios for processing"
messages.Item("nagios").Add "not_authorized", "Sorry, but you are not authorized to commit the specified command."
messages.Item("nagios").Add "no_author", "Author was not entered"
messages.Add "multisite", CreateObject("Scripting.Dictionary")
messages.Item("multisite").Add "success", "Successfully sent 1 commands"
messages.Item("multisite").Add "not_authorized", "Invalid automation secret"
messages.Item("multisite").Add "no_author", "TODO"
' Read all params
i = 0
Do While i < Wscript.Arguments.Count
If WScript.Arguments(i) = "/H" or WScript.Arguments(i) = "-H" or UCase(WScript.Arguments(i)) = "-HOSTNAME" or UCase(WScript.Arguments(i)) = "/HOSTNAME" then
' Hostname: /H, /hostname, -H, -hostname
i = i + 1
If i < Wscript.Arguments.Count Then
hostname = WScript.Arguments(i)
Else
err "No hostname given"
End If
ElseIf WScript.Arguments(i) = "/i" or WScript.Arguments(i) = "-i" or UCase(WScript.Arguments(i) = "-INTERFACE") or UCase(WScript.Arguments(i)) = "/INTERFACE" then
' Type: /i, /interface, -i, -interface
i = i + 1
ty = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/m" or WScript.Arguments(i) = "-m" or UCase(WScript.Arguments(i) = "-MODE") or UCase(WScript.Arguments(i)) = "/MODE" then
' Mode: /m, /mode, -m, -mode
i = i + 1
mode = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/S" or WScript.Arguments(i) = "-S" or UCase(WScript.Arguments(i)) = "/SERVER" or UCase(WScript.Arguments(i)) = "-SERVER" then
' Nagios Server: /S, /server, -S, -server
i = i + 1
server = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/p" or WScript.Arguments(i) = "-p" or UCase(WScript.Arguments(i)) = "/PATH" or UCase(WScript.Arguments(i)) = "-PATH" then
' Nagios CGI Path: /p, /path, -p, -path
i = i + 1
basePath = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/u" or WScript.Arguments(i) = "-u" or UCase(WScript.Arguments(i)) = "/USER" or UCase(WScript.Arguments(i)) = "-USER" then
' Nagios User: /u, /user, -u, -user
i = i + 1
user = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/P" or WScript.Arguments(i) = "-P" or UCase(WScript.Arguments(i)) = "/PASSWORD" or UCase(WScript.Arguments(i)) = "-PASSWORD" then
' Nagios Password: /P, /password, -P, -password
i = i + 1
userPw = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/s" or WScript.Arguments(i) = "-s" or UCase(WScript.Arguments(i)) = "/SERVICE" or UCase(WScript.Arguments(i)) = "-SERVICE" then
' Servicename: /s, /service, -s, -service
i = i + 1
service = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/t" or WScript.Arguments(i) = "-t" or UCase(WScript.Arguments(i)) = "/DOWNTIME" or UCase(WScript.Arguments(i)) = "-DOWNTIME" Then
' downtime duration: /t, /downtime, -t, -downtime
i = i + 1
downtimeDuration = WScript.Arguments(i)
ElseIf WScript.Arguments(i) = "/c" or WScript.Arguments(i) = "-c" or UCase(WScript.Arguments(i)) = "/COMMENT" or UCase(WScript.Arguments(i)) = "-COMMENT" Then
' downtime comment: /c, /comment, -c, -comment
i = i + 1
downtimeComment = WScript.Arguments(i)
ElseIf UCase(WScript.Arguments(i)) = "/E" or UCase(WScript.Arguments(i)) = "-E" or UCase(WScript.Arguments(i)) = "/EVTLOG" or UCase(WScript.Arguments(i)) = "-EVTLOG" Then
' log to Window event log: /e, -e, /evtlog, -evtlog
evtlog = 1
ElseIf UCase(WScript.Arguments(i)) = "/D" or UCase(WScript.Arguments(i)) = "-D" or UCase(WScript.Arguments(i)) = "/DEBUG" or UCase(WScript.Arguments(i)) = "-DEBUG" Then
' debug mode: /d, -d, /debug, -debug
debug = 1
ElseIf WScript.Arguments(i) = "/?" or WScript.Arguments(i) = "-?" or WScript.Arguments(i) = "/h" or WScript.Arguments(i) = "-h" or WScript.Arguments(i) = "-help" or WScript.Arguments(i) = "/help" Then
' help: /?, /h, /help, -?, -h, -help
help = 1
Else
' ....
End If
i = i + 1
Loop
' Read optional config
If oFS.FileExists("nagios_downtime.vbs.conf") Then
ExecuteGlobal(oFS.OpenTextFile("nagios_downtime.vbs.conf").ReadAll())
End If
If help = 1 Then
Call about()
WScript.Quit(1)
End If
' Mode can be add, del or clean, default is "add"
If mode = "" Then
mode = "add"
End If
' Get hostname if not set via param
If hostname = "" Then
' Read the hostname
Set oNetwork = WScript.CreateObject("WScript.Network")
hostname = LCase(oNetwork.ComputerName)
End If
' When no nagios webserver is set the webserver and Nagios should be on the same
' host
If webServer = "" Then
webServer = server
End If
' When a service name is set, this will be a service downtime
If service <> "" Then
downtimeType = 2
End If
' Initialize the port to be added to the url. If default http port (80) or
' default ssl port don't add anything
If webProto = "http" And webPort = 80 Then
webPort = ""
ElseIf webProto = "https" And webPort <> 443 Then
webPort = ""
Else
webPort = ":" & webPort
End If
' Append the script internal downtime id when id storing is enabled
' The downtime ID is important to identify the just scheduled downtime for
' later removal. The CGIs do not provide the downtime id right after sending
' the schedule request. So it is important to tag the downtime with this.
If storeDowntimeIds = 1 Then
downtimeComment = downtimeComment & " (ID:" & downtimeId & ")"
End If
' Expand the environment string in downtime path
If storeDowntimeIds = 1 Then
downtimePath = oShell.ExpandEnvironmentStrings(downtimePath)
End If
' Calculate the start of the downtime
timeStart = gettime(timeNow)
' Calculate the end of the downtime
timeEnd = gettime(DateAdd("n", downtimeDuration, timeNow))
' Check if Nagios web server is reachable via ping, if not, terminate the script
If PingTest(webServer) Then
err "Given Nagios web server """ & webServer & """ not reachable via ping!"
End If
' Initialize the browser
Set oBrowser = CreateObject("WinHttp.WinHttpRequest.5.1")
' Set the proxy address depending on the configured option
If proxyAddress = "env" Then
oBrowser.SetProxy HTTPREQUEST_PROXYSETTING_PRECONFIG
dbg "Proxy-Mode: Env (" & HTTPREQUEST_PROXYSETTING_PRECONFIG & ")"
ElseIf proxyAddress = "" Then
oBrowser.SetProxy HTTPREQUEST_PROXYSETTING_DIRECT
dbg "Proxy-Mode: Direct (" & HTTPREQUEST_PROXYSETTING_DIRECT & ")"
Else
oBrowser.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, proxyAddress
dbg "Proxy-Mode: Proxy (" & HTTPREQUEST_PROXYSETTING_PROXY & "): " & proxyAddress
End If
' When enabled ignore all certificate problems
If ignoreCertProblems = 1 Then
oBrowser.Option(HTTPREQUEST_SSLERROR_IGNORE_FLAG) = HTTPREQUEST_SECURITY_IGNORE_ALL
End If
baseUrl = webProto & "://" & webServer & webPort & basePath
' Handle the given action
Select Case mode
Case "add"
' Add a new scheduled downtime
' ##########################################################################
Set params = CreateObject("Scripting.Dictionary")
params.add "baseUrl", baseUrl
params.add "hostname", hostname
params.add "user", user
params.add "password", userPw
params.add "comment", downtimeComment
params.add "start_time", timeStart
params.add "end_time", timeEnd
params.add "duration", downtimeDuration
If downtimeType = 1 Then
' Schedule Host Downtime
url = get_url("host_downtime", params)
Else
' Schedule Service Downtime
params.add "service", service
url = get_url("service_downtime", params)
End If
dbg "HTTP-GET: " & url
oBrowser.Open "GET", url
setBrowserOptions()
oBrowser.Send
dbg "HTTP-Response (" & oBrowser.Status & "): " & oBrowser.ResponseText
' Handle response code, not in detail, only first char
Select Case Left(oBrowser.Status, 1)
' 2xx response code is OK
Case 2
If InStr(oBrowser.ResponseText, get_msg("success")) > 0 Then
' Save the id of the just scheduled downtime
If storeDowntimeIds = 1 Then
saveDowntimeId()
log EVENTLOG_SUCCESS, "OK: Downtime was submitted successfully"
WScript.Quit(0)
Else
log EVENTLOG_INFORMATION, "Downtime IDs are not set to be stored"
WScript.Quit(1)
End If
ElseIf InStr(oBrowser.ResponseText, get_msg("not_authorized")) > 0 Then
err "Maybe not authorized or wrong host- or servicename"
ElseIf InStr(oBrowser.ResponseText, get_msg("no_author")) > 0 Then
err "No Author entered, define Author in user var"
Else
err "Some undefined error occured, turn debug mode on to view what happened"
End If
Case 3
err "HTTP Response code 3xx says ""moved url"" (" & oBrowser.Status & ")"
Case 4
err "HTTP Response code 4xx says ""client error"" (" & oBrowser.Status & ")" & _
"Hint: This could be caused by wrong auth credentials and/or datetime settings in this script"
Case 5
err "HTTP Response code 5xx says ""server Error"" (" & oBrowser.Status & ")"
Case Else
err "HTTP Response code unhandled by script (" & oBrowser.Status & ")"
End Select
Case "del"
' Delete the last scheduled downtime
' ##########################################################################
If storeDowntimeIds <> 1 Then
err "Unable to remove a downtime. The storingDowntimeIds option is set to disabled."
End If
' Read all internal downtime ids for this host/service
Dim aDowntimes
aDowntimes = getDowntimeIds()
' Only proceed when downtimes found
If UBound(aDowntimes)+1 > 0 Then
' Sort downtimes (lowest number at top)
aDowntimes = bubblesort(aDowntimes)
dbg "Trying to delete with internal downtime id: " & aDowntimes(0)
' Get the nagios downtime id for the last scheduled downtime
Dim nagiosDowntimeId
nagiosDowntimeId = getNagiosDowntimeId(aDowntimes(0))
dbg "Translated downtime id: " & aDowntimes(0) & "(internal) => " & nagiosDowntimeId & " (Nagios)"
If nagiosDowntimeId <> "" Then
deleteDowntime(nagiosDowntimeId)
End If
' We can safely delete the downtime from the list of saved downtimes,
' because getNagiosDowntimeId(aDowntimes(0)) will exit the script if
' it can't get the downtimes from the nagios server.
delDowntimeId(aDowntimes(0))
Else
err "Unable to remove a downtime. No previously scheduled downtime found."
End If
Case "clean"
' Cleanup the stored downtime ids
' ##########################################################################
dbg "Cleanup mode selected."
cleanupDowntimeIds
Case Else
err "Unknown mode was set (Available: add, del, clean)"
WScript.Quit(1)
End Select
Set oBrowser = Nothing
Set oShell = Nothing
Set oFile = Nothing
Set oFS = Nothing
' Regular end of script
' ##############################################################################
' #############################################################
' Subs
' #############################################################
sub dbg(msg)
If debug = 1 Then
log EVENTLOG_INFORMATION, msg
End If
End Sub
sub err(msg)
log EVENTLOG_ERROR, "ERROR: " & msg
WScript.Quit(1)
End Sub
Sub log(logType, msg)
WScript.echo msg
If evtlog = 1 Then
oShell.LogEvent logType, WScript.ScriptName & ":" & VBCRLF & msg
End If
End Sub
Sub setBrowserOptions()
oBrowser.SetRequestHeader "User-Agent", "nagios_downtime.vbs / " & version
dbg "User-Agent: " & "nagios_downtime.vbs / " & version
' Only try to auth if auth informations are given
If authName <> "" And userPw <> "" Then
dbg "Nagios Auth: " & authName
dbg "Nagios User: " & user
dbg "Nagios Password: " & userPw
' Set the login information (0: Server auth / 1: Proxy auth)
oBrowser.SetCredentials user, userPw, 0
End If
End Sub
Function get_url(key, params)
url = urls.Item(ty).Item(key)
Dim k
For Each k In params.Keys
url = Replace(url, "[" & k & "]", params.Item(k))
Next
get_url = url
End Function
Function get_msg(key)
get_msg = messages.Item(ty).Item(key)
End Function
Function bubblesort(arrSort)
Dim i, j, arrTemp
For i = 0 to UBound(arrSort)
For j = i + 1 to UBound(arrSort)
If arrSort(i) < arrSort(j) Then
arrTemp = arrSort(i)
arrSort(i) = arrSort(j)
arrSort(j) = arrTemp
End If
Next
Next
bubblesort = arrSort
End Function
Sub about()
WScript.echo "Usage:" & vbcrlf & vbcrlf & _
"cscript " & WScript.ScriptName & " [-i <interface>] [-m add] [-H <hostname>] [-s <service>] [-t <minutes>]" & vbcrlf & _
" [-S <webserver>] [-p <cgi-bin-path>] [-u <username>]" & vbcrlf & _
" [-p <password>] [-e] [-d]" & vbcrlf & _
"cscript " & WScript.ScriptName & " -m del [-i <interface>] [-H <hostname>] [-s <service>] [-S <webserver>]" & vbcrlf & _
" [-p <cgi-bin-path>] [-u <username>] [-p <password>] [-e] [-d]" & vbcrlf & _
"cscript " & WScript.ScriptName & " -m clean [-i <interface>] [-H <hostname>] [-s <service>] [-S <webserver>]" & vbcrlf & _
" [-p <cgi-bin-path>] [-u <username>] [-p <password>] [-e] [-d]" & vbcrlf & _
"cscript " & WScript.ScriptName & " -h" & vbcrlf & _
"" & vbcrlf & _
"Nagios Downtime Script by Lars Michelsen <lars@vertical-visions.de>" & vbcrlf & _
"Sends a HTTP(S) request to the nagios cgis to add a downtime for a host or" & vbcrlf & _
"service. Since version 0.7 the script can remove downtimes too when being" & vbcrlf & _
"called in ""del"" mode." & vbcrlf & _
"" & vbcrlf & _
"Parameters:" & vbcrlf & _
" -i, --interface Type of interface to be used to set downtimes (nagios or" & vbcrlf & _
" multisite). Defaults to nagios." & vbcrlf & _
" -m, --mode Mode to run the script in (Available: add, del, clean)" & vbcrlf & _
"" & vbcrlf & _
" -H, --hostname Name of the host the downtime should be scheduled for." & vbcrlf & _
" Important: The name must be same as in Nagios." & vbcrlf & _
" -s, --service Name of the service the downtime should be scheduled for." & vbcrlf & _
" Important: The name must be same as in Nagios. " & vbcrlf & _
" When empty or not set a host downtime is being submitted." & vbcrlf & _
" -t, --downtime Duration of the fixed downtime in minutes" & vbcrlf & _
" -c, --comment Comment for the downtime" & vbcrlf & _
" " & vbcrlf & _
" -S, --server Nagios Webserver address (IP or DNS)" & vbcrlf & _
" -p, --path Web path to Nagios cgi-bin (Default: /nagios/cgi-bin)" & vbcrlf & _
" -u, --user Usernate to be used for accessing the CGIs" & vbcrlf & _
" -P, --password Password for accessing the CGIs" & vbcrlf & _
" " & vbcrlf & _
" -e, --evtlog Enable logging to Windows event log " & vbcrlf & _
" -d, --debug Enable debug mode" & vbcrlf & _
" -h, --help Show this message" & vbcrlf & _
"" & vbcrlf & _
"If you call " & WScript.ScriptName & " without parameters the script takes the default" & vbcrlf & _
"options which are hardcoded in the script." & vbcrlf & _
""
End Sub
Sub delDowntimeId(internalId)
Dim file, aDowntimes, id
file = downtimePath & "\"
If downtimeType = 1 Then
file = file & hostname & ".txt"
Else
file = file & hostname & "-" & service & ".txt"
End If
' Read all downtimes to array
Set oFile = oFS.OpenTextfile(file, FOR_READING)
Do While Not oFile.AtEndOfStream
Push aDowntimes, oFile.Readline
Loop
oFile.Close
' Filter downtime
ArrayRemoveVal aDowntimes, internalId
' Write downtimes back to file
Set oFile = oFS.OpenTextfile(file, FOR_WRITING, CREATE_IF_NOT_EXISTS)
For Each id In aDowntimes
dbg "Rewriting id to file: " & id
oFile.Writeline id
Next
oFile.Close
Set oFile = Nothing
End Sub
Sub cleanupDowntimeIds()
Dim aDowntimes, nagiosDowntimeId, count, id
' Read all internal downtime ids for this host/service from file
aDowntimes = getDowntimeIds()
' Only proceed when stored downtime ids found
count = UBound(aDowntimes)
If UBound(aDowntimes)+1 > 0 Then
For Each id In aDowntimes
' Get the nagios downtime id
nagiosDowntimeId = getNagiosDowntimeId(id)
dbg "Translated downtime id: " & id & "(internal) => " & nagiosDowntimeId & " (Nagios)"
If nagiosDowntimeId = "" Then
' no nagios downtime found -> delete the stored internal downtime id
' We can safely delete the downtime from the list of stored downtimes,
' because getNagiosDowntimeId(id) will exit the script if
' it can't get the downtimes from the nagios server.
dbg "Internal downtime id " & id & " not found on nagios server"
dbg "Deleting internal downtime id " & id & " from file"
delDowntimeId(id)
log EVENTLOG_INFORMATION, "Internal downtime id " & id & " deleted from file"
End If
Next
Else
log EVENTLOG_INFORMATION, "INFO: Nothing to do. No stored downtime ids found."
End If
End Sub
Function getDowntimeIds()
Dim file, aDowntimes, sLine, oRegex, oMatches
aDowntimes = Array()
file = downtimePath & "\"
If downtimeType = 1 Then
file = file & hostname & ".txt"
Else
file = file & hostname & "-" & service & ".txt"
End If
Set oRegex = New RegExp
oRegex.Pattern = "[0-9]+"
' Read all downtimes to array
If oFS.FileExists(file) Then
Set oFile = oFS.OpenTextfile(file, FOR_READING)
Do While Not oFile.AtEndOfStream
sLine = oFile.Readline
' Do some validation
If oRegex.Execute(sLine).Count > 0 Then
Push aDowntimes, sLine
End If
Loop
oFile.Close
Else
err "Could not open temporary file (" & file & ")"
WScript.Quit(1)
End If
getDowntimeIds = aDowntimes
End Function
Sub saveDowntimeId()
Dim file
file = downtimePath & "\"
If downtimeType = 1 Then
file = file & hostname & ".txt"
Else
file = file & hostname & "-" & service & ".txt"
End If
dbg "Saving downtime to file: " & file
Set oFile = oFS.OpenTextfile(file, FOR_APPENDING, CREATE_IF_NOT_EXISTS)
oFile.Writeline downtimeId
oFile.Close
' FIXME: Error handling
'err "Could not write downtime to temporary file (" & $file & ")"
'WScript.Quit(1)
End Sub
Function getNagiosDowntimeId(internalId)
getNagiosDowntimeId = ""
Dim aDowntimes, id
' Get all downtimes
aDowntimes = getAllDowntimes()
' Filter the just scheduled downtime
For Each id In aDowntimes
' Matching by:
' - internal id in comment field
' - triggerId: N/A
If id("triggerId") = "N/A" And InStr(id("comment"), "(ID:" & internalId & ")") > 0 Then
dbg "Found matching downtime: " & id("host") & " " & id("service") & " " & id("entryTime") & " " & id("downtimeId")
getNagiosDowntimeId = id("downtimeId")
End If
Next
End Function
Sub deleteDowntime(nagiosDowntimeId)
If nagiosDowntimeId = "" Then
err "Unable to delete downtime. Nagios Downtime ID not given"
End If
Set params = CreateObject("Scripting.Dictionary")
params.add "baseUrl", baseUrl
params.add "user", user
params.add "password", userPw
params.add "downtime_id", nagiosDowntimeId
If downtimeType = 1 Then
' Host downtime
url = get_url("del_host_downtime", params)
Else
' Service downtime
url = get_url("del_service_downtime", params)
End If
dbg "HTTP-GET: " & url
oBrowser.Open "GET", url
setBrowserOptions()
oBrowser.Send
dbg "HTTP-Response (" & oBrowser.Status & "): " & oBrowser.ResponseText
' Handle response code, not in detail, only first char
' Exit the script if we can't get the downtimes from the nagios server
Select Case Left(oBrowser.Status, 1)
' 2xx response code is OK
Case 2
If InStr(oBrowser.ResponseText, get_msg("success")) > 0 Then
log EVENTLOG_SUCCESS, "OK: Downtime (ID: " & nagiosDowntimeId & ") has been deleted"
ElseIf InStr(oBrowser.ResponseText, get_msg("not_authorized")) > 0 Then
err "Maybe not authorized or wrong host- or servicename"
ElseIf InStr(oBrowser.ResponseText, get_msg("no_author")) > 0 Then
err "No Author entered, define Author in user var"
Else
err "Some undefined error occured, turn debug mode on to view what happened"
End If
Case 3
err "HTTP Response code 3xx says ""moved url"" (" & oBrowser.Status & ")"
Case 4
err "HTTP Response code 4xx says ""client error"" (" & oBrowser.Status & ")" & _
"Hint: This could be caused by wrong auth credentials and/or datetime settings in this script"
Case 5
err "HTTP Response code 5xx says ""server Error"" (" & oBrowser.Status & ")"
Case Else
err "HTTP Response code unhandled by script (" & oBrowser.Status & ")"
End Select
End Sub
Function getAllDowntimes()
Dim aDowntimes, oRegex, oMatches, oDict
aDowntimes = Array()
' Url to downtime page
Set params = CreateObject("Scripting.Dictionary")
params.add "baseUrl", baseUrl
params.add "user", user
params.add "password", userPw
url = get_url("all_downtimes", params)
dbg "HTTP-GET: " & url
' Fetch information via HTTP-GET
oBrowser.Open "GET", url
setBrowserOptions()
oBrowser.Send
dbg "HTTP-Response (" & oBrowser.Status & "): " & oBrowser.ResponseText
' Handle response code, not in detail, only first char
' Exit on error
Select Case Left(oBrowser.Status, 1)
' 2xx response code is OK
Case 2
dbg "OK: Got downtime response from nagios server"
Case 3
err "HTTP Response code 3xx says ""moved url"" (" & oBrowser.Status & ")"
Case 4
err "HTTP Response code 4xx says ""client error"" (" & oBrowser.Status & ")" & VBCRLF & _
"Hint: This could be caused by wrong auth credentials and/or datetime settings in this script"
Case 5
err "HTTP Response code 5xx says ""server Error"" (" & oBrowser.Status & ")"
Case Else
err "HTTP Response code unhandled by script (" & oBrowser.Status & ")"
End Select
If ty = "nagios" Then
Set oRegex = New RegExp
oRegex.IgnoreCase = True
' Parse all downtimes to an array
Dim lineType, sLine
lineType = ""
' Removed vbCrLf here
For Each sLine In Split(oBrowser.ResponseText, vblf)
' Filter only downtime lines
oRegex.Pattern = "CLASS=\'downtime(Odd|Even)"
Set oMatches = oRegex.Execute(sLine)
If oMatches.Count > 0 Then
lineType = "downtime" & oMatches(0).SubMatches(0)
oRegex.Pattern = "<tr\sCLASS=\'" & lineType & "\'><td\sCLASS=\'" & lineType & _
"\'><A\sHREF=\'extinfo\.cgi\?type=1&host=([^\']+)\'>[^<]+<\/A>" & _
"<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & _
lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)" & _
"<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & _
lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)" & _
"<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & _
lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td>"
Set oMatches = oRegex.Execute(sLine)
If oMatches.Count > 0 Then
' Host downtime:
' <tr CLASS='downtimeEven'><td CLASS='downtimeEven'><A HREF='extinfo.cgi?type=1&host=dev.nagvis.org'>dev.nagvis.org</A></td><td CLASS='downtimeEven'>10-13-2009 09:15:35</td><td CLASS='downtimeEven'>Nagios Admin</td><td CLASS='downtimeEven'>Perl Downtime-Script</td><td CLASS='downtimeEven'>01-10-2010 09:15:35</td><td CLASS='downtimeEven'>01-10-2010 09:25:35</td><td CLASS='downtimeEven'>Fixed</td><td CLASS='downtimeEven'>0d 0h 10m 0s</td><td CLASS='downtimeEven'>9</td><td CLASS='downtimeEven'>N/A</td>
Set oDict = CreateObject("Scripting.Dictionary")
dbg "Found host downtime:" & _
"Host: " & oMatches(0).SubMatches(0) & _
" EntryTime: " & oMatches(0).SubMatches(1) & _
" User: " & oMatches(0).SubMatches(2) & _
" Comment: " & oMatches(0).SubMatches(3) & _
" Start: " & oMatches(0).SubMatches(4) & _
" End: " & oMatches(0).SubMatches(5) & _
" Type: " & oMatches(0).SubMatches(6) & _
" Duration: " & oMatches(0).SubMatches(7) & _
" DowntimeID: " & oMatches(0).SubMatches(8) & _
" TriggerID: " & oMatches(0).SubMatches(9)
oDict.Add "host", oMatches(0).SubMatches(0)
oDict.Add "service", ""
oDict.Add "entryTime", oMatches(0).SubMatches(1)
oDict.Add "user", oMatches(0).SubMatches(2)
oDict.Add "comment", oMatches(0).SubMatches(3)
oDict.Add "start", oMatches(0).SubMatches(4)
oDict.Add "end", oMatches(0).SubMatches(5)
oDict.Add "type", oMatches(0).SubMatches(6)
oDict.Add "duration", oMatches(0).SubMatches(7)
oDict.Add "downtimeId", oMatches(0).SubMatches(8)
oDict.Add "triggerId", oMatches(0).SubMatches(9)
' Push to array
ReDim Preserve aDowntimes(UBound(aDowntimes) + 1)
Set aDowntimes(UBound(aDowntimes)) = oDict
Else
oRegex.Pattern = "<tr\sCLASS=\'" & lineType & "\'><td\sCLASS=\'" & lineType & _
"\'><A\sHREF=\'extinfo\.cgi\?type=1&host=([^\']+)\'>[^<]+" & _
"<\/A><\/td><td\sCLASS=\'" & lineType & "\'><A\sHREF=\'" & _
"extinfo\.cgi\?type=2&host=[^\']+&service=([^\']+)\'>[^<]+" & _
"<\/A><\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td>" & _
"<td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & _
lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & lineType & "\'>" & _
"([^<]+)<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td>" & _
"<td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & _
lineType & "\'>([^<]+)<\/td><td\sCLASS=\'" & lineType & "\'>" & _
"([^<]+)<\/td><td\sCLASS=\'" & lineType & "\'>([^<]+)<\/td>"
Set oMatches = oRegex.Execute(sLine)
If oMatches.Count > 0 Then
' Service downtime:
' <tr CLASS='downtimeEven'><td CLASS='downtimeEven'><A HREF='extinfo.cgi?type=1&host=dev.nagvis.org'>dev.nagvis.org</A></td><td CLASS='downtimeEven'><A HREF='extinfo.cgi?type=2&host=dev.nagvis.org&service=HTTP'>HTTP</A></td><td CLASS='downtimeEven'>10-13-2009 10:28:30</td><td CLASS='downtimeEven'>Nagios Admin</td><td CLASS='downtimeEven'>test</td><td CLASS='downtimeEven'>10-13-2009 10:28:11</td><td CLASS='downtimeEven'>10-13-2009 12:28:11</td><td CLASS='downtimeEven'>Fixed</td><td CLASS='downtimeEven'>0d 2h 0m 0s</td><td CLASS='downtimeEven'>145</td><td CLASS='downtimeEven'>N/A</td>
Set oDict = CreateObject("Scripting.Dictionary")
dbg "Found service downtime:" & _
"Host: " & oMatches(0).SubMatches(0) & _
" Service: " & oMatches(0).SubMatches(1) & _
" EntryTime: " & oMatches(0).SubMatches(2) & _
" User: " & oMatches(0).SubMatches(3) & _
" Comment: " & oMatches(0).SubMatches(4) & _
" Start: " & oMatches(0).SubMatches(5) & _
" End: " & oMatches(0).SubMatches(6) & _
" Type: " & oMatches(0).SubMatches(7) & _
" Duration: " & oMatches(0).SubMatches(8) & _
" DowntimeID: " & oMatches(0).SubMatches(9) & _
" TriggerID: " & oMatches(0).SubMatches(10)
oDict.Add "host", oMatches(0).SubMatches(0)
oDict.Add "service", oMatches(0).SubMatches(1)
oDict.Add "entryTime", oMatches(0).SubMatches(2)
oDict.Add "user", oMatches(0).SubMatches(3)
oDict.Add "comment", oMatches(0).SubMatches(4)
oDict.Add "start", oMatches(0).SubMatches(5)
oDict.Add "end", oMatches(0).SubMatches(6)
oDict.Add "type", oMatches(0).SubMatches(7)
oDict.Add "duration", oMatches(0).SubMatches(8)
oDict.Add "downtimeId", oMatches(0).SubMatches(9)
oDict.Add "triggerId", oMatches(0).SubMatches(10)
' Push to array
ReDim Preserve aDowntimes(UBound(aDowntimes) + 1)
Set aDowntimes(UBound(aDowntimes)) = oDict
End If
End If
End If
Next
ElseIf ty = "multisite" Then
' basic, simple json parsing
Dim parsed, row
parsed = parseMultisiteData(oBrowser.ResponseText)