PHP obtains server monitoring information through the Zabbix API and zabbix server monitoring
The open-source monitoring system Zabbix provides a wide range of APIS for third-party systems to call.
The basic steps are as follows:
1. Obtain valid authentication. Connect to the Zabbix URL and provide the user name and password. The HTTP method is "POST" and the HTTP header type is "application/json"
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 authentication 3 * @ param $ uri Zabbix address 4 * @ param $ username Zabbix username 5 * @ param $ password Zabbix password 6 * @ return permission 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' => $ password15 ), 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}
2. Call the API to obtain data. After obtaining the authentication, POST the encapsulated data as needed. The format is json. Configure different methods to obtain the required data. The method list can be viewed on the official website (https://www.zabbix.com/documentation/3.0/manual/api/reference. The following instances obtain the host ID based on the Host IP Address
1/** 2 * @ get hostid Based on IP address 3 * @ param $ uri Zabbix address 4 * @ param $ authtoken authentication information can be obtained through the zabbixAuth method above 5 * @ param $ ip host IP address 6 * @ return hostid get host 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' => $ authtoken21); 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}