首页 > 代码库 > zabbix的api统计zabbix监控的主机数量与主机名
zabbix的api统计zabbix监控的主机数量与主机名
python通过zabbix的api获取监控的主机名和主机数量
#!/usr/bin/env python# -*- encoding: utf8 -*-#导入模块,urllib2是一个模拟浏览器HTTP方法的模块import jsonimport urllib2import sysimport smtplibfrom urllib2 import Request,urlopen,URLError,HTTPError#url and url header#zabbix的API地址、用户名、密码、这里修改为实际的参数zabbix_url="http://ip/api_jsonrpc.php"zabbix_header = {"Content-Type":"application/json"}zabbix_user = "zabbix"zabbix_pass = "admin"auth_code = ""#auth user and password#用户认证信息的部分,最终的目的是得到一个SESSIONID#下面是生成一个JSON格式的数据:用户名和密码def auto_login(): auth_data = json.dumps( { "jsonrpc" : "2.0", "method" : "user.login", "params" : { "user":zabbix_user, "password":zabbix_pass }, "id":0 })# create request object request = urllib2.Request(zabbix_url,auth_data) for key in zabbix_header: request.add_header(key,zabbix_header[key])#认证和获取SESSION ID try: result = urllib2.urlopen(request)#对于认证出错的处理 except HTTPError,e: print ‘The server couldn\‘t fulfill the request, Error code: ‘,e.code except URLError,e: print ‘We failed to reach a server.Reason: ‘,e.reason else: response = json.loads(result.read()) return responseres=auto_login()#判断SESSIONID是否在返回的数据中def check_sessionid(): if ‘result‘ in res: # if ‘result‘ in auto_info: auth_code = res[‘result‘] else: print res[‘error‘][‘data‘] json_data ={ "method":"host.get", "params":{ "output":"extend", } } json_base={ "jsonrpc":"2.0", "auth":auth_code, "id":1 } json_data.update(json_base)#用得到的SESSIONID去验证,获取主机的信息(用http.get方法) if len(auth_code) == 0: sys.exit(1) host=[] if len(auth_code) != 0: get_host_data = json.dumps(json_data) #create request object request = urllib2.Request(zabbix_url,get_host_data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) #get host list 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 fulfill the request.‘ print ‘Error code: ‘,e.code else: response = json.loads(result.read()) result.close() #将所有的主机信息显示出来 # print response for i in response[‘result‘]: #print i if unicode(str(i[‘host‘][-1])).isdecimal() == True: H= i[‘host‘] host.append(H) return hostif __name__ == "__main__": return_host=check_sessionid() print return_host print len(return_host)
zabbix的api统计zabbix监控的主机数量与主机名
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。