python调用zabbix api 获取主机cpumemdisk
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python调用zabbix api 获取主机cpumemdisk相关的知识,希望对你有一定的参考价值。
1.代码
# -*- coding:utf-8 -*-
import requests
import json
class Zabbix:
def __init__(self, username=None, password=None):
self.headers = {
‘Content-Type‘: ‘application/json-rpc‘
}
self.url = ‘https://www.xxx.com/zabbix/api_jsonrpc.php‘ #替换为具体的zabbix地址
if username and password:
self.username = username
self.password = password
else:
self.username = ‘Admin‘
self.password = ‘admin‘
def _token(self): #获取token
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.username,
"password": self.password
},
"id": 1,
"auth": None
}
r = requests.post(url=self.url, headers=self.headers, data=json.dumps(data))
token = json.loads(r.content).get("result")
return token
def all_hostid(self): #获取所有主机的hostid
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host",
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 2,
"auth": self._token()
}
r = requests.post(url=self.url, headers=self.headers, data=json.dumps(data))
hosts = json.loads(r.content)
for i in hosts[‘result‘]:
yield i
def get_hostid_by_ip(self, ip=None): #通过ip地址获取主机的hostid
hostid = ""
if ip is None:
print("ip address is None")
return hostid
for i in self.all_hostid():
if i["interfaces"][0]["ip"] == ip:
hostid = i[‘hostid‘]
break
return hostid
def get_item_data(self, ip=None, item=None): #获取item 最新数据,item自定义
hostid = self.get_hostid_by_ip(ip)
data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": hostid,
"search": {
"key_": item
}
},
"id": 0,
"auth": self._token()
}
r = requests.post(url=self.url, headers=self.headers, data=json.dumps(data))
res = json.loads(r.content)
return res["result"][0]["lastvalue"]
def get_mem_total(self, ip): #获取内存总数
return str(int(int(self.get_item_data(ip, ‘vm.memory.size[total]‘)) / 1024**3)) + ‘G‘
def get_disk(self, ip): #获取系统磁盘大小
return str(int(int(self.get_item_data(ip, ‘vfs.fs.size[/,total]‘)) / 1000**3)) + ‘G‘
def get_cpu_num(self, ip): #获取cpu核数
return self.get_item_data(ip, ‘system.cpu.num‘)
if __name__ == "__main__":
zabbix = Zabbix()
ip = "10.19.1.101"
print(zabbix.get_disk(ip))
print(zabbix.get_mem_total(ip))
print(zabbix.get_cpu_num(ip))
- 获取zabbix其他的监控数据,可以通过get_item_data() 方法,传入不同的item,如:system.cpu.util[,idle],vm.memory.size[available]等等
以上是关于python调用zabbix api 获取主机cpumemdisk的主要内容,如果未能解决你的问题,请参考以下文章
python 调用zabbix api实现查询主机信息,输出所有主机ip
python 调用zabbix api实现查询主机信息,输出所有主机ip