有時候使用zabbix需要另外呼叫zabbix的介面執行一些操作,這裡記下使用的小demo
- 公用 helper 檔案
<?php
namespace tSDK\application\helpers;
use tSDK\application\exceptions\InfoException;
class ZabbixHelper
{
public static $method = '';
protected static $access_token = '';
public static $query = '';
protected static $host = '';
protected static function connect($query){
$http = curl_init(self::$host);
curl_setopt($http, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($http, CURLOPT_POSTFIELDS, $query);
curl_setopt($http, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($http, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($http, CURLOPT_SSL_VERIFYHOST, TRUE);
curl_setopt($http, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($http);
curl_close($http);
return json_decode($response, true);
}
public static function call(){
$data['jsonrpc'] = '2.0';
$data['method'] = self::$method;
$data['params'] = self::$query;
if (!$data) {
throw new InfoException('缺少method引數');
}
if (!$data['params']) {
throw new InfoException('缺少params引數');
}
self::$query = '';
self::$method = '';
if(!empty(self::$access_token)) $data['auth'] = self::$access_token;
if (!self::$access_token) {
self::login();
}
$data['id'] = rand(1,100);
$data['auth'] = self::$access_token;
$data = json_encode($data, JSON_PRETTY_PRINT);
return self::connect($data);
}
protected static function login()
{
$zabbixConfig = ENV_DATA['zabbix_config'];
if (!$zabbixConfig['host'] || !$zabbixConfig['name'] || !$zabbixConfig['pwd']) {
throw new InfoException('缺少zabbix配置');
}
self::$host = $zabbixConfig['host'] . '/api_jsonrpc.php';
$data = [
'jsonrpc' => '2.0',
'method' => 'user.login',
'params' => ['user' => $zabbixConfig['name'], 'password' => $zabbixConfig['pwd']],
'id' => rand(1, 100),
];
$data = json_encode($data, JSON_PRETTY_PRINT);
$result = self::connect($data);
if ($result['result']) {
self::$access_token = $result['result'];
} else {
throw new InfoException('zabbix登入失敗');
}
}
}
當然,如果需要引用的話 namespace tSDK\application\helpers;use tSDK\application\exceptions\InfoException;
以及 類裡的InfoException需要去掉,只需引用類即可,ENV_DATA為設定的全域性資料,儲存zabbix賬號,可根據自己需要設定
- 介面呼叫 demo
public function actionTest()
{
ZabbixHelper::$method = 'event.acknowledge';
ZabbixHelper::$query = ['eventids' => [123456], 'message' => 'hello world', 'action' => 14, 'severity' => 1];
$resutl = ZabbixHelper::call();
print_r($resutl);exit;
}
這裡使用記得先引用 ZabbixHelper,這個測試 demo 的功能是事件確認,zabbix4.0文件 https://www.zabbix.com/documentation/4.0/z... ,zabbix3.4的文件對事件確認的引數描述沒有這麼清晰
這裡的目的是確認事件還可以新增自定義的訊息,卻出現一個問題還沒有解決,就是呼叫一次介面,zabbix上面會出現兩條記錄,如果單單是確認事件就只有一條記錄,但只要加上自定義訊息就會出現兩條,納悶!!!
本作品採用《CC 協議》,轉載必須註明作者和本文連結