ZABBIX API Introduction and use

Source: Internet
Author: User

API Introduction

The Zabbix API begins to play an increasingly important role, especially when integrating third-party software and automating daily tasks. It's hard to imagine how difficult it is to manage thousands of servers without automation. The Zabbix API provides a programmable interface for bulk operations, third-party software integration, and other functions.

The Zabbix API was introduced in version 1.8 and has been widely used. All Zabbix mobile clients are API-based and even native web front-end parts are built on top of it. The Zabbix API middleware makes the architecture more modular and avoids direct manipulation of the database. It allows you to create, update, and retrieve Zabbix objects through the JSON RPC protocol and do whatever you like "if you have an authentication account," of course.

The Zabbix API provides two key features:

    • Remote Management Zabbix Configuration

    • Remote retrieval of configuration and historical data

Using JSON

The API is implemented with JSON-RPC. This means that any function that is called will need to send a POST request, and the input and output data are in JSON format. The approximate workflow is as follows:

    • Prepare the JSON object, which describes what you want to do (create a host, get an image, update a monitor item, and so on).

    • Use the Post method to send this JSON object to http://example.com/zabbix/api_jsonrpc.php. http://example.com/zabbix/is the Zabbix front-end address. Api_jsonrpc.php is the PHP script that invokes the API. Can be found in the directory where the visual frontend is installed.

    • Gets the JSON format response.

    • Note: The HTTP Header Content-type must be one of "Application/jsonrequest,application/json-rpc,application/json" except that the request must be a POST method.

You can use the API using scripts or any "manual" support for JSON RPC tools. The first thing you need to know is how to verify and how to use the authentication ID to get the information you want. The following demo will present the basic use of the API in Python scripts and curl-based examples.

Basic Request Format

The Zabbix API simplifies the JSON request as follows:

{    "Jsonrpc":"2.0",    "Method":"Method.name",     "params": {        "Param_1_name":"Param_1_value",        "Param_2_name":"Param_2_value"     },    "ID":1,    "Auth":"159121b60d19a9b4b55d49e30cf12b81",}

The following line looks:

    • "Jsonrpc": "2.0"-this is the standard JSON RPC parameter to indicate the protocol version. All requests will remain unchanged.

    • "Method": "Method.name"-This parameter defines the action that is actually performed. For example: Host.create, item.update, etc.

    • "Params"-this is done by passing a JSON object as a parameter to a particular method. If you want to create a monitoring entry, the "name" and "Key_" parameters are required, and the parameters required for each method are described in the Zabbix API documentation.

    • "id": 1-this field is used to bind JSON requests and responses. The response will have the same "id" as the request. Useful when sending multiple requests at once, and these do not require a single or sequential

    • "Auth": "159121b60d19a9b4b55d49e30cf12b81"-This is an authentication token "authentication token" to authenticate the user and access the API. This is also the premise of using the API for related operations-get the authentication ID.

API usage
    • Environment preparation

The Zabbix API is based on the JSON-RPC 2.0 specification, and the implementation can choose any programming language you prefer, or manual mode. Here we use Python and curl-based methods to do the example. Python version 2.7 already supports JSON, so additional module components are no longer required. Of course, you can use Perl, Ruby, PHP and other languages, before using to ensure that the corresponding JSON module installation.

    • Identity verification

Any Zabbix API client needs to verify itself before it really works. Here is the use of the User.login method. This method takes a user name and password as a parameter and returns a validation ID, a secure hash string for persistent API calls (valid for the validation ID before using user.logout). The specific Python code auth.py is as follows:

#!/usr/bin/env python2.7#Coding=utf-8ImportJSONImportUrllib2#based URL and required headerURL ="http://monitor.example.com/api_jsonrpc.php"Header= {"Content-type":"Application/json"}#auth user and passworddata =Json.dumps ({"Jsonrpc":"2.0",    "Method":"User.login",    "params": {    "User":"Admin",    "Password":"Zabbix"},"ID": 0})#Create Request ObjectRequest =Urllib2. Request (Url,data) forKeyinchHeader:request.add_header (Key,header[key])#Auth and get AuthidTry: Result=Urllib2.urlopen (Request)exceptUrlerror as E:Print "Auth Failed, please Check Your Name and Password:", E.codeElse: Response=json.loads (Result.read ()) Result.close ()Print "Auth successful. The Auth ID is:", response['result']

Here you need to make sure that the user name and password in the URL match. Here is the result of the operation:

As you can see, auth.py is successfully connected and certified. Now with the validation ID, it can be reused in new API calls.

Here's how the curl-based approach to validation is implemented:

' Content-type:application/json ' -D'{"JSONRPC": "2.0", "Method": "User.authenticate", "params": {"user": "Admin", "Password": " Zabbix "}," auth ": null," id ": 0}' http://monitor.example.com/api_jsonrpc.php

    • General operation

Here is an example of how to get a list of the monitoring hosts, "host List". This script needs to take the validation ID obtained in auth.py and execute the Host.get method to get the host list. To see the specific code get_host.py:

#!/usr/bin/env python2.7#Coding=utf-8ImportJSONImportUrllib2#based URL and required headerURL ="http://monitor.example.com/api_jsonrpc.php"Header= {"Content-type":"Application/json"}#Request JSONdata =Json.dumps ({"Jsonrpc":"2.0",    "Method":"Host.get",    "params":{        "Output":["HostID","name"],        "Filter":{"Host":""}    },    "Auth":"2ee379e516f386ca4c24da7fd9fd5bb4",#The Auth ID is a auth script returns, remeber it is string    "ID": 1,})#Create Request ObjectRequest =Urllib2. Request (Url,data) forKeyinchHeader:request.add_header (Key,header[key])#Get host listTry: Result=Urllib2.urlopen (Request)exceptUrlerror as E:ifHasattr (E,'reason'):        Print 'We failed to reach a server.'        Print 'Reason:', E.reasonelifHasattr (E,'Code'):        Print 'The server could not fulfill the request.'        Print 'Error Code:', E.codeElse: Response=json.loads (Result.read ()) Result.close ()Print "Number of Hosts:", Len (response['result'])     forHostinchresponse['result']:        Print "Host ID:", host['HostID'],"Host Name:", host['name']

Partial results list:

Compare the access method based on Curl: curl-i-x post-h ' Content-type:application/json '-d ' {"JSONRPC": "2.0", "Method": "Host.get", "params": {" Output ": [" HostID "," name "]," filter ": {" host ":" "}}," Auth ":" Ecc543db662930c122b5fbedee60cc63 "," id ": 1} '/HTTP/ monitor.example.com/api_jsonrpc.php

Too many results were not shown. In comparison, the use of scripting can have more flexibility, and based on curl, the results of processing is not very convenient. The principles are all interlinked.

In addition to these fetch information, the use of API calls can also be created operations, update operations and delete operations, and so on. It's also easy for us to think about database operations and, of course, to compare the way the API calls get results, and not to forget the most direct and risky way. As already mentioned in the beginning of the discussion, the front-end implementation of Zabbix now comes with a database operation, partly based on API calls. In the API is not very mature now, specifically in which way, need to be determined according to business requirements.

    • Data flow

The following flowchart represents a typical workflow for Zabbix API work. Validation (method User.login) is a mandatory step to get the validation ID. This ID also allows us to invoke any permissions provided by the API to allow the operation of the method. The User.logout method is not mentioned in the previous example, which is why a validation ID can be reused. Using the User.logout method will invalidate the validation ID, and subsequent operations will no longer use this ID.

Ref

    • Http://doc.bonfire-project.eu/R2/monitoring/monitoring_zabbix_API.html
    • https://www.zabbix.com/documentation/1.8/api/getting_started
    • http://blog.zabbix.com/getting-started-with-zabbix-api/1381/

Original address: http://paperplane.ruhoh.com/zabbix/intro-to-zabbix-api/

ZABBIX API Introduction and use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.