zabbix的api统计zabbix监控的主机数量与主机名

时间:2016-09-30 20:50:48   收藏:0   阅读:3440

python通过zabbix的api获取监控的主机名和主机数量

#!/usr/bin/env python
# -*- encoding: utf8 -*-

#导入模块,urllib2是一个模拟浏览器HTTP方法的模块
import json
import urllib2
import sys
import smtplib
from 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 response
res=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 host

if __name__ == "__main__":
    return_host=check_sessionid()
    print return_host
    print len(return_host)

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!