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)
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'])) 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')
|