zabbix api 使用
之前一直纠结从mysql表里取数据,因为不清楚怎么取表之间的关系,故只能使用zabbix的api来取数据,使用api后,发现还是很方便的。废话不说,开始!1.首先php必须支持curl,我使用的是ubuntu,故需要在php.ini配置上curl.so文件。至于怎么找curl.so,大家可以网上下载curl的包来编译。
修改php.ini,添加extension=cURL.so,so文件自己找准路径啊。
2. 添加php api调用封装如下:
zbx.inc.php
<?php
class jsonrpc{
protected function connect($server, $query){
$http = curl_init($server);
echo $query;
echo "<br/><br/>";
curl_setopt($http, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($http, CURLOPT_POSTFIELDS, $query);
curl_setopt($http, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($http, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($http, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($http, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($http);
return json_decode($response, true);
curl_close($http);
}
}
class zbx extends jsonrpc{
public $method;
public $access_token;
public $url;
public $query;
function call(){
$data['jsonrpc'] = '2.0';
$data['method'] = $this->method;
$data['params'] = $this->query;
$this->query = '';
if(!empty($this->access_token)) $data['auth'] = $this->access_token;
$data['id'] = rand(1,100);
$data = json_encode($data, JSON_PRETTY_PRINT);
return $this->connect($this->url, $data);
}
}
?>
测试的test.php
<?php
require dirname(__FILE__).'/zbx.inc.php';
$zbx = new zbx;
$zbx->url = 'http://1.2.3.1/zabbix/api_jsonrpc.php';
$zbx->method = 'user.login';
$zbx->query['user'] = 'admin';
$zbx->query['password'] = 'zabbix';
$zbx->access_token = $zbx->call()['result'];
$zbx->method = 'history.get';
$zbx->query['output'] = 'extend';
$zbx->query['history'] = 3;
$zbx->query['itemids'] = '23985';
$zbx->query['sortfield'] = 'clock';
$zbx->query['sortorder'] = 'DESC';
$zbx->query['limit'] = 1;
$hostid = $zbx->call();
var_dump($hostid);
?>
这里有个地方需要注意的$zbx->query['history'] = 3;这个类型要根据select value_type from items where itemid='23985'; 切记!!
输出结果如下:
request:
</pre><pre name="code" class="html">{ "jsonrpc": "2.0", "method": "history.get", "params": { "output": "extend", "history": 3, "itemids": "23985", "sortfield": "clock", "sortorder": "DESC", "limit": 1 }, "auth": "f926d068fc5ba59e222b2c157ef993a1", "id": 79 }
result:
array(3) { ["jsonrpc"]=> string(3) "2.0" ["result"]=> array(1) { => array(4) { ["itemid"]=> string(5) "23985" ["clock"]=> string(10) "1416371085" ["value"]=> string(5) "42304" ["ns"]=> string(9) "828133527" } } ["id"]=> int(79) }
another way:
$zbx->method = 'item.get';
$zbx->query['output'] = 'extend';
$zbx->query['itemids'] = '24038';
$result = $zbx->call()['result']['0'];
echo 'item.key_:' . $result['key_'] . 'lastvalue' . $result['lastvalue'];
页:
[1]