See www.zabbix.com for the official Zabbix site.

Perl script to add/remove Maintenance

From Zabbix.org
Jump to: navigation, search

The following script should work with Zabbix 2.4 and up.

#!/usr/bin/perl
 
use strict;
use Getopt::Std;
use vars qw/ %opt /;
 
my $url = "http://<zabbix server>/api_jsonrpc.php"; # change <zabbix server> to your zabbix server
my $apiuser="username"; # API User's Username
my $apipassword="password"; # API User's password
my $maintenanceid;
 
#############
# Begin main
#
init();
my $hostname = $opt{s};
my $duration = $opt{d} || 10800;
my $maintname = $opt{n}; 


# Authenticate against Zabbix for API Maintenance addition
my $auth = newrequest($url, $apiuser, $apipassword);
my $hostid = gethostid($hostname);

if($opt{r}){
    print "Removing maintenance for host $hostname\n";
    getmaintid($hostid,$maintname);
    exit(0);
}else{
	print "Adding maintenance for host $hostname\n";
    addmaint($hostid,$duration,$maintname);
}
exit(0);
 
#########################
# Get command line input
#
sub init(){
    my $opt_string = 'hrs:d:n:';
    getopts( "$opt_string", \%opt ) or usage();
    usage() if $opt{h};
    usage() if !$opt{s};
	usage() if !$opt{n};
}
#####################
# Print script usage
#
sub usage(){
    print STDERR << "EOF";
usage: $0 [-hr] -s hostname [-d duration] -n name
 -h          : This (help) message   
 -r          : Remove maintenance for specified host 
 -s hostname : Hostname in Zabbix
 -d          : Duration of maintenance in seconds. Leave blank to use default.
                 300 =  5 minutes
                1800 = 30 minutes
                3600 =  1 hour
               10800 =  3 hour (default)
 -n name     : unique identifier

-s and -n are required
 
example: $0 -s hostname -d 3600 -n backup
example: $0 -s hostname -r -n backup
EOF
    exit;
}


#############################################
# Zabbix API requests require authentication
#
sub newrequest {
    my ($url, $user, $password) = @_;
 
    my $authenticate = qq(curl -s -i -X POST -H 'Content-Type: application/json-rpc' -d '{
      "params": {
          "password": "$password",
          "user": "$user"
      },
      "jsonrpc": "2.0",
      "method": "user.login",
      "id": 0
    }'  $url | grep result | head -n 1 | cut -d '"' -f 8);
    my $auth = `$authenticate`;
    chomp($auth);
    return $auth
 
}

###################################################
# Subroutine to query Zabbix to get host id
#
sub gethostid{
    my $hostname = shift;
    my $process = qq(curl -s -i -X POST -H 'Content-Type: application/json-rpc' -d '{
    "params": {
        "host": "$hostname"
    },
    "jsonrpc": "2.0",
    "method": "host.getobjects",
    "auth": "$auth",
    "id": 2 }' $url);
    my $res = `$process`;
    chomp($res);

    my @output = split(/,/,$res);
    my $x=0;
    foreach(@output){
		if (($output[$x] =~ m/\"host\"/)&&($output[$x] =~ m/$hostname/)){
            $output[$x-2] =~ s/\[\{//g;
            $output[$x-2] =~ s/"//g;
            $output[$x-2] =~ s/hostid://g;
            $output[$x-2] =~ s/result://g;
            $hostid = $output[$x-2];
        }
        $x++;
    }
    if(!$hostid){
       print "WARNING - $hostname not found in maintenance for Zabbix.\n";
       exit(1);
    }
    print "Host ID: ".$hostid."\n";
    return $hostid
}


###################################################
# Subroutine to query Zabbix to get maintenance id
#
sub getmaintid{
    my $hostid = shift;
	my $maintname = shift;
    my $process = qq(curl -s -i -X POST -H 'Content-Type: application/json-rpc' -d '{
    "params": {
        "output": "extend",
        "selectHosts": "refer",
        "selectGroups": "refer",
		"hostids": "$hostid"
    },
    "jsonrpc": "2.0",
	"method": "maintenance.get",
	"auth": "$auth",
    "id": 2 }' $url);
 
    my $res = `$process`;
    chomp($res);
 
    my @output = split(/,/,$res);
    my $x=0;
    foreach(@output){
        if (($output[$x] =~ m/\"name\"/)&&($output[$x] =~ m/ID $maintname/)){
            $output[$x-1] =~ s/\[\{//g;
			$output[$x-1] =~ s/"//g;
            $output[$x-1] =~ s/maintenanceid://g;
			$output[$x-1] =~ s/result://g;
            $maintenanceid = $output[$x-1];
            remmaint($maintenanceid);
        }
        $x++;
    }
    if(!$maintenanceid){
       print "WARNING - $hostname not found in maintenance for Zabbix.\n";
       exit(1);
    }
}
 
 
#################################################
# Subroutine to add maintenance window to Zabbix
#
sub addmaint{
    $hostid = shift;
    $duration = shift;
	$maintname = shift;
    my $start = time();
    my $end = ($start + $duration);
    # my $auth = newrequest($url, $apiuser, $apipassword);
   my $process = 'curl -s -i -X POST -H \'Content-Type: application/json-rpc\' -d "{
    \"jsonrpc\":\"2.0\",
    \"method\":\"maintenance.create\",
    \"params\":[{
        \"groupids\":[],
        \"hostids\":[\"'.$hostid.'\"],
        \"name\":\"Scripted Maintenance with ID '.$maintname.' - '.$start.'\",
        \"maintenance_type\":\"0\",
        \"description\":\"Scripted maintenance\",
        \"active_since\":\"'.$start.'\",
        \"active_till\":\"'.$end.'\",
        \"timeperiods\": [{
            \"timeperiod_type\": 0,
            \"start_date\": \"'.$start.'\",
            \"period\": '.$duration.'}]
        }],
    \"auth\":\"'.$auth.'\",
    \"id\":3}" '.$url; 
    my $res = `$process`;
    chomp($res);
 
    my @output = split(/,/,$res);
 
    foreach(@output){
    if ($_ =~ m/\"error/){
            print "$_\n";
	    exit(1);
        }
        print "$_\n" if ($_ =~ m/\"result/);
    }
 
}
#################################################
# Subroutine to remove maintenance window from Zabbix
#
sub remmaint{
    $maintenanceid = shift;
    my $process = qq(curl -s -i -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc":"2.0",
    "method":"maintenance.delete",
    "params":["$maintenanceid"],
    "auth":"$auth",
    "id":2}' $url);
 
    my $res = `$process`;
    chomp($res);
 
    my @output = split(/,/,$res);
 
    foreach(@output){
        print "$_\n" if ($_ =~ m/\"error/);
        print "$_\n" if ($_ =~ m/\"result/);
    }
}