PHP通过Zabbix API获取服务器监控信息
2021-04-30 09:26
标签:logs param ip地址 put 取数据 type word str inf 开源监控系统Zabbix提供了丰富的API,供第三方系统调用。 基本步骤如下: 1、获取合法认证;连接对应Zabbix URL,并提供用户名和密码,HTTP方法为“POST”,HTTP头部类型为“application/json” 2、调用API获取数据;取得认证后,根据需要POST封装好的data,格式为json,配置不同的方法获取需要的数据。方法列表可在官方网站(https://www.zabbix.com/documentation/3.0/manual/api/reference)查阅。以下实例根据主机IP地址获取主机ID PHP通过Zabbix API获取服务器监控信息 标签:logs param ip地址 put 取数据 type word str inf 原文地址:http://www.cnblogs.com/himismad/p/7808566.html 1 public function zabbixJsonRequest($uri, $data) {
2 try{$json_data = json_encode($data);
3 $c = curl_init();
4 curl_setopt($c, CURLOPT_URL, $uri);
5 curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
6 curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
7 curl_setopt($c, CURLOPT_POST, $json_data);
8 curl_setopt($c, CURLOPT_POSTFIELDS, $json_data);
9 curl_setopt($c, CURLOPT_HTTPHEADER, array(
10 ‘Content-Type: application/json‘,
11 ‘Content-Length: ‘ . strlen($json_data))
12 );
13 curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
14 $result = curl_exec($c);
15
16 return json_decode($result, true);
17 }catch(Exception $e) {
18 CCLog::LogErr(‘ZabbixInfoLogic: zabbixJsonRequest Err ->‘ . $e->getMessage());
19 return array();
20 }
21 }
1 /**
2 * @Zabbix鉴权
3 * @param $uri Zabbix地址
4 * @param $username Zabbix用户名
5 * @param $password Zabbix密码
6 * @return 权限
7 */
8 public function zabbixAuth($uri, $username, $password) {
9 try{$data = array(
10 ‘jsonrpc‘ => "2.0",
11 ‘method‘ => "user.login",
12 ‘params‘ => array(
13 ‘user‘ => $username,
14 ‘password‘ => $password
15 ),
16 ‘id‘ => "1"
17 );
18 $response = $this->zabbixJsonRequest($uri, $data);
19 return $response[‘result‘];
20 }catch(Exception $e) {
21 CCLog::LogErr(‘ZabbixInfoLogic: zabbixAuth Err ->‘ . $e->getMessage());
22 return array();
23 }
24 }
1 /**
2 * @根据IP获取hostid
3 * @param $uri Zabbix地址
4 * @param $authtoken 认证信息 可通过上述zabbixAuth方法获取
5 * @param $ip 主机IP地址
6 * @return hostid 获取主机ID
7 */
8 public function zabbixGetHostIdByIp($uri, $authtoken,$ip) {
9 try{$data = array(
10 ‘jsonrpc‘ => "2.0",
11 ‘method‘ => "host.get",
12 ‘params‘ => array(
13 "output"=>[ "host" ],
14 "filter" => array(
15 "ip" => $ip,
16
17 )
18 ),
19 ‘id‘ => "1",
20 ‘auth‘ => $authtoken
21 );
22 $response = $this->zabbixJsonRequest($uri, $data);
23 return $response[‘result‘][0][‘hostid‘];
24 }catch(Exception $e) {
25 CCLog::LogErr(‘ZabbixInfoLogic: zabbixGetHostIdByIp Err ->‘ . $e->getMessage());
26 return array();
27 }
28 }
文章标题:PHP通过Zabbix API获取服务器监控信息
文章链接:http://soscw.com/index.php/essay/80342.html