举个栗子

马辰龙De技术分享
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

zabbix api 获取所有主机名、IP

Posted on 2016-07-09 14:13  ChenlongMa  阅读(4766)  评论(0编辑  收藏  举报

主要添加了1条selectInterfaces记录,本质就是对于数据库就是join这张表。perl代码如下:

#!/usr/bin/perl
use strict;
use warnings;
use JSON::RPC::Client;
use Data::Dumper;
use JSON;
use utf8;
use Parallel::ForkManager;
my $pm = Parallel::ForkManager->new(20);    
#定义开启进程数
$| = 1;
binmode( STDIN,  ':encoding(utf8)' );
binmode( STDOUT, ':encoding(utf8)' );       
#三行
binmode( STDERR, ':encoding(utf8)' );       
#用来正常输出中文
 
# Authenticate yourself
my $client = new JSON::RPC::Client;
my $url    = 'http://zabbix.mcshell.org/api_jsonrpc.php';
my $authID;
my $response;
 
my $json = {
 
    jsonrpc => "2.0",
    method  => "user.login",
    params  => {
        user     => "user",
        password => "password"
    },
    id => 1
};
 
$response = $client->call( $url, $json );
 
# Check if response was successful
die "Authentication failed\n" unless $response->content->{'result'};
 
$authID = $response->content->{'result'};
print "Authentication successful. Auth ID: " . $authID . "\n";
 
print Dumper \get_all_host_and_ip();
 
sub get_all_host_and_ip {
    my $json = {
        jsonrpc => '2.0',
        method  => 'host.get',
        params  => {
            "output" => [ 'name', "host" ],    
#可以进行模糊匹配
            "selectInterfaces" => [ "interfaces", "ip" ]    
#过滤 ip
        },
        id   => 1,
        auth => "$authID",
    };
    my $response = $client->call( $url, $json );
    die "host.get failed\n" unless $response->content->{result};
    my $hostID;
    foreach my $host ( @{ $response->content->{result} } ) {
 for my $num ( @{$host->{interfaces}} ) {
 
 
 $hostID->{ $host->{host} }
 = $num->{ip};
 
 }
 
    }
    return $hostID;
 
}