Zabbix: first experience of zabbix API

Xiaosheng blog: http://xsboke.blog.51cto.com

        -------Thank you for your reference. If you have any questions, welcome to exchange

When you have a large number of machines to monitor, are you still doing a lot of repetitive operations (for example, if you want to create an aggregate graph, hundreds of graphs need to be added below the aggregate graph)
This article may relieve your troubles and free your hands

This article uses an example [create aggregate graph according to the name of graph] to let you understand how to use the zabbix api

Environmental Science:

    python==3.7
    requests==2.21.0

Document introduction:

    config.py   # Store global variables
    base.py     # Program code

1,config.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-

http_url = 'http://192.168.0.1/zabbix/api ﹣ the url of your ZABBIX file API ﹣ jsonrpc.php
headers = {'Content-Type':'application/json-rpc'}
jsonrpc = '2.0'
username = 'admin'  # zabbix user name
password = 'zabbix' # zabbix password

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):
        '''
        //Send post request to zabbix server
        :param u: Requested url
        :param d: Submitted data
        :param h: http Header information
        :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):
        '''
        //Get token
        :param user: zabbix User name
        :param passwd: zabbix Password
        :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):
        '''
        //Get monitored host information
        :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):
        '''
        //Get all graphics
        :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):
        '''
        //Get all the screen graphs
        :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, ):
        '''
        //Create aggregate graphics
        :param name: Name of the aggregate drawing
        :param resourceidlist: Projects that need to be added to specific drawings id(If it is graph then is graphid)
        :param hsize: Define column number
        :param type: Specified type,The default is[Graphical]
        :return:
        '''
        vsize = len(resourceidlist) // 3 + 1
        x = 0
        y = 0

        # Generate the list of items required by screenitems
        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

# Instantiate the program to obtain all graph information
handler = base()
hostinfo = handler.get_graph

# Filter out all drawing names
graph_name_list = []
for host in hostinfo:
    graph_name_list.append(host['name'])

graph_name_list = list(set(graph_name_list))

# Assign the graphid list to the corresponding key according to the graph name
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

# Group by drawing name to generate aggregate drawing
for gname,gid_list in dict.items():
    handler.create_screen(name=gname,resourceidlist=gid_list)

Tags: Operation & Maintenance Zabbix JSON Python PHP

Posted on Sun, 10 Nov 2019 16:56:52 -0500 by jassikundi