Get server information with the Zabbix API

Source: Internet
Author: User
Sometimes we need to monitor the running state of the server, Zabbix is such an online monitoring system. At the same time Zabbix provides the API and other ways for other programs to get the data, this article with PHP instance code sharing to let everyone know how to get the server information through Zabbix.

Since we have installed the Zabbix system, I only know how to get the information, summarizing there are two ways to get it.

Installation can be referred to: CENTOS7 installation Zabbix Detailed introduction

First, get host information through Zabbix API

The host information obtained in this way is relatively new (updated every minute). However, because the interface needs to be requested each time, it is relatively slow, if the number of concurrent queries host more, it will be very slow.

The open source monitoring System Zabbix's official documentation provides a rich API. Here I HTTP request is with guzzle 6. Of course you can also use the PHP built-in curl function to write an HTTP request yourself, very simple.


1, the user authentication to obtain tokens.

$responst = $this->httpclient->request (' POST ', ' http://zabbix.xxxxx.com/zabbix/api_jsonrpc.php ', [    ' Headers ' = [        ' content-type ' = ' application/json-rpc ',    ],    ' json ' and ' = '        jsonrpc ' = ' 2.0 ',        ' method ' = ' user.login ',        ' params ' = [            ' user ' = ' your username ',            ' password ' and ' your ' Password '        ],        ' id ' = 1,        ' auth ' = null    ],]);


Since this is a user authentication, all auth can write null directly. The returned result is:

{    "JSONRPC": "2.0",    "result": "0424bd59b807674191e7d77572075f33",    "id": 1}

The result is token, which is required in the subsequent request.


2, according to the host IP to obtain HostID.


$responst = $this->httpclient->request (' POST ', ' http://zabbix.xxxxx.com/zabbix/api_jsonrpc.php ', [    ' Headers ' = [        ' content-type ' = ' application/json-rpc ',    ],    ' json ' and ' = '        jsonrpc ' = ' 2.0 ',                ' method ' = ' host.get ',        ' params ' = ["Output" = ["HostID"], "filter" = [    "Host" = ' 192.168.1.1 '], ' id ' = 1, ' auth ' = ' 0424bd59b807674191e7d77572075f33 '],]);


The above output is a restriction on the return item, and if you want to return all the host information, you can remove the output. The returned result of the above request is:


{    "JSONRPC": "2.0",    "result": [        {            "HostID": "10160",        }    ],    "id": 1}




3, get the monitor item Itemid of the host.

Zabbix provides a lot of monitoring, so what's the problem, and what do we need? Here are some common monitoring items that bloggers are introducing to you:

$items = Array (    ' vm.memory.size[available] ',        //Memory Available value  (KB)    ' vm.memory.size[total] ',            //Total Memory  (KB)    ' system.cpu.util[,idle] ',           //Current CPU idle value (%)    ' vfs.fs.size[/,used] ',              //Current/Disk usage value (KB)    ' Vfs.fs.size[/,total] ',             //Current/Disk total    (KB));


$item _ids = Array (), foreach ($items as $item) {    $responst = $this->httpclient->request (' POST ', $this->url, ['        headers ' = ['            content-type ' = ' application/json-rpc ',        ],        ' json ' = '            = ' jsonrpc ' = > $this->jsonrpc,            ' method ' and $this->method_item_get,            ' params ' and ' [                ' output ' = ' Extend ',                "hostids" = $this->hostid,                "Search" = [                    "Key_" and "= $item                ],                ' SortField ' = ' + ' name '            ],            ' id ' = 1,            ' auth ' + $this->token        ],    ]);    $body = Json_decode ($responst->getbody ()->getcontents ()); $item _ids[] = $body->result[0]->itemid;}

The returned result is:


{"JSONRPC": "2.0", "result": [{"Itemid": "23298", "type": "0", "Snmp_comm            Unity ":", "snmp_oid": "", "HostID": "10084", "name": "Context switches per second", "Key_": "vm.memory.size[available", "Delay": "$", "History": "7", "Trends": "36 5 "," Lastvalue ":" 2552 "," Lastclock ":" 1351090998 "," Prevvalue ":" 2641 "," stat E ":" 0 "," status ":" 0 "," Value_type ":" 3 "," Trapper_hosts ":" "," units ":" SPS " , "multiplier": "0", "Delta": "1", "Snmpv3_securityname": "", "snmpv3_security Level ":" 0 "," snmpv3_authpassphrase ":" "," Snmpv3_privpassphrase ":" "," Snmpv3_authprotoc            Ol ":" 0 "," snmpv3_privprotocol ":" 0 "," snmpv3_contextname ":" "," Formula ":" 1 ",          "Error": "",  "Lastlogsize": "0", "logtimefmt": "", "TemplateID": "22680", "valuemapid": "0", "Delay_flex": "", "params": "", "Ipmi_sensor": "", "Data_type": "0", "auth             Type ":" 0 "," username ":" "," Password ":" "," PublicKey ":" "," Privatekey ":" ",            "Mtime": "0", "lastns": "564054253", "Flags": "0", "InterfaceID": "1", "Port": "", "description": "", "Inventory_link": "0", "Lifetime": "0", "E Valtype ":" 0 "}]," id ": 1}



4. Get historical information of the corresponding monitoring item

In the previous step we obtained the itemid of all the corresponding monitoring items. Now get the historical information for these monitoring items. The information in this interface is updated every minute, so the details of how long it takes to see the individual needs.

$items _result = Array (), foreach ($this->itemids as $k = = $itemid) {if ($this->items[$k] = = ' System.cpu.util[,idl    E] ') {$history = 0;    }else {$history = 3; } $responst = $this->httpclient->request (' POST ', ' http://zabbix.xxxxx.com/zabbix/api_jsonrpc.php ', [' head ers ' = [' content-type ' = ' application/json-rpc ',], ' json ' and ' = ' jsonrpc '                = ' 2.0 ', ' method ' = ' history.get ', ' params ' = [' output ' = ' extend ',                 "History" and "$history", "Itemids" and "SortField" and "The Clock"            ' SortOrder ' = ' DESC ', ' limit ' = ' 1 ',], ' id ' = + 1,    ' Auth ' = $this->token],]);    $body = Json_decode ($responst->getbody ()->getcontents ()); if (property_exists ($body, ' result ')) {$items _result[$this->items[$k]] = $body->result[0]->value;        }else {log::error (Json_encode ($body));    return false; }}


The returned result is:


{    "JSONRPC": "2.0",    "result": [        {            "itemid": "23296",            "clock": "1351090996",            "value": " 0.0850 ",            " ns ":" 563157632 "        },        {    ],    " id ": 1}


The end result should be:


Array:5 [  "system.cpu.util[,idle]" "= 98.9622  " vfs.fs.size[/,total] "=" 42141548544 "  " Vfs.fs.size[/,used] "=" 6917797137 "  " vm.memory.size[available "" = "57394996906"  "vm.memory.size[ Total] "=" 67439050752 "]



Ii. obtaining information directly from the database


The data obtained in this way is not up-to-date (updated hourly). However, the query speed is greatly improved.

Because I am using the Laravel framework to write code, all lazy, do not write the original SQL statement, we do not look.


1. Get HostID from the hosts table via IP

$host _id = host::where (' host ', ' 10.50.150.80 ')->value (' HostID ');

The result returned is: 11101


2, through the HostID from the items table to get items itemid

$items = Array (    ' vm.memory.size[available] ',        //Memory Available value  (KB)    ' vm.memory.size[total] ',            //Total Memory  (KB)    ' system.cpu.util[,idle] ',           //Current CPU idle value (%)    ' vfs.fs.size[/,used] ',              //Current/Disk usage value (KB)    ' Vfs.fs.size[/,total] ',             //Current/Disk total    (KB)); $item _ids = Item::where (' HostID ', 11106)->wherein (' Key_ ', $ Items)->pluck (' itemid ', ' key_ ');


The returned result is:

Collection {#183  #items: array:5 [    "system.cpu.util[,idle]" = = 152511    "vfs.fs.size[/,total]" = 155584    "vfs.fs.size[/,used" "= 155587    " vm.memory.size[available] "= 152533    " vm.memory.size[ Total] "= 152534  ]}

3. Get historical information from trends table or Trends_uint table via Itemid

$result = Array (), foreach ($item _ids as $key = = $item _id) {    if ($key = = ' System.cpu.util[,idle] ') {        $value = Tren D::where (' itemid ', $item _id)->orderby (' clock ', ' DESC ')->value (' Value_avg ');    } else {        $value = trendsuint::where (' itemid ', $item _id)->orderby (' clock ', ' DESC ')->value (' Value_avg ');    }    $result [$key] = $value;}


The returned result is:

Array:5 [  "system.cpu.util[,idle]" "= 98.9622  " vfs.fs.size[/,total] "=" 42141548544 "  " Vfs.fs.size[/,used] "=" 6917797137 "  " vm.memory.size[available "" = "57394996906"  "vm.memory.size[ Total] "=" 67439050752 "]


Related recommendations:

CENTOS7 Installation Zabbix Detailed introduction

Zabbix implementation of mail Alarm example Tutorial

Detailed examples of Zabbix monitoring server time issues

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.