Zabbix api php примеры

Zabbix API Introduction and Examples

This lesson was from a previous version of my course, which I’ve now made this video available to view for free.

The Zabbix Server also has an application programming interface (API). This allows you to programmatically configure and retrieve data from the Zabbix Server.

The reason for using the API is that you either want to create your own custom interface for your Zabbix Server, e.g., a new web interface, IOS or Android app, or integrate into another monitoring system. The Grafana tutorials from earlier are an example of using the Zabbix API to read the data and create custom dashboards.

In this lesson, we will connect to our API first using the Linux cURL commands, the simple API testing tool, and then we try and example using Python.

From the examples, you will have enough background information to know how to retrieve, add, delete and modify data in the Zabbix server.

When making calls to the API you need to supply a user authentication token. The first step is to get one.

Get Authentication Token

method : user.login

 "jsonrpc": "2.0", "method": "user.login", "params":  "user": "Admin", "password": "password" >, "id": 1, "auth": null > 
curl --header "Content-Type: application/json" \ --request POST \ --data ', "id": 1, "auth": null>' \ "https://example.com/zabbix/api_jsonrpc.php" 

The authentication token is in the result value above, and you will need it for all other calls to the API.

With the token, we can now make another call to retrieve a list of all the hosts and see some info about them.

List all Hosts

Method : host.get

 "jsonrpc": "2.0", "method": "host.get", "params":  "output": ["hostid", "host"], "selectInterfaces": ["interfaceid", "ip"] >, "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c" > 
curl --header "Content-Type: application/json" \ --request POST \ --data ', "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c">' \ "https://example.com/zabbix/api_jsonrpc.php" 
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 "jsonrpc": "2.0", "result": [  "hostid": "10084", "host": "Zabbix server", "interfaces": [  "interfaceid": "1", "ip": "127.0.0.1" > ] >,  "hostid": "10336", "host": "Switch", "interfaces": [  "interfaceid": "32", "ip": "192.168.1.1" > ] >,  "hostid": "10338", "host": "HP790128.home", "interfaces": [  "interfaceid": "33", "ip": "192.168.1.81" > ] > ], "id": 2 > 

Create an item

Method : item.create

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
 "jsonrpc": "2.0", "method": "item.create", "params":  "name": "Free disk space on $1", "key_": "vfs.fs.size[/home/seanwasere/,free]", "hostid": "10084", "type": 0, "value_type": 3, "interfaceid": "1", "delay": 30 >, "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c" > 
curl --header "Content-Type: application/json" \ --request POST \ --data ', "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c">' \ "https://example.com/zabbix/api_jsonrpc.php" 

Update an Item

Method : item.update

 "jsonrpc": "2.0", "method": "item.update", "params":  "itemid": "33249", "key_": "vfs.fs.size[/home/seanwasere_2/,free]" >, "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c" > 
curl --header "Content-Type: application/json" \ --request POST \ --data ', "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c">' \ "https://example.com/zabbix/api_jsonrpc.php" 

Delete an Item

Method : item.delete

 "jsonrpc": "2.0", "method": "item.delete", "params":  "itemid": "33249" >, "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c" > 
curl --header "Content-Type: application/json" \ --request POST \ --data ', "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c">' \ "https://example.com/zabbix/api_jsonrpc.php" 

View a list of problems

Method : problem.get

 1 2 3 4 5 6 7 8 9 10 11 12 13
 "jsonrpc": "2.0", "method": "problem.get", "params":  "output": "extend", "selectAcknowledges": "extend", "recent": "true", "sortfield": ["eventid"], "sortorder": "DESC" >, "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c" > 
curl --header "Content-Type: application/json" \ --request POST \ --data ', "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c">' \ "https://example.com/zabbix/api_jsonrpc.php" 

User Logout

method : user.logout

 "jsonrpc": "2.0", "method": "user.logout", "params": <>, "id": 2, "auth": "186f9f0a1d77c843d0c36641fafb1c7c" > 
curl --header "Content-Type: application/json" \ --request POST \ --data ', "id": 1, "auth": "186f9f0a1d77c843d0c36641fafb1c7c">' \ "https://example.com/zabbix/api_jsonrpc.php" 

Источник

README

The 3.x versions of this package are compatible and tested with Zabbix™ from version 3.0.0 up to 3.4.15. If you are migrating this package from 2.x to 3.0, please follow the upgrade notes.

About

PhpZabbixApi is an open-source PHP SDK to communicate with the Zabbix JSON-RPC API.

Because this package is generated directly from the origin Zabbix PHP front-end source code, each real Zabbix JSON-RPC API method is implemented directly as a PHP method. This means PhpZabbixApi is IDE-friendly, because you’ve a declared PHP method for each API method, and there are no PHP magic functions or alike.

License

PhpZabbixApi is licensed under the MIT license.

Installing

Make sure the version of the package you are trying to install is compatible with your Zabbix API version. If you aren’t sure about your Zabbix API version, send a request to the apiinfo.version method:

curl -X POST \ -H 'Content-Type: application/json-rpc' \ -d ',"id":1>' 

Replace with your Zabbix API endpoint (for example, «https://your-zabbix-domain/api_jsonrpc.php»). Then, you will be able to install the PhpZabbixApi version that is better for you:

composer require confirm-it-solutions/php-zabbix-api:

All tagged versions can be installed, for example:

composer require confirm-it-solutions/php-zabbix-api:^3.0 
composer require confirm-it-solutions/php-zabbix-api:^3.2 

The tag names may include build metadata (the part after the plus sign) to easily identify which range of Zabbix API versions are supported. By instance, the tag 42.1.2+z3.0.0-z3.4.15 denotes that PhpZabbixApi version 42.1.2 is compatible and tested with Zabbix API from version 3.0.0 to 3.4.15 .

If you’re looking for more bleeding-edge versions (e.g. for testing), then you could also use development branches by setting a specific stability flag in the version constraint:

composer require confirm-it-solutions/php-zabbix-api:3.0@dev 

Using the thing

Naming concept

To translate a Zabbix API call into an SDK method call, you can simply do the following:

Zabbix API PHP SDK
graph.get graphGet()
host.massUpdate hostMassUpdate()
dcheck.isWritable dcheckIsWritable()

Basic usage

To use the PhpZabbixApi you just have to load ZabbixApi.php , create a new ZabbixApi instance, and you’re ready to go:

 // Load ZabbixApi. require_once __DIR__.'/vendor/autoload.php'; use Confirm\ZabbixApi\Exception; use Confirm\ZabbixApi\ZabbixApi; try < // Connect to Zabbix API. $api = new ZabbixApi( 'https://zabbix.confirm.ch/api_jsonrpc.php', 'zabbix_user', 'zabbix_password' ); // Do your stuff here. > catch (Exception $e) < // Caught exception from ZabbixApi. echo $e->getMessage(); >

The API can also work with HTTP Basic Authroization, you just have to call the constructor with additional parameters:

// Connect to Zabbix API through HTTP basic auth. $api = new ZabbixApi( 'https://zabbix.confirm.ch/api_jsonrpc.php', 'zabbix_user', 'zabbix_password', 'http_user', 'http_password' );

If you already have an authentication token, you can pass that value as argument 6 in order to avoid the library to perform the request for the user.login method for requests that require an authenticated user. If the token is valid, you can omit the argument 2 and 3, since they will be not required:

// This token was previously obtained from a call to the `user.login` method. $token = 'my_secret_token'; $api = new ZabbixApi( 'https://zabbix.confirm.ch/api_jsonrpc.php', null, null, null, null, $token ); // Make any secured method call. $api->userGet();

HTTP client

Internally, this package uses the Guzzle HTTP client to perform the requests against the Zabbix API. In order to give you more control and flexibility about the client configuration, you can pass your own implementation of \GuzzleHttp\ClientInterface as argument 7 for ZabbixApi :

// Using your own HTTP client. use GuzzleHttp\Client; $httpClient = new Client([/* Your own config */]); $api = new ZabbixApi( 'https://zabbix.confirm.ch/api_jsonrpc.php', 'zabbix_user', 'zabbix_password', 'http_user', 'http_password', null, $httpClient );

Additionally, if you prefer to provide options for the built-in client instead of provide your own client, you can pass an options array as argument 8:

// Using custom options fot the built-in HTTP client. use GuzzleHttp\Client; $httpClientOptions = [/* Your own config */]; $api = new ZabbixApi( 'https://zabbix.confirm.ch/api_jsonrpc.php', 'zabbix_user', 'zabbix_password', 'http_user', 'http_password', null, null, $httpClientOptions );

Please, note that argument 7 and 8 cannot be used together. You must choose between one of both.

Authentication token caching

In order to improve the response times avoiding the call for the user.login method in each request, you can configure a PSR-6 caching backend for the authentication token. This way the SDK will get the cached token after the first login and until its expiration. The following example uses a fictional Psr6FilesystemAdapter class, but you can choose any available implementation:

/** @var \Psr\Cache\CacheItemPoolInterface $psr6Cache */ $psr6Cache = new Psr6FilesystemAdapter(); $api->setTokenCache($psr6Cache);

Examples

Simple request

Here’s a simple request to fetch all defined graphs via graph.get API method:

// Get all graphs. /** @var array> $graphs */ $graphs = $api->graphGet(); // Print all graph IDs. foreach ($graphs as $graph) < echo $graph['graphid']."\n"; >

By default, the values will be returned using an associative array, but you can always choose to get instances of \stdClass instead, using false as argument 3 in the method call:

// Get all graphs as instances of `\stdClass`. /** @var \stcClass[] $graphs */ $graphs = $api->graphGet([], null, false); // Print all graph IDs. foreach ($graphs as $graph) < echo $graph->graphid."\n"; >

Request with parameters

Most of the time you want to define some specific parameters. Here’s an example to fetch all CPU graphs via graph.get API method:

// Get all graphs named "CPU". $cpuGraphs = $api->graphGet([ 'output' => 'extend', 'search' => ['name' => 'CPU'], ]); // Print graph ID with graph name. foreach ($cpuGraphs as $graph) < printf("id:%d name:%s\n", $graph['graphid'], $graph['name']); >

Define default parameters

Sometimes you want to define default parameters, which will be included in each API request. You can do that by defining the parameters in an array via setDefaultParams() :

// Use extended output for all further requests. $api->setDefaultParams([ 'output' => 'extend', ]); // Get all graphs named "CPU". $cpuGraphs = $api->graphGet([ 'search' => ['name' => 'CPU'], ]); // Print graph ID with graph name. foreach ($cpuGraphs as $graph) < printf("id:%d name:%s\n", $graph['graphid'], $graph['name']); >

Get associative / un-indexed array

By default all API responses will be returned in an indexed array.

So if you then looking for a specific named graph, you’ve to loop through the indexed array and compare the name attribute of each element. This can be a bit of a pain, and because of that, there’s a simple way to get an associative array instead of an indexed one. You just have to pass the argument 2 for the method, which is the name of attribute you’d like to use as a key in the resulting array.

Here’s an example to fetch all graphs in an associative array, with the graph’s name as array key:

// Get all graphs in an associative array (key=name). $graphs = $api->graphGet([], 'name'); // Print graph ID with graph name. if (array_key_exists('CPU Load Zabbix Server', $graphs)) < echo 'Graph "CPU Load Zabbix Server" exists.'; > else < echo 'Could not find graph "CPU Load Zabbix Server".'; >

Источник

Читайте также:  Html page to android app
Оцените статью