蒙珣的博客

活好当下,做好今天该做的事情。

0%

Zabbix API

Zabbix API 半成品,可能会后续更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import json
import requests

class ZabbixAPI:
def __init__(self, host, user, password) -> None:
self.host = "http://" + host + "/zabbix/api_jsonrpc.php"
self.user = user
self.password = password

def apiCall(self,data):
headers = {"Content-Type": "application/json"}
data = json.dumps(data)
response = requests.post(self.host, data, headers=headers)
responseResult = json.loads(response.text)
return responseResult

def login(self):
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.user,
"password": self.password
},
"id": 0
}
response = self.apiCall(data)
return response['result']

def addZabbixHost(self,host,port):
data = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": host,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": host,
"dns": "",
"port": port
}
],
"groups": [
{
"groupid": "4"
}
],
"templates": [
{
"templateid": "10001"
}
]
},
"auth": self.login(),
"id": 1
}
response = self.apiCall(data)
if 'error' in response:
print("ERROR:addZabbixHost()报错 " + response['error']['data'])
else:
print("添加监控主机成功:" + str(response['result']['hostids']))
# 返回主机列表
return response['result']['hostids']

def getItems(self,host):
data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"host": host, # 需要监控的主机
"search": {
"key_": "system.cpu.util[,idle]" # 监控项类型为"系统监控"
}
},
"auth": self.login(),
"id": 1,
}
response = self.apiCall(data)
print(response)
#return response["result"]

# 检查已经添加的主机,并返回hostid列表
def checkHost(self):
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ["host"]
},
"auth": self.login(),
"id": 1
}
response = self.apiCall(data)
hostidList = []
for i in response['result']:
hostidList.append(i['hostid'])
print("已经添加的主机有:" + str(i['hostid']))
# 返回查询到的主机hostid列表
return hostidList

# 导出配置
def exportConf(self,hostidList=None):
if hostidList is None:
hostidList = self.checkHost()
data = {
"jsonrpc": "2.0",
"method": "configuration.export",
"params": {
"options": {
"hosts": hostidList
},
"format": "xml"
},
"auth": self.login(),
"id": 1
}
response = self.apiCall(data)
# 暂时不知道要干嘛,只是打印出来
print(response)

p = ZabbixAPI('172.22.144.81', 'Admin', 'zabbix')
p.getItems('172.22.144.81')