使用用户名密码或ssl证书获取zabbix-api token,批量操作管理zabbix-server

个人博客地址

http://www.darkghost.life

概述

Zabbix API 允许你以编程方式检索和修改 Zabbix 的配置,并提供对历史数据的访问。它广泛用于:

  • 创建新的应用程序以使用Zabbix;
  • 将Zabbix与第三方软件集成;
  • 自动执行常规任务。

Zabbix API 是基于 Web 的API,作为 Web 前端 的一部分提供。它使用 JSON-RPC 2.0 协议,这意味着两点:

  • 该 API 包含一组独立的方法;
  • 客户端和 API 之间的请求和响应使用 JSON 格式进行编码

环境

  zabbix-api

  open-ssl

  python3.6

  requests

安装

sudo apt install zabbix-api
sudo apt install open-ssl
pip3 install requests

api使用方法

在访问 Zabbix 中的任何数据之前,你需要登录并获取身份认证 token。这可以使用user.login方法完成。


zabbix_url='http://10.0.3.108:6588/api_jsonrpc.php' zabbix_user = "Admin" zabbix_pass = "passwd" head={"Content-Type":"application/json"} operate = ZabbixOperates(zabbix_url,zabbix_user,zabbix_pass) data = { "jsonrpc":"2.0", "method":"user.login", "params":{ "user":self.user, "password":self.pwd }, "id":1 } res =requests.post(zabbix_url,headers=head,json=data) token = res.json()['result']

 获取host列表,这里我们可以筛选自己所需的属性

data={
    "jsonrpc": "2.0",
    "method":"host.get",
    "params": {
        "output": [
            "hostid",
            "host",
            "interfaceid"
        ],
        "selectInterfaces": [
            "interfaceid",
            "ip"
        ]
    },
    "id":1,
    "auth":token
    }
res = requests.post(zabbix_url,json=data)
for host in value['result']:
    print(host)
    print('-------------------------------------------------------------')

得到以下输出

dark@dark:~/python$ /usr/bin/python3 /home/ghost/python/zabbix-api/host.py
{'hostid': '10084', 'host': 'Zabbix server', 'interfaces': [{'interfaceid': '1', 'ip': '127.0.0.1'}]}
------------------------------------------------------------------------------
{'hostid': '10318', 'host': 'zabbix-agent', 'interfaces': [{'interfaceid': '2', 'ip': '10.0.3.108'}]}
------------------------------------------------------------------------------
{'hostid': '10319', 'host': 'Juniper-10.0.3.1', 'interfaces': [{'interfaceid': '3', 'ip': '10.0.3.1'}]}
------------------------------------------------------------------------------
{'hostid': '10320', 'host': 'ju_route', 'interfaces': [{'interfaceid': '4', 'ip': '10.0.0.1'}]}
------------------------------------------------------------------------------

使用item.create来创建item,我们需要使用以上获取到的hostid interfaceid属性

data={
    "jsonrpc": "2.0",
    "method": "item.create",
    "params": {
        "name": 1.1.1.1-restime,
        "key_": ping_restime[1.1.1.1],
        "hostid": "10318",
        "type": 0,
        "value_type": 0,
        "interfaceid": "2",
        "delay": '20s',
        'history': '90d',
        'trends': '365d',
        'units': "ms",
        'lifetime': '30d',
    },
    "auth": token,
    "id": 3
    }
if 'result' in value:
    for host in value['result']:
        if isinstance(host,dict):
            for k,v in host.items():
                print(k,v)
        else:
            print(host)
        print('------------------------------------------------------------------------------')
elif 'error' in value:
    print(value['error'])

 

 

创建成功后会返回itemid,如果key存在会返回错误信息,可以做下异常处理

dark@dark:~/python$ /usr/bin/python3 /home/ghost/python/zabbix-api/host.py
{'itemids': ['32918']}


dark@dark:~/python$ /usr/bin/python3 /home/ghost/python/zabbix-api/host.py

{'code': -32602, 'message': 'Invalid params.', 'data': 'Item with key "ping_pkloss[1.1.1.1]" already exists on "zabbix-agent".'}

简单的操作就是这样,如果客户端使用证书加密码登录,只需要在requests.post附带证书信息就行

功能封装

为了日常工作使用起来更为便捷,我们对这些功能做下封装

zabbixoperates.py
只做了host.get和item.create模块,其他模块可根据日常添加习惯进行定义
import requests

class ZabbixOperates:
    def __init__(self,zabbix_url,zabbix_user,zabbix_pass,verify_file=None,ssl_pem=None,ssl_key=None):
        self.zabbix_url = zabbix_url
        self.user=zabbix_user
        self.pwd=zabbix_pass
        self.verify_file,self.ssl_pem,self.ssl_key=verify_file,ssl_pem,ssl_key
        self.head={"Content-Type":"application/json"}
        self.token = self.get_token()
    def get_token(self):
        data = {
        "jsonrpc":"2.0",
        "method":"user.login",
        "params":{
            "user":self.user,
            "password":self.pwd
        },
        "id":1 
        }
        res = requests.post(self.zabbix_url,headers=self.head,json=data,verify=self.verify_file,cert=(self.ssl_pem,self.ssl_key))
        return res.json()['result']
    def reuqest(self,data):
        res = requests.post(self.zabbix_url,json=data,verify=self.verify_file,cert=(self.ssl_pem,self.ssl_key))
        # self.show(res.json())
        return(res.json())
    def show(self,value,filter=None):
        if 'result' in value:
            for host in value['result']:
                if isinstance(host,dict):
                    if filter:
                        for k in filter:
                            v = host[k] if k in host else None
                            print(k,v)
                    else:
                        for k,v in host.items():
                            print(k,v)
                else:
                    print(host)
                print('------------------------------------------------------------------------------')
        elif 'error' in value:
            print(value['error'])
    #通用方法
    def operate(self,data):
        return self.reuqest(data)
    #根据日常工作习惯自定义模板
    def get_host(self):
        data={
            "jsonrpc": "2.0",
            "method":"host.get",
            "params": {
                "output": [
                    "hostid",
                    "host",
                    "interfaceid"
                ],
                "selectInterfaces": [
                    "interfaceid",
                    "ip"
                ]
            },
            "id":1,
            "auth":self.token
            }
        return self.reuqest(data)
    def get_item(self,*value):
        hostid,key=value
        data = {
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": "extend",
                    "hostids": hostid,
                    "search": {
                        "key_": key
                    },
                    "sortfield": "name"
                },
                "auth": self.token,
                "id": 1
                }
        return self.reuqest(data)
    def create_item(self,*value):
        hostid,interfaceid,name,key,units=value
        data={
            "jsonrpc": "2.0",
            "method": "item.create",
            "params": {
                "name": name,
                "key_": key,
                "hostid": hostid,
                "type": 0,
                "value_type": 0,
                "interfaceid": interfaceid,
                "delay": '20s',
                'history': '90d',
                'trends': '365d',
                'units': units,
                'lifetime': '30d',
            },
            "auth": self.token,
            "id": 3
            }
        return self.reuqest(data)
    
    def get_graph(self,*value):
        hostid = value
        data = {
                "jsonrpc": "2.0",
                "method": "graph.get",
                "params": {
                    "output": "extend",
                    "hostids": hostid,
                    "sortfield": "name",
                    "selectGraphItems":'gitemid',
                },
                "auth": self.token,
                "id": 1
                }
        return self.reuqest(data)

 

 

使用方法

from zabbixoperates import ZabbixOperates
if __name__ == '__main__':
    verify_file = '/home/ghost/ghost.pem'
    ssl_pem = '/home/ghost/ghost.pem'
    ssl_key = '/home/ghost/ghost.key'
    zabbix_url='https://ex.zabbix.com/api_jsonrpc.php'
    zabbix_user   = "Admin"
    zabbix_pass   = "passwd"
    operate = ZabbixOperates(zabbix_url,zabbix_user,zabbix_pass,verify_file,ssl_pem,ssl_key)
    #获取host
    operate.get_host()
    #创建item
    for host in ['1.1.1.1','2.2.2.2']:
        operate.create_item('10318','2',host+'-restime','ping_restime[%s]'%host,'ms')
        operate.create_item('10318','2',host+'-pkloss','ping_pkloss[%s]'%host,'%')
    #原始数据,通过operate方法执行
    data={
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": "extend",
            "hostids": "11148",
            "search": {
                "key_": "ping_"
            },
            "sortfield": "name"
        },
        "auth": operate.token,
        "id": 1
        }
    operate.operate(data)

确认结果

 

 

posted @ 2022-05-16 10:35  无限's-blog  阅读(344)  评论(0编辑  收藏  举报