Zabbix API を使用してホストリストを取得する
zabbixに多数サーバ登録した場合、ホストリストの視認性に苦労する事がある。
※Webコンパネからポチポチしたくない・・
その場合、APIを使用しリスト化するのが便利そうなので実装した。
<?php // リクエストデータの作成 $request_ver = array( 'jsonrpc' => '2.0', 'method' => 'apiinfo.version', 'id' => 1, 'auth' => null, 'params' => array(), ); $request_token = array( 'jsonrpc' => '2.0', 'method' => 'user.login', 'params' => array( 'user' => '[userid]', 'password' => '[passwd]', ), 'id' => 1, 'auth' => null, ); $request_list = array( 'jsonrpc' => '2.0', 'method' => 'host.get', 'params' => array( 'output' => array('hostid', 'host'), 'selectGroups' => array('groupid', 'name'), 'selectParentTemplates' => array('templateid', 'name'), 'selectInterfaces' => array('interfaceid', 'ip'), ), 'id' => 1, 'auth' => '[auth_token]', ); // リクエストデータを JSON 形式に変換 //$request_json = json_encode($request_ver); // ver取得 //$request_json = json_encode($request_token); // auth_token取得 $request_json = json_encode($request_list); // ホストリスト取得 // HTTPストリームコンテキストの作成 $opts['http'] = array( 'method' => 'POST', 'header' => 'Content-Type: application/json-rpc', 'content' => $request_json, ); $context = stream_context_create($opts); // リクエストの実行 $url = 'http://[basic_auth_id]:[basic_auth_passwd]@localhost/zabbix/api_jsonrpc.php'; $response_json = file_get_contents($url, false, $context); // レスポンスの表示 $response = json_decode($response_json, true); //var_dump($response); // // ホストリスト取得する場合、下記コード有効化 // foreach((array)$response as $key => $value){ foreach((array)$value as $key1 => $value1){ echo 'hostid:' . $value1['hostid'] . "\t" . 'host:' . $value1['host'] ."\n"; foreach((array)$value1 as $key2 => $value2){ if ($key2 == 'groups'){ echo $key2 . "\n"; foreach((array)$value2 as $key3 => $value3){ echo 'groupid:' . $value3['groupid'] . "\t" . 'groupname:' . $value3['name'] ."\n"; } } if ($key2 == 'parentTemplates'){ echo $key2 . "\n"; foreach((array)$value2 as $key4 => $value4){ echo 'templateid:' . $value4['templateid'] . "\t" . 'templatename:' . $value4['name'] ."\n"; } } if ($key2 == 'interfaces'){ echo $key2 . "\n"; foreach((array)$value2 as $key5 => $value5){ echo 'interfaceid:' . $value5['interfaceid'] . "\t" . 'ip:' . $value5['ip'] ."\n"; } } } } }
上記実行時した場合の出力結果を示します。
hostid:1234 host:vm1234 groups groupid:11 groupname:DB servers groupid:19 groupname:groupA groupid:15 groupname:Staging servers parentTemplates templateid:10860 templatename:Template OS CentOS7 templateid:11303 templatename:Template App MySQL GroupReplication interfaces interfaceid:1183 ip:172.31.100.1
出力フォーマットの検討の余地があるが、箇条書きベースでリスト取得出来た。