开源监控系统Zabbix提供了丰富的API,供第三方系统调用。
基本步骤如下:
1、获取合法认证;连接对应Zabbix URL,并提供用户名和密码,HTTP方法为“POST”,HTTP头部类型为“application/json”
public function zabbixJsonRequest($uri, $data) {
try{$json_data = json_encode($data);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $uri);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST, $json_data);
curl_setopt($c, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($c);
return json_decode($result, true);
}catch(Exception $e) {
CCLog::LogErr('ZabbixInfoLogic: zabbixJsonRequest Err ->' . $e->getMessage());
return array();
}
}
/**
* @Zabbix鉴权
* @param $uri Zabbix地址
* @param $username Zabbix用户名
* @param $password Zabbix密码
* @return 权限
*/
public function zabbixAuth($uri, $username, $password) {
try{$data = array(
'jsonrpc' => "2.0",
'method' => "user.login",
'params' => array(
'user' => $username,
'password' => $password
),
'id' => "1"
);
$response = $this->zabbixJsonRequest($uri, $data);
return $response['result'];
}catch(Exception $e) {
CCLog::LogErr('ZabbixInfoLogic: zabbixAuth Err ->' . $e->getMessage());
return array();
}
}
2、调用API获取数据;取得认证后,根据需要POST封装好的data,格式为json,配置不同的方法获取需要的数据。方法列表可在官方网站(https://www.zabbix.com/documentation/3.0/manual/api/reference)查阅。以下实例根据主机IP地址获取主机ID
/**
* @根据IP获取hostid
* @param $uri Zabbix地址
* @param $authtoken 认证信息 可通过上述zabbixAuth方法获取
* @param $ip 主机IP地址
* @return hostid 获取主机ID
*/
public function zabbixGetHostIdByIp($uri, $authtoken,$ip) {
try{$data = array(
'jsonrpc' => "2.0",
'method' => "host.get",
'params' => array(
"output"=>[ "host" ],
"filter" => array(
"ip" => $ip,
)
),
'id' => "1",
'auth' => $authtoken
);
$response = $this->zabbixJsonRequest($uri, $data);
return $response['result'][0]['hostid'];
}catch(Exception $e) {
CCLog::LogErr('ZabbixInfoLogic: zabbixGetHostIdByIp Err ->' . $e->getMessage());
return array();
}
}
更多Zabbix相关教程集合: