Wednesday, 15 February 2012

Using the Zabbix API with Perl

I've recently started looking into Zabbix as a monitoring solution for a project at work. First impressions are it's as ugly as a bag of smashed crabs garnished with ugly berries, but it's certainly functional. One of those functions is a pretty extensive JSON API. To test it out, I put together a basic Perl script because I couldn't find anyone elses to steal learn from. Maybe it will be of use to someone who needs to see the basic structure of sending requests to Zabbix via the API.

Source file: Here
use 5.010;
use strict;
use warnings;
use JSON::RPC::Legacy::Client;
use Data::Dumper;

# Step 1 - request the auth hash
#
#create new JSON_RPC object
my $client = new JSON::RPC::Legacy::Client; 
my $uri = 'http://x.x.x.x/zabbix/api_jsonrpc.php'; 
#replace x.x.x.x with Zabbix IP / Hostname

my $json_obj = {
 jsonrpc => "2.0",
 method => "user.login", #method for creating the authentication hash
 params => {
  user => "admin", #user must have Zabbix API access
  password => "zabbix"
 },
 id => 1 #Request tagging for sending multiple requests
};

#Send finished JSON_RPC request to Zabbix
my $response = $client->call($uri, $json_obj);  
my $authHash;
if ($response->content->{'result'}) { 
 #'result' value is only present in a successful request
 $authHash = $response->content->{'result'}; 
 print "Auth successful - ID hash: " . $authHash . "\n"; 
 #Print to screen, not necessary but good to know everything is working
 }
else { #handle invalid credentials
 print "sorry, incorrect auth\n";
 exit; #exit - we don't have an auth hash so can't proceed
 }

# Step 2 - if we have an auth hash, get host groups available.
# As the third step in our example is going to create a host
# that host needs to belong to a group so we need to know 
# which group IDs are available to put our new host in

$client = new JSON::RPC::Legacy::Client;
$json_obj = {
 jsonrpc=> '2.0',
 method => 'hostgroup.get',
 params => 
  {
  output => 'extended',
  sortfield => 'name',
  },
 id => 2,
 auth => "$authHash",
};
$response = $client->call($uri, $json_obj);
#Dump the response in a basic a format - this will give you a feel for 
#what data is returned by the calls
print Dumper($response);


# Step 3 - create a host using the information from the previous call
# In this example - I have used a host group ID 
# which existed in my demo install.
# This will almost certainly be different in your environment!
$client = new JSON::RPC::Legacy::Client;
$json_obj = {
 jsonrpc => '2.0',
 method => 'host.create',
 params => 
  {
  host => 'myAPI_Host',
  ip => '1.2.3.4',
  port => '10050',
  useip => 1,
  groups => 
   {
   groupid => 7
   }
  },
 id => 3,
 auth => "$authHash"
 };
$response = $client->call($uri, $json_obj);
print Dumper($response);

No comments:

Post a Comment