小生博客:http://xsboke.blog.51cto.com

        -------谢谢您的参考,如有疑问,欢迎交流

当你有大量机器需要监控时,你是否还在做大量的重复性操作(比如你想创建一个聚合图形,这个聚合图形下面需要添加上百个graph).
这篇文章也许可以解除你的烦恼,解放你的双手.

此篇文章通过一个示例 [根据graph的名字创建聚合图形] 让大家理解有关zabbix api的使用方法

环境:

    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)