python程序调用zabbix系统的api接口实现对zabbix_server端主机的增删改查,使用相关功能时候,需要打开脚本中的相关函数。
函数说明:
zabbixtools() 调用zabbix api
template_get() 获取zabbix server端已经配置的模板信息
hostgroup_get() 获取已经添加的主机组列表信息
host_get() 单个主机信息
host_del() 删除主机
host_create() 新建主机
get_grouphost() 获取某个组下面所有的主机信息
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import json 4 import urllib2 5 import sys 6 class zabbixtools: 7 def __init__(self): 8 self.url = "http://x.x.x.x/zabbix/api_jsonrpc.php" 9 self.header = {"Content-Type": "application/json"} 10 self.authID = self.user_login() 11 def user_login(self): 12 data = json.dumps( 13 { 14 "jsonrpc": "2.0", 15 "method": "user.login", 16 "params": { 17 "user": "Admin", 18 "password": "xxxx" 19 }, 20 "id": 0 21 }) 22 request = urllib2.Request(self.url,data) 23 for key in self.header: 24 request.add_header(key,self.header[key]) 25 try: 26 result = urllib2.urlopen(request) 27 except URLError as e: 28 print "Auth Failed, Please Check Your Name And Password:",e.code 29 else: 30 response = json.loads(result.read()) 31 result.close() 32 authID = response['result'] 33 return authID 34 def get_data(self,data,hostip=""): 35 request = urllib2.Request(self.url,data) 36 for key in self.header: 37 request.add_header(key,self.header[key]) 38 try: 39 result = urllib2.urlopen(request) 40 except URLError as e: 41 if hasattr(e, 'reason'): 42 print 'We failed to reach a server.' 43 print 'Reason: ', e.reason 44 elif hasattr(e, 'code'): 45 print 'The server could not fulfill the request.' 46 print 'Error code: ', e.code 47 return 0 48 else: 49 response = json.loads(result.read()) 50 result.close() 51 return response 52 def host_get(self,hostip): 53 #hostip = raw_input(" 33[1;35;40m%s 33[0m" % 'Enter Your Check Host:Host_ip :') 54 data = json.dumps( 55 { 56 "jsonrpc": "2.0", 57 "method": "host.get", 58 "params": { 59 "output":["hostid","name","status","host"], 60 "filter": {"host": [hostip]} 61 }, 62 "auth": self.authID, 63 "id": 1 64 }) 65 res = self.get_data(data)['result'] 66 if (res != 0) and (len(res) != 0): 67 #for host in res: 68 host = res[0] 69 if host['status'] == '1': 70 print " ","