zabbix中的IT service可以是树状结构。
这就要求脚本要有这个功能点:能收集到一个节点的所有子节点信息。(这是典型的递归循环的使用场景)。
接着上篇博客,我们已经可以获取到zabbix的auth信息。
使用zbxapi_login.pl脚本获取认证串这里是2080444abc88afe37b59456d4b7ee0a1
打开页面的IT service,点击某个你关心的节点。之你可以在地址栏看到如下信息。serviceID就在里面。
http://x.x.x.x/zabbix/report3.php?serviceid=4&year=2016&period=weekly
现在我可以用如下命令获取到IT service信息了。第三第四个参数分别是起止时间。
perl getsla.pl 2080444abc88afe37b59456d4b7ee0a1 4 `date -d '2015-10-01 00:00:00' +%s` `date -d '2015-11-01 00:00:00' +%s`
以下是脚本内容
#cat getsla.pl
use Text::CSV_XS;
use JSON::RPC::Client;
use Time::Local;
use Data::Dumper;
use strict;
use warnings;
my $csv = Text::CSV_XS->new ({ binary => 1, eol => $/ });
sub getsla {
my($auth,$serviceid,$from,$to) = @_;
my $client = new JSON::RPC::Client;
my $uri = 'http://zabbixIP/zabbix/api_jsonrpc.php';
my $callobj = {
jsonrpc => '2.0',
method => 'service.getsla',
params => { serviceids => [$serviceid],
intervals => [{ from => "$from" , to => "$to" }],
#intervals => [ from => "1443913200" , to => "1444518000" ],
} ,
auth => "$auth",
id => '1',
};
my $res = $client->call($uri, $callobj);
return $res->result;
}
sub getservice{
my($auth,$serviceid) = @_;
my $client = new JSON::RPC::Client;
my $uri = 'http://zabbixIP/zabbix/api_jsonrpc.php';
my $callobj = {
jsonrpc => '2.0',
method => 'service.get',
params => { serviceids => [$serviceid],
selectDependencies => "extend",
output => "extend",
},
auth => "$auth",
id => '1',
};
my $res = $client->call($uri, $callobj);
my $return = $res->result;
return $return;
}
sub average {
my (@num) = @_;
my $num = scalar @num;
my $total;
foreach (0..$#num) {
$total += $num[$_];
}
return ($total/$num);
}
sub getobj{
my($auth,$serviceid,$from,$to) = @_;
my @array;
my %hash;
$hash{'sla'}=getsla($auth,$serviceid,$from,$to);
$hash{'service'}=getservice($auth,$serviceid);
${$hash{'service'}}[0]{'countdependencies'}=scalar(@{$hash{'service'}->[0]{'dependencies'}});
my @num;
if (${$hash{'service'}}[0]{'countdependencies'} > 0 ){
my $sid ;
foreach $sid (@{$hash{'service'}->[0]{'dependencies'}}) {
my $child=&getobj($auth,$sid->{'serviceid'},$from,$to);
push (@array,$child);
push (@num,$child->{'sla'}{$child->{'service'}[0]{'serviceid'}}{'sla'}[0]{'sla'})
}
my $num = scalar @num;
my $total;
foreach (0..$#num) {
$total += $num[$_];
}
$hash{'sla'}{$serviceid}{'sla'}[0]{'sla'}= $total / $num;
}
push (@array,%hash);
return @array;
}
sub caltime{
my($period) = @_;
my $days = int($period/(24*3600));
my $hours = int($period%(24*3600)/3600);
my $mins = int($period%3600/60);
my $secs = $period%60;
return $days."d,".$hours."h,".$mins."m,".$secs."s";
}
open my