基本的にZabbixAPIの、ただのラッパーです。
APIのクラス、メソッドをアンダースコアでくっつけたもの(host.getならばhost_get())を呼び出せます。
引数はparamsのハッシュリファレンスです。
サンプルをいくつか
APIバージョン、ホストグループの一覧を取得
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use ZabbixAPI; my $za = ZabbixAPI->new("http://127.0.0.1/zabbix/"); $za->auth("Admin", "password"); print Dumper $za->apiinfo_version(); print Dumper $za->hostgroup_get({output => "extend"});
出力
[mikeda@admin01 work]$ perl api_test1.pl $VAR1 = '1.3'; $VAR1 = [ { 'name' => 'Templates', 'groupid' => '1', 'internal' => '0' }, { 'name' => 'Linux servers', 'groupid' => '2', 'internal' => '0' }, { 'name' => 'Windows servers', 'groupid' => '3', 'internal' => '0' }, { 'name' => 'Zabbix servers', 'groupid' => '4', 'internal' => '0' }, { 'name' => 'Discovered hosts', 'groupid' => '5', 'internal' => '1' } ];
新規ホスト作成
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use ZabbixAPI; my $za = ZabbixAPI->new("http://127.0.0.1/zabbix/"); $za->auth("Admin", "password"); my $groupid = $za->hostgroup_get({filter=>{name=>"Linux servers"}})->[0]->{groupid}; my $templateid = $za->template_get({filter=>{host=>"Template_Linux"}})->[0]->{templateid}; my $result = $za->host_create({ host => "api_test01", ip => "192.168.1.200", port => "10050", useip => 1, groups => [ { groupid => $groupid } ], templates => [ { templateid => $templateid } ] }); print Dumper $result;
出力
[mikeda@admin01 work]$ perl api_test2.pl $VAR1 = { 'hostids' => [ '10062' ] };
モジュールのソースコード
とりあえず版ですがさらしておきます。
package ZabbixAPI; use strict; use warnings; use Data::Dumper; use JSON; use LWP::UserAgent; our $VERSION = "0.01"; use constant JSONRPC => "2.0"; use constant API_PATH => "api_jsonrpc.php"; sub new { my $class = shift; my ($url, $id) = @_; ### 同時に走らせるときはID変えないとダメなんだろうか? $id ||= 1; my $self = bless { url => $url . API_PATH, id => $id, auth => undef }; return $self; } sub auth { my $self = shift; my ($user, $password) = @_; my %params = ( user => $user, password => $password ); $self->{auth} = $self->call_api('user.authenticate', \%params); } sub call_api { my $self = shift; my ($method, $params) = @_; $params ||= {}; my %request = ( method => $method, auth => $self->{auth}, id => $self->{id}, jsonrpc => JSONRPC, params => $params, ); my $json_request = encode_json(\%request); my $ua = LWP::UserAgent->new; my $http_res = $ua->post( $self->{url}, 'Content-Type' => 'application/json-rpc', 'User-Agent' => "ZabbixAPI/mikeda v$VERSION", Content => $json_request ); if($http_res->is_error){ die "HTTP Error\n" . $http_res->status_line ."\n"; } my $api_res = decode_json($http_res->content); if($api_res->{error}){ die "API Error\n" . Dumper($api_res->{error}); } return $api_res->{result}; } sub DESTROY {}; sub AUTOLOAD{ my $self = shift; my $method = our $AUTOLOAD; $method =~ s/.*:://; if($method =~ tr/_/./ == 1){ $self->call_api($method, @_); }else{ die "Undefined Method $AUTOLOAD"; } } 1;
※githubにアップしました。更新はこちらで
https://github.com/mikeda/ZabbixAPI