調用ZABBIX的API獲取節點主機信息小記

需求背景

在ZABBIX服務端能夠看到各個節點客戶端主機的詳細信息,可是觀察各個節點時,同一時刻只能觀察到一個,以下圖所示。
圖片描述php

如今想將全部節點主機的一些信息經過腳本調用API讀取出來,錄入到數據庫,以供其餘模塊使用,查了一些相關資料,將大概思路記錄下來。node

實現方案

ZABBIX API的官方網址:https://www.zabbix.com/docume...
Python的zabbix-api網址:https://github.com/gescheit/s...
使用zabbix-api這個python第三方庫讓開發變得更爲簡潔。python

一、安裝zabbix-api
首先要安裝這個第三方庫,一個命令就能夠搞定:git

# pip install zabbix-api

這裏使用pip進行安裝,沒有安裝pip的童鞋請自行百度安裝pipgithub

二、獲取各個節點主機的信息
(1)首先要鏈接並登陸zabbix服務端,兩條語句就能夠搞定(開源是多麼重要呀)數據庫

#!/usr/bin/env python
#coding=utf-8

from zabbix_api import ZabbixAPI

server = "your server address"
username = "your user name"
password = "your password"

zapi = ZabbixAPI(server=server, path="", log_level=6)
zapi.login(username, password)

看看,是否是很簡單,固然也能夠本身寫,有興趣的能夠看看相關資料。此時運行一下,能夠看到相關打印:json

20: url: http://xxxxx/zabbix//api_jsonrpc.php
10: Trying to login with 'xxxxx':'md5(xxxxx)'
10: json_obj: {'params': {'password': 'xxxxx', 'user': 'xxxxx'}, 'jsonrpc': '2.0', 'method': 'user.login', 'id': 0}
20: Sending: {"params": {"password": "xxxxx", "user": "xxxxx"}, "jsonrpc": "2.0", "method": "user.login", "id": 0}
10: Sending headers: {'Content-Type': 'application/json-rpc', 'User-Agent': 'python/zabbix_api'}
20: Response Code: 200
10: Response Body: {u'jsonrpc': u'2.0', u'result': u'271eca6ecbd4640c33f822cfaea4f0b5', u'id': 0}

Response Code爲200,應該都知道,表示請求成功了.api

(2)獲取節點主機
因爲個人節點主機都在同一"Host groups"下面,所以我一次性獲取所有節點主機的信息。好了,這是須要將API文檔拿出來查閱。由於是獲取相關信息,因此使用hostgroup.get這個API函數。這個API函數說明在這裏:https://www.zabbix.com/docume...
如今簡單的貼下一代碼:數據結構

hostgroup_name = "your host group name"

hostids = zapi.hostgroup.get(
                              {
                                  "filter": 
                                  {
                                      "name": hostgroup_name
                                  }, 
                                  "selectHosts": ["hostid", "host"]
                              }
                             )
print json.dumps(hostids, indent=4)

在這個json語句中,有個關鍵參數filter,查閱官方文檔:
圖片描述
這裏只返回名爲"hostgroup_name",即你本身的hostgroup分組下面的全部主機。我這裏只返回這些主機的"hostid"和"host"。
注意,zapi.hostgroup.get返回的是python數據結構,爲了方便調試代碼,print時注意把python數據結構在轉化爲json文件,打印信息以下。app

10: json_obj: {'params': {'filter': {'name': 'xxxxx'}, 'selectHosts': ['hostid', 'host']}, 'jsonrpc': '2.0', 'method': 'hostgroup.get', 'auth': u'af7401886734c31defdface109ed171e', 'id': 1}
20: Sending: {"params": {"filter": {"name": "xxxxx"}, "selectHosts": ["hostid", "host"]}, "jsonrpc": "2.0", "method": "hostgroup.get", "auth": "af7401886734c31defdface109ed171e", "id": 1}
10: Sending headers: {'Content-Type': 'application/json-rpc', 'User-Agent': 'python/zabbix_api'}
20: Response Code: 200
10: Response Body: {u'jsonrpc': u'2.0', u'result': [{u'hosts': [{u'host': u'pc00000011.mknode.cn', u'hostid': u'10274'}, {u'host': u'pc00000013.mknode.cn', u'hostid': u'10275'}, {u'host': u'pc00000015.mknode.cn', u'hostid': u'10276'}, {u'host': u'pc00000012.mknode.cn', u'hostid': u'10277'}, {u'host': u'pc00000016.mknode.cn', u'hostid': u'10278'},  u'internal': u'0', u'flags': u'0', u'groupid': u'15', u'name': u'xxxxx'}], u'id': 1}
[
    {
        "hosts": [
            {
                "host": "pc00000011.mknode.cn", 
                "hostid": "10274"
            }, 
            {
                "host": "pc00000013.mknode.cn", 
                "hostid": "10275"
            }, 
            {
                "host": "pc00000015.mknode.cn", 
                "hostid": "10276"
            }, 
            {
                "host": "pc00000012.mknode.cn", 
                "hostid": "10277"
            }, 
            {
                "host": "pc00000016.mknode.cn", 
                "hostid": "10278"
            }, 
        ], 
        "internal": "0", 
        "flags": "0", 
        "groupid": "15", 
        "name": "xxxxx"
    }
]

關於json.dumps()、json.loads():
json.dumps():dict轉爲str
json.loads():str轉爲dict

(3)獲取節點主機具體信息
這個就太豐富啦,具體問題看具體API,這裏以查看內存剩餘容量爲例吧。

memfree_get = zapi.item.get(
                             {
                                "hostids": [host_cnt['hostid']],
                                "filter": {
                                            "key_": ["vm.memory.size[available]"]
                                             # "name": ["Available memory"]
            }
    })
    memfree_get_last = memfree_get[0]["lastvalue"]
    print json.dumps(memfree_get,indent=4)

查看打印信息:

10: Response Body: {u'jsonrpc': u'2.0', u'result': [{u'itemid': u'29401', u'username': u'', u'snmpv3_contextname': u'', u'inventory_link': u'0', u'mtime': u'0', u'authtype': u'0', u'trends': u'365d', u'snmpv3_authpassphrase': u'', u'snmp_oid': u'', u'snmpv3_securitylevel': u'0', u'port': u'', u'lastns': u'31272984', u'master_itemid': u'0', u'logtimefmt': u'', u'jmx_endpoint': u'', u'delay': u'1m', u'publickey': u'', u'state': u'0', u'params': u'', u'snmpv3_securityname': u'', u'formula': u'', u'type': u'7', u'snmpv3_authprotocol': u'0', u'prevvalue': u'3426082816', u'status': u'0', u'lastlogsize': u'0', u'lastclock': u'1523192709', u'snmp_community': u'', u'description': u'Available memory is defined as free+cached+buffers memory.', u'evaltype': u'0', u'trapper_hosts': u'', u'lastvalue': u'3425476608', u'units': u'B', u'value_type': u'3', u'templateid': u'22181', u'snmpv3_privprotocol': u'0', u'password': u'', u'interfaceid': u'0', u'snmpv3_privpassphrase': u'', u'hostid': u'10276', u'key_': u'vm.memory.size[available]', u'name': u'Available memory', u'privatekey': u'', u'lifetime': u'0', u'valuemapid': u'0', u'flags': u'0', u'error': u'', u'ipmi_sensor': u'', u'history': u'1w'}], u'id': 19}
[
    {
        "itemid": "29401", 
        "username": "", 
        "snmpv3_contextname": "", 
        "inventory_link": "0", 
        "mtime": "0", 
        "authtype": "0", 
        "trends": "365d", 
        "snmpv3_authpassphrase": "", 
        "snmp_oid": "", 
        "snmpv3_securitylevel": "0", 
        "port": "", 
        "lastns": "31272984", 
        "master_itemid": "0", 
        "logtimefmt": "", 
        "jmx_endpoint": "", 
        "delay": "1m", 
        "publickey": "", 
        "state": "0", 
        "params": "", 
        "snmpv3_securityname": "", 
        "formula": "", 
        "type": "7", 
        "snmpv3_authprotocol": "0", 
        "prevvalue": "3426082816", 
        "status": "0", 
        "lastlogsize": "0", 
        "lastclock": "1523192709", 
        "snmp_community": "", 
        "description": "Available memory is defined as free+cached+buffers memory.", 
        "evaltype": "0", 
        "trapper_hosts": "", 
        "lastvalue": "3425476608", 
        "units": "B", 
        "value_type": "3", 
        "templateid": "22181", 
        "snmpv3_privprotocol": "0", 
        "password": "", 
        "interfaceid": "0", 
        "snmpv3_privpassphrase": "", 
        "hostid": "10276", 
        "key_": "vm.memory.size[available]", 
        "name": "Available memory", 
        "privatekey": "", 
        "lifetime": "0", 
        "valuemapid": "0", 
        "flags": "0", 
        "error": "", 
        "ipmi_sensor": "", 
        "history": "1w"
    }
]

此次以json格式打印的優點就凸顯出來了,」Response Body「爲未進行json轉碼前的python數據結構。若是不知道剩餘內存容量該怎麼從memfree_get中取出,能夠從打印信息中查看,很顯然,字段"lastvalue"就是最新剩餘內存值:

memfree_get_last = memfree_get[0]["lastvalue"]

這樣咱們就將該值取出,錄入數據庫就OK了,獲取其餘信息也是一樣的道理。

這裏須要說明的是,我前面獲取的是全部節點主機的信息,而我是每獲取完一個節點主機就會錄入數據庫,因此採用了循環遍歷全部節點主機信息。"hostids": [host_cnt['hostid']]就指當前的主機信息。

總結

一、有問題,看文檔二、合理利用第三方庫,讓開發變得更加高效

相關文章
相關標籤/搜索