Zabbix:zabbix API初体験


小生ブログ:http://xsboke.blog.51cto.com
        -------      ,    ,    

大量の機械が監視する必要がある場合、あなたはまだ大量の繰り返し操作をしているかどうか(例えば、集約図形を作成したい場合、この集約図形の下に100以上のgraphを追加する必要があります).この文章はあなたの悩みを解消し、両手を解放することができるかもしれません.
この記事では、zabbix apiの使用方法について説明する[graphの名前に基づいて集約グラフィックを作成する]例を示します.
環境:
    python==3.7
    requests==2.21.0

ファイルの紹介:
    config.py   #       
    base.py     #     

1、config.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

http_url = 'http://192.168.0.1/zabbix/api_jsonrpc.php'  #   zabbix  api_jsonrpc.php   url
headers = {'Content-Type':'application/json-rpc'}
jsonrpc = '2.0'
username = 'admin'  # zabbix   
password = 'zabbix' # zabbix  

2、base.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import random
import requests

import config

class base:
    def __init__(self):
        self.jsonrpc = config.jsonrpc
        self.headers = config.headers
        self.url = config.http_url
        jsonrpc, result, id = self._get_user_token(user=config.username, passwd=config.password)
        self.auth = result
        self.id = id

    def _get_identifier(self):
        str = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()1234567890'
        iden = ''
        i = 0
        length = 10
        while i < length:
            s = random.choice(str)
            iden += s
            i += 1

        return iden

    def _post(self, u, d, h):
        '''
         zabbix     post  
        :param u:    url
        :param d:      
        :param h: http   
        :return:
        '''
        jsondata = json.dumps(d)
        r = requests.post(url=u, data=jsondata, headers=h)
        r.encoding = 'utf-8'
        transfer = json.loads(r.text)
        jsonrpc, result, id = transfer['jsonrpc'], transfer['result'], transfer['id']

        return jsonrpc, result, id

    def _get_user_token(self, user, passwd):
        '''
          token
        :param user: zabbix   
        :param passwd: zabbix  
        :return:
        '''
        data = {'jsonrpc': self.jsonrpc,
                'method': 'user.login',
                'params': {'user': user,
                           'password': passwd
                           },
                'id': self._get_identifier(),
                'auth': None
                }
        jsonrpc, result, id = self._post(u=self.url, d=data, h=self.headers)

        return jsonrpc, result, id

    @property
    def get_host(self):
        '''
                 
        :return:
        '''
        data = {"jsonrpc": self.jsonrpc,
                "method": "host.get",
                "params": {"output": ["hostid",
                                      "host"
                                      ],
                           "selectInterfaces": ["interfaceid",
                                                "ip"
                                                ]
                           },
                "id": self.id,
                "auth": self.auth
                }

        jsonrpc, result, id = self._post(u=self.url, d=data, h=self.headers)

        return result

    @property
    def get_graph(self):
        '''
               (graph)
        :return:
        '''
        hostid_list = [host['hostid'] for host in self.get_host]

        result_list = []
        for hid in hostid_list:
            data = {"jsonrpc": self.jsonrpc,
                    "method": "graph.get",
                    "params": {"output": "extend",
                               "hostids": int(hid),
                               "sortfield": "name"
                               },
                    "id": self.id,
                    "auth": self.auth
                    }

            jsonrpc, result, id = self._post(u=self.url, d=data, h=self.headers)
            result_list.extend(result)

        return result_list

    @property
    def get_screen(self):
        '''
                 (screen graph)
        :return:
        '''
        data = {"jsonrpc": self.jsonrpc,
                "method": "screen.get",
                "params": {"output": "extend",
                           "selectScreenItems": "extend",
                           },
                "id": self.id,
                "auth": self.auth
                }

        jsonrpc, result, id = self._post(u=self.url, d=data, h=self.headers)

        return result

    def create_screen(self, name, resourceidlist, hsize=3, type=0, ):
        '''
              
        :param name:        
        :param resourceidlist:              id(   graph  graphid)
        :param hsize:     
        :param type:     ,   [  ]
        :return:
        '''
        vsize = len(resourceidlist) // 3 + 1
        x = 0
        y = 0

        #   screenitems   item  
        params_list = []
        for resourceid in resourceidlist:
            params_dict = {}
            params_dict['resourcetype'] = int(type)
            params_dict['resourceid'] = resourceid
            params_dict['rowspan'] = 1
            params_dict['colspan'] = 1
            if x < hsize:
                params_dict['x'] = x
                params_dict['y'] = y
            else:
                x = 0
                y += 1
                params_dict['x'] = x
                params_dict['y'] = y
            x += 1
            params_list.append(params_dict)

        data = {"jsonrpc": self.jsonrpc,
                "method": "screen.create",
                "params": {"name": name,
                           "hsize": hsize,
                           "vsize": vsize,
                           "screenitems": [screenitem for screenitem in params_list]
                           },
                "id": self.id,
                "auth": self.auth
                }

        jsonrpc, result, id = self._post(u=self.url, d=data, h=self.headers)
        return result

#      ,     graph  
handler = base()
hostinfo = handler.get_graph

#           
graph_name_list = []
for host in hostinfo:
    graph_name_list.append(host['name'])

graph_name_list = list(set(graph_name_list))

#       , graphid        key
dict = {}
for graph_name in graph_name_list:
    gid_list = []
    for host in hostinfo:
        if graph_name == host['name']:
            gid_list.append(host['graphid'])
    dict[graph_name] = gid_list

#         ,      
for gname,gid_list in dict.items():
    handler.create_screen(name=gname,resourceidlist=gid_list)