参考官方手册:https://www.zabbix.com/documentation/2.2/manual/api/reference
#!/usr/bin/python# -*- coding: utf-8 -*-import urllib2import sysimport jsonclass zabbixtools: def __init__(self): self.url = "http://192.168.6.116/zabbix/api_jsonrpc.php" self.header = {"Content-Type": "application/json"} self.authID = self.user_login() def user_login(self): data = json.dumps( { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "admin123", "password": "hxage.123" }, "id": 0 }) request = urllib2.Request(self.url,data) for key in self.header: request.add_header(key,self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "Auth Failed, Please Check Your Name And Password:",e.code else: response = json.loads(result.read()) result.close() authID = response['result'] return authID def get_data(self,data,hostip=""): request = urllib2.Request(self.url,data) for key in self.header: request.add_header(key,self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: if hasattr(e,'reason'): print "we Failed to reach a server" print 'reason:',e.reason elif hasattr(e,'code'): print "the server could not fulfaild the request" print "error code:",e.code return 0 else: response = json.loads(result.read()) result.close() return response def host_get(self,hostip): # 生成json格式数据 data = json.dumps( { "jsonrpc": "2.0", "method": "host.get", "params": { "output":["hostid","name","status","host"], "filter": {"host": [hostip]} }, "auth": self.authID, "id": 1 }) res = self.get_data(data)['result'] if (res != 0) and (len(res) != 0): host = res[0] # print host if host['status'] == 1: print "\x1b[1;32mHost_IP: %s Host_Name: %s down\x1b[0m" % (host['host'],host['name']) return host['hostid'] else: print "\x1b[1;32mHost_ip: %s Host_Name: %s up\x1b[0m" % (host['host'],host['name']) return host['hostid'] else: print "host_get error please check define host_get()" return 0 def hostgroup_get(self): data = json.dumps( { "jsonrpc":"2.0", "method":"hostgroup.get", "params":{ "output":"extend" }, "auth":self.authID, "id":1 }) res = self.get_data(data) if 'result' in res.keys(): res = res['result'] # print res if (res != 0) and (len(res) != 0): for host in res: print "\x1b[1;32mHost_id: %s Hostgroup_name: %s\x1b[0m" % (host['groupid'],host['name']) else: print "Host_Group info Gets the Error" def template_get(self): data = json.dumps( { "jsonrpc":"2.0", "method":"template.get", "params":{ "output":"extend" }, "auth":self.authID, "id":1 }) res = self.get_data(data) if 'result' in res.keys(): res = res['result'] if (res != 0) and (len(res) != 0): for host in res: print "\x1b[1;32mTemplate_id: %s Template_name: %s\x1b[0m" % (host['templateid'],host['name']) else: print "Templateid gets the error" def host_delete(self): hostip = raw_input("please input your delete hostip:") hostid = self.host_get(hostip) if hostid == 0: print "\x1b[1;31mhost_get error please check it" sys.exit() # print hostid data = json.dumps( { "jsonrpc":"2.0", "method":"host.delete", "params":[{"hostid":hostid}], "auth":self.authID, "id":1 }) res = self.get_data(data)['result'] if 'hostids' in res.keys(): print "\x1b[1;32m%s删除成功!!!\x1b[0m" % hostip else: print "\x1b[1;31m%s删除失败!!!\x1b[0m" % hostip def host_create(self): hostip = raw_input("please input hostip:") groupid = raw_input("please input groupid:") templateid = raw_input("please input templateid:") g_list = [] t_list = [] for i in groupid.split(','): var = {} var['groupid'] = i g_list.append(var) for i in templateid.split(','): var = {} var['templateid'] = i t_list.append(var) if hostip and groupid and templateid: data = json.dumps( { "jsonrpc":"2.0", "method":"host.create", "params":{ "host":hostip, "interfaces":[ { "type":1, "main":1, "useip":1, "ip":hostip, "dns":"", "port":"10050", } ], "groups":g_list, "templates":t_list }, "auth":self.authID, "id":1 }) res = self.get_data(data,hostip) if 'result' in res: res = res['result'] if 'hostids' in res.keys(): print "\x1b[1;32m%s \t\t主机添加成功\x1b[0m" % hostip else: print "\x1b[1;31m%s \t\t主机添加失败\x1b[0m" % hostip else: print "您输入的参数有误."if __name__ == '__main__': num = raw_input('\x1b[1;30mplease input 1(create host) or 2(delete host)?\x1b[0m') if not num.strip(): print "Your input num is null!!!" if num == str(1): a = zabbixtools() a.hostgroup_get() a.template_get() a.host_create() elif num == str(2): a = zabbixtools() a.host_delete() else: print "you input num noteq 1 or 2"
原文地址:Python调用Zabbix Api 添加和删除主机, 感谢原作者分享。 流转的时光,都成为命途中美丽的点缀,