作用:

当我们需要通过API调用ZABBIX各项数据的时候,首先需要通过用户名和密码,连接ZABBIX,获取ZABBIX返回给我们的授权密钥,后续调用API各种方法的时候,只需要复制该授权密钥就可以直接访问。

官方API文档:https://www.zabbix.com/documentation/3.4/zh/manual/api

代码:

#Author Kang

import json
from urllib import request, parse

ZABBIX_URL = 'http://10.3.153.14:9000'
ZABBIX_USERNAME = "admin"
ZABBIX_PASSWORD = "admin的登陆密码"

#zabbix的url请求访问地址
url = "{}/api_jsonrpc.php".format(ZABBIX_URL)

#申请头部内容
header = {"Content-Type": "application/json"}

# auth user and password
data = {
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
        "user": ZABBIX_USERNAME,
        "password": ZABBIX_PASSWORD
    },
    "id": 1,
}
# 由于API接收的是json字符串,故需要转化一下
value = json.dumps(data).encode('utf-8')

# 对请求进行包装
req = request.Request(url, headers=header, data=value)

# 验证并获取Auth ID
try:
    # 打开包装过的url
    result = request.urlopen(req)
except Exception as e:
    print("Auth Failed, Please Check Your Name And Password:", e)
else:
    response = result.read()
    # 上面获取的是bytes类型数据,故需要decode转化成字符串
    page = response.decode('utf-8')
    # 将此json字符串转化为python字典
    page = json.loads(page)
    result.close()
    print("Auth Successful. The Auth ID Is: {}".format(page.get('result')))

结果:

Auth Successful. The Auth ID Is: d9fc47c6b8a956f6e6fd17e23eea61d7
备注:ID值就是我们后续需要使用的授权ID