WebSVN - scripts - Blame - Rev 5 - /perl/trunk/v1.0/nagios_mass_downtime.pl

thorko Repositories scripts

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 guest 1
#!/usr/bin/perl -w
2
# ##############################################################################
3
# Copyright (c) 2007,2008 Lars Michelsen http://www.vertical-visions.de
4
#
5
# Permission is hereby granted, free of charge, to any person
6
# obtaining a copy of this software and associated documentation
7
# files (the "Software"), to deal in the Software without
8
# restriction, including without limitation the rights to use,
9
# copy, modify, merge, publish, distribute, sublicense, and/or sell
10
# copies of the Software, and to permit persons to whom the
11
# Software is furnished to do so, subject to the following
12
# conditions:
13
#
14
# The above copyright notice and this permission notice shall be
15
# included in all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24
# OTHER DEALINGS IN THE SOFTWARE.
25
# ##############################################################################
26
# SCRIPT:       nagios_downtime
27
# AUTHOR:       Lars Michelsen
28
# DECRIPTION:   Sends a HTTP(S)-GET to the nagios web server to
29
#                     enter a downtime for a host or service.
30
# CHANGES IN 0.4:
31
# 19.05.2008    - Some code formating
32
#               - The downtime type is now automaticaly detected on given params
33
#               - Changed case of the parameters
34
#               - Added proxy configuration options
35
#               - User Agent is now "nagios_downtime.pl / <version>"
36
#               - Added parameter -S and -p for setting server options via param
37
# CHANGES IN 0.5:
38
# changes made by thorko
39
# 20.05.2011    - Added option for multiple hosts
40
#               - Added option for setting a start time of downtime
41
#
42
# $Id$
43
# ##############################################################################
44
 
45
# ##############################################################################
46
# Configuration (-> Here you have to set some values!)
47
# ##############################################################################
48
 
49
# Protocol for the GET Request, In most cases "http", "https" is also possible
50
my $nagiosWebProto = "http";
51
# IP or FQDN of Nagios server (example: nagios.domain.de)
52
my $nagiosServer = "my nagios server";
53
# IP or FQDN of Nagios web server. In most cases same as $nagiosServer, if
54
# empty automaticaly using $nagiosServer
55
#my $nagiosWebServer = "my web server";
56
my $nagiosWebServer = "";
57
# Port of Nagios webserver (If $nagiosWebProto is set to https, this should be
58
# SSL Port 443)
59
my $nagiosWebPort = 80;
60
# Web path to Nagios cgi-bin (example: /nagios/cgi-bin) (NO trailing slash!)
61
my $nagiosCgiPath = "/nagios/cgi-bin";
62
# User to take for authentication and author to enter the downtime (example:
63
# nagiosadmin)
64
my $nagiosUser = "myuser";
65
# Password for above user
66
my $nagiosUserPw = "somepw";
67
# Name of authentication realm, set in the Nagios .htaccess file 
68
# (example: "Nagios Access")
69
my $nagiosAuthName = "Nagios Access";
70
# Nagios date format (same like set in value "date_format" in nagios.cfg)
71
my $nagiosDateFormat = "iso8601";
72
# When you have to use a proxy server for access to the nagios server, set the
73
# URL here. The proxy will be set for this script for the choosen web protocol
74
# When this is set to 'env', the proxy settings will be read from the env.
75
my $proxyAddress = 'http://172.19.4.18:8080';
76
 
77
# Some default options (Usualy no changes needed below this)
78
 
79
# Default downtime type (1: Host Downtime, 2: Service Downtime)
80
my $downtimeType = 1;
81
# Default Downtime duration in minutes
82
my $downtimeDuration = 10;
83
# Default Downtime text
84
my $downtimeComment = "Perl Downtime-Script";
85
# Default Debugmode: off => 0 or on => 1
86
my $debug = 0;
87
# Script version
88
my $version = "0.5";
89
 
90
# ##############################################################################
91
# Don't change anything below, except you know what you are doing.
92
# ##############################################################################
93
 
94
use strict;
95
use warnings;
96
use Net::Ping;
97
use LWP 5.64;
98
use Sys::Hostname;
99
use Getopt::Long;
100
use Switch;
101
 
102
my $arg;
103
my $p;
104
my $i = 0;
105
my $oBrowser;
106
my $oResponse;
107
my $hostname = "";
108
my $service = "";
109
my $start;
110
my $starttime;
111
my $end;
112
my $url = "";
113
my $help = "";
114
 
115
Getopt::Long::Configure('bundling');
116
GetOptions(
117
        "h|help" => \$help,
118
        "d|debug"   => \$debug,
119
        "H|hostname=s" => \$hostname,
120
        "S|server=s" => \$nagiosServer,
121
        "p|path=s" => \$nagiosCgiPath,
122
        "b|starttime=s" => \$starttime,
123
        "t|downtime=i" => \$downtimeDuration,
124
        "c|comment=s" => \$downtimeComment,
125
        "s|service=s" => \$service);
126
 
127
if($help) {
128
        about();
129
        exit(0);
130
}
131
 
132
# Get hostname if not set via param
133
if($hostname eq "") {
134
        $hostname = hostname;
135
}
136
 
137
# When no nagios webserver is set the webserver and Nagios should be on the same
138
# host 
139
if($nagiosWebServer eq "") {
140
        $nagiosWebServer = $nagiosServer;
141
}
142
 
143
# When a service name is set, this will be a service downtime
144
if($service ne "") {
145
        $downtimeType = 2;
146
}
147
 
148
# set time
149
if($starttime eq "") {
150
        # Calculate the start of the downtime
151
        $start = gettime(time+60);
152
} else {
153
        my @time = split(/#/,$starttime);
154
        $start = $time[0]." ".$time[1];
155
}
156
 
157
# Calculate the end of the downtime
158
$end = gettime(time+$downtimeDuration*60);
159
 
160
 
161
# split hosts and set a downtime for all of it
162
my @hosts = split(/,/, $hostname);
163
 
164
foreach my $host (@hosts) {
165
         print "#" x 20;
166
         print "\nSetting downtime for $host\n";
167
# Check if Nagios web server is reachable via ping, if not, terminate the script
168
#$p = Net::Ping->new();
169
#if(!$p->ping($nagiosWebServer)) {
170
        # Nagios web server is not pingable
171
#       print "ERROR: Given Nagios web server \"" . $nagiosWebServer . "\" not reachable via ping\n";
172
#       exit(1);
173
#} else {
174
        # initialize browser
175
        $oBrowser = LWP::UserAgent->new(keep_alive => 1,timeout => 10);
176
        $oBrowser->agent("nagios_downtime.pl / " . $version);
177
 
178
        # Set the proxy address depending on the configured option
179
        if($proxyAddress eq 'env') {
180
                $oBrowser->env_proxy = 1;
181
        } else {
182
                $oBrowser->proxy([$nagiosWebProto], $proxyAddress);
183
        }
184
 
185
        if($downtimeType == 1) {
186
                # Schedule Host Downtime
187
                $url = $nagiosWebProto . "://" . $nagiosWebServer . ":" . $nagiosWebPort . $nagiosCgiPath . "/cmd.cgi?cmd_typ=55&cmd_mod=2" .
188
                        "&host=" . $host .
189
                        "&com_author=" . $nagiosUser . "&com_data=" . $downtimeComment .
190
                        "&trigger=0&start_time=" . $start . "&end_time=" . $end .
191
                        "&fixed=1&childoptions=1&btnSubmit=Commit";
192
 
193
                if($debug == 1) {
194
                        print "HTTP-GET: " . $url;
195
                }
196
        } else {
197
                # Schedule Service Downtime
198
                $url = $nagiosWebProto . "://" . $nagiosWebServer . ":" . $nagiosWebPort . $nagiosCgiPath . "/cmd.cgi?cmd_typ=56&cmd_mod=2" .
199
                        "&host=" . $host . "&service=" . $service .
200
                        "&com_author=" . $nagiosUser . "&com_data=" . $downtimeComment .
201
                        "&trigger=0&start_time=" . $start . "&end_time=" . $end .
202
                        "&fixed=1&btnSubmit=Commit";
203
 
204
                if($debug == 1) {
205
                        print "HTTP-GET: " . $url;
206
                }
207
        }
208
 
209
        # Only try to auth if auth informations given
210
        if($nagiosAuthName ne "" && $nagiosUserPw ne "") {
211
                # submit auth informations
212
                $oBrowser->credentials($nagiosWebServer.':'.$nagiosWebPort, $nagiosAuthName, $nagiosUser => $nagiosUserPw);
213
        }
214
 
215
        # Send the get request to the web server
216
        $oResponse = $oBrowser->get($url);
217
 
218
        if($debug == 1) {
219
                print "HTTP-Response: " . $oResponse->content;
220
        }
221
 
222
        # Handle response code, not in detail, only first char
223
        switch(substr($oResponse->code,0,1)) {
224
                # 2xx response code is OK
225
                case 2 {
226
                        # Do some basic handling with the response content
227
                        switch($oResponse->content) {
228
                                case /Your command request was successfully submitted to Nagios for processing/ {
229
                                        print "OK: Downtime was submited successfully\n";
230
                                        #exit(0);
231
                                }
232
                                case /Sorry, but you are not authorized to commit the specified command\./ {
233
                                        print "ERROR: Maybe not authorized or wrong host- or servicename\n";
234
                                        #exit(1);
235
                                }
236
                                case /Author was not entered/ {
237
                                        print "ERROR: No Author entered, define Author in \$nagiosUser var\n";
238
                                        #exit(1);
239
                                }
240
                                else {
241
                                        print "ERROR: Some undefined error occured, turn debug mode on to view what happened\n";
242
                                        #exit(1);
243
                                }
244
                        }
245
                }
246
                case 3 {
247
                        print "ERROR: HTTP Response code 3xx says \"moved url\" (".$oResponse->code.")\n";
248
                        #exit(1);
249
                }
250
                case 4 {
251
                        print "ERROR: HTTP Response code 4xx says \"client error\" (".$oResponse->code.")\n";
252
                        #exit(1);
253
                }
254
                case 5 {
255
                        print "ERROR: HTTP Response code 5xx says \"server error\" (".$oResponse->code.")\n";
256
                        #exit(1);
257
                }
258
                else {
259
                        print "ERROR: HTTP Response code unhandled by script (".$oResponse->code.")\n";
260
                        #exit(1);
261
                }
262
        }
263
        print "#" x 20 ."\n";
264
#}
265
}
266
 
267
# Regular end of script
268
# ##############################################################################
269
 
270
# ###
271
# Subs
272
# ###
273
 
274
sub about {
275
                print <<'ABOUT';
276
Usage:
277
  nagios_downtime [-H <hostname>] [-s <service>] [-t <minutes>] [-S <webserver>] [-p <cgi-bin-path>] [-d]
278
  nagios_downtime -h
279
 
280
Nagios Downtime Script by Lars Michelsen <lars@vertical-visions.de>
281
Sends a HTTP(S) request to the nagios cgis to add a downtime for a host or service.
282
 
283
Parameters:
284
 -H, --hostname(s)   Name of the host(s) the downtime should be scheduled for.
285
                     Important: The name must be same as in Nagios.(Hostnames seperated by comma)
286
 -s, --service       Name of the service the downtime should be scheduled for.
287
                     Important: The name must be same as in Nagios.
288
                     When empty or not set a host downtime is being submited.
289
 -b, --starttime     Start time of downtime (Format: YYYY-mm-dd#HH:MM:SS)
290
 -t, --downtime      Duration of the fixed downtime in minutes
291
 -c, --comment       Comment for the downtime
292
 -S, --server        Nagios Webserver address (IP or DNS)
293
 -p, --path          Web path to Nagios cgi-bin (Default: /nagios/cgi-bin)
294
 -d, --debug         Enable debug mode
295
 -h, --help          Show this message
296
 
297
If you call nagios_downtime without parameters the script takes the default options which are
298
hardcoded in the script.
299
 
300
ABOUT
301
}
302
 
303
sub gettime {
304
        my $timestamp;
305
        $timestamp = shift;
306
 
307
        if($timestamp eq "") {
308
                        $timestamp = time;
309
        }
310
 
311
        my ($sec,$min,$hour,$mday,$month,$year,$wday,$yday,$isdst) = localtime($timestamp);
312
        # correct values
313
        $year += 1900;
314
        $month += 1;
315
 
316
        # add leading 0 to values lower than 10
317
        $month = $month < 10 ? $month = "0".$month : $month;
318
        $mday = $mday < 10 ? $mday = "0".$mday : $mday;
319
        $hour = $hour < 10 ? $hour = "0".$hour : $hour;
320
        $min = $min < 10 ? $min = "0".$min : $min;
321
        $sec = $sec < 10 ? $sec = "0".$sec : $sec;
322
 
323
        switch ($nagiosDateFormat) {
324
                case "euro" {
325
                        return $mday."-".$month."-".$year." ".$hour.":".$min.":".$sec;
326
                }
327
                case "us" {
328
                        return $month."-".$mday."-".$year." ".$hour.":".$min.":".$sec;
329
                }
330
                case "iso8601" {
331
                        return $year."-".$month."-".$mday." ".$hour.":".$min.":".$sec;
332
                }
333
                case "strict-iso8601" {
334
                        return $year."-".$month."-".$mday."T".$hour.":".$min.":".$sec;
335
                }
336
                else {
337
                        print "ERROR: No valid date format given in \$nagiosDateFormat";
338
                        exit(1);
339
                }
340
        }
341
}
342
 
343
# #############################################################
344
# EOF
345
# #############################################################