Python zabbix api 获取图形

蓝蓝 · 2020年06月24日 · 1970 次阅读

一.背景

因为接口压测平台需要获取接口服务器的性能数据,所以找了一圈 zabbix api 获取数据的方式,以此记录下来。

zabbix api 地址:https://www.zabbix.com/documentation/3.4/zh/manual/api 功能还真挺多,挺详细的。

二.zabbix api 获取方式

1.获取 token

url = "http://ip/zabbix/api_jsonrpc.php"
header = {
    "Content-Type": "application/json"
}

def get_token():
    data = {"jsonrpc": "2.0", "method": "user.login", "params": {"user": "xxx", "password": "xxx"},
            "id": 1, "auth": None}
    resp = requests.post(url, json=data, headers=header)
    print(resp.status_code)
    print(resp.text)
    if resp.status_code == 200:
        json_data = json.loads(resp.text)
        return json_data['result']
    return None

2.获取服务器 ip,这个可以获取到 hostid

def get_machine():
    auth = get_token()
    data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": [
                "hostid",
                "host"
            ],
            "selectInterfaces": [
                "interfaceid",
                "ip"
            ]
        },
        "id": 2,
        "auth": auth
    }
    resp = requests.post(url, json=data, headers=header)
    print(resp.status_code)
    print(resp.text)

3.获取 graphid

def get_graph():
    auth = get_token()
    data = {
        "jsonrpc": "2.0",
        "method": "graph.get",
        "params": {
            "output": "extend",
            "hostids": 10351,
            "sortfield": "name"
        },
        "auth": auth,
        "id": 1
    }
    resp = requests.post(url, json=data, headers=header)
    print(resp.status_code)
    print(resp.text)

4.获取图形写入文件

def get_png():
    token = get_token()
    print(token)
    header = {
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Cookie": "PHPSESSID=2bvctu9rva99ppd74gaopb8i42; zbx_sessionid=" + token,
        "Pragma": "no-cache",
        "Upgrade-Insecure-Requests": "1"
    }
    charUrl = "http://ip/zabbix/chart2.php?graphid=3396&period=120&stime=20200624103155&isNow=0&profileIdx=web.graphs&profileIdx2=3396&width=682&sid=96b019eb208dec18&screenid=&curtime=1592965915667"
    resp = requests.get(charUrl, headers=header)
    with open("test_img.png", 'wb') as f:
        f.write(resp.content)

关键参数:

charUrl可以从 graphs 查询的图片,然后右击 - 复制图片地址获取到

graphid=3396这个就是 graph 下拉那块的 id,有 CPU、流量等,上面有方法通过 hostid 可以获取到

period=120这个单位秒,即获取 2 分钟的图形,可以随便改

stime=20200624103155开始时间,意思很明朗;所以其实获取的图形,就是从 stime 到 stime+period 这段的图形

width=682这个是图片宽度

isNow=0默认是 1,就是 5 分钟时长的图形,改为 0 后,period 就起作用了

总结:简单记录 api 获取方式,但是其实我是想获取 CPU 的数据,不是图形,还在琢磨能不能获取到一段时间的平均值。有知道的请告诉我哇~~

有问题请指出哦~~

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册