Zabbix API学习_工具篇

 

接上面得到认证之后,可以直接进行操作了。想要做什么事,就看你个人想做什么了。

 

#-*- coding:utf-8 -*-
'''
Created on 2016-6-8

@author: 
'''
import sys
import json
import urllib2
from urllib2 import URLError
from zabbix_auth import Zabbix_Auth

class Zabbix_Utils:

    def __init__(self):
        self.url = 'http://zabbix.light.fang.com/api_jsonrpc.php'
        self.header = {"Content-Type":"application/json"}
        
    # 获取数据,统一提出来做成一个方法使用
    def get_data(self, data):
        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 'Reason: ', e.reason 
            elif hasattr(e, 'code'): 
                print 'Error code: ', e.code 
        else: 
            response = json.loads(result.read()) 
            result.close()
            return response
                

    def host_get(self,hostip=''): 
        data=json.dumps({
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                          "output": "extend",
                          "filter":{"ip":hostip} 
                          },
                "auth": Zabbix_Auth().user_login(),
                "id": 1
                })
        response = self.get_data(data)
        hostlist = []
        for host in response['result']:      
            hostlist.append(host['name'])
        #print len(hostlist)
        return hostlist

    def hostgroup_get(self, hostgroupName=''): 
        data = json.dumps({ 
                   "jsonrpc":"2.0", 
                   "method":"hostgroup.get", 
                   "params":{ 
                             "output": "extend", 
                             "filter": { 
                                        "name": hostgroupName 
                                        } 
                             }, 
                   "auth":Zabbix_Auth().user_login(), 
                   "id":1, 
                   }) 
         
        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 "Error as ", e 
        else: 
            response = json.loads(result.read()) 
            result.close() 


    def template_get(self,templateName=''): 
        data = json.dumps({ 
                           "jsonrpc":"2.0", 
                           "method": "template.get", 
                           "params": { 
                                      "output": "extend", 
                                      "filter": { 
                                                 "name": templateName                                                        
                                                 } 
                                      }, 
                           "auth": Zabbix_Auth().user_login(), 
                           "id":1, 
                           })
         
        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 "Error as ", e 
        else: 
            response = json.loads(result.read()) 
            result.close() 

    def hostgroup_create(self,hostgroupName):

        if self.hostgroup_get(hostgroupName):
            print "hostgroup  \033[42m%s\033[0m is exist !"%hostgroupName
            sys.exit(1)
        data = json.dumps({
                          "jsonrpc": "2.0",
                          "method": "hostgroup.create",
                          "params": {
                          "name": hostgroupName
                          },
                          "auth": Zabbix_Auth().user_login(),
                          "id": 1
                          })
        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 "Error as ", e 
        else: 
            response = json.loads(result.read()) 
            result.close()
            print "\033[042m 添加主机组:%s\033[0m  hostgroupID : %s"%(hostgroupName,response['result']['groupids'])


                 
    def host_create(self, hostname, hostip, name, proxyid, hostgroupName, templateName):
        if self.host_get(hostip):
            print "\033[041m该主机已经添加!\033[0m" 
            sys.exit(1)
        group_list=[]
        template_list=[]
        for i in hostgroupName.split(','):
            var = {}
            var['groupid'] = self.hostgroup_get(i)
            group_list.append(var)
        for i in templateName.split(','):
            var={}
            var['templateid']=self.template_get(i)
            template_list.append(var)    

        data = json.dumps({ 
                   "jsonrpc":"2.0", 
                   "method":"host.create", 
                   "params":{ 
                        "host": name,
                        "name": hostname, 
                        "interfaces": [ 
                         { 
                             "type": 1, 
                             "main": 1, 
                             "useip": 1, 
                             "ip": hostip, 
                             "dns": "", 
                             "port": "10050" 
                          } 
                        ], 
                        "groups": group_list,
                        "templates": template_list,
                        "proxy_hostid": proxyid,
                     }, 
                   "auth": Zabbix_Auth().user_login(), 
                   "id":1                   
        }) 
        response = self.get_data(data)
        print "添加主机 : \033[32m%s\033[0m \tid :\033[31m%s\033[0m \tproxy :\033[31m%s\033[0m" % (hostip, response, proxyid) 

    def host_disable(self,hostip):
        data=json.dumps({
                        "jsonrpc": "2.0",
                        "method": "host.update",
                        "params": {
                        "hostid": self.host_get(hostip),
                        "status": 1
                        },
                        "auth": Zabbix_Auth().user_login(),
                        "id": 1
        })
        response = self.get_data(data)
        print self.host_get(hostip)
                 

    def host_delete(self,hostid):
        hostid_list=[]
        for i in hostid.split(','):
            var = {}
            var['hostid'] = self.host_get(i)
            hostid_list.append(var)         
        data=json.dumps({
                        "jsonrpc": "2.0",
                        "method": "host.delete",
                        "params": hostid_list,
                        "auth": Zabbix_Auth().user_login(),
                        "id": 1
                })

        response = self.get_data(data)

    def get_host(self, hostip=""):
        data = json.dumps({
            "jsonrpc":"2.0",
            "method":"host.get",
            "params":{
                "output":"extend",
                "filter":{
                    "host":hostip
                    }
                },
            "auth": Zabbix_Auth().user_login(),
            "id":2
            });
        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 fulfill the request.' 
                print 'Error code: ', e.code
                return 0
        else:
            response = json.loads(result.read()) 
            result.close() 
            hostsid = []
            for host in response['result']:
                hostsid.append({host['host']:host['hostid']})
            return hostsid

    def get_hostgroup(self, hostgroupname=""):
        data = json.dumps({
                   "jsonrpc":"2.0",
                   "method":"hostgroup.get",
                   "params":{
                             "output": "extend",
                             "filter": {
                                        "name": hostgroupname
                                        }
                             },
                   "auth":Zabbix_Auth().user_login(),
                   "id":1,
                   })
        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 "Error as ", e
        else:
            response = json.loads(result.read())
            result.close()
            grouphosts = []
            for group in response['result']:
                grouphosts.append({group['name']:group['groupid']})
            return grouphosts
        
    def get_host_graph(self, hostid):
        graph_json_body = {
                        "jsonrpc": "2.0",
                        "method": "graph.get",
                        "params": {
                            "output": "extend",
                            #"selectGraphs": ["name","graphid"],
                            "hostids": hostid,
                            #"filter": {"hostids": hostid},
                            "sortfield": "name"
                        },
                        "auth": Zabbix_Auth().user_login(),
                        "id": 1
                    }
        
#         graph_json_body =   {
#               "jsonrpc": "2.0",
#               "method": "host.get",
#               "params": { 
#                       "selectGraphs": ["name","graphid"],
#                       "filter": {"host": hostname}},
#               "auth": Zabbix_Auth().user_login(),
#               "id": 1
#           }
        
        data = json.dumps(graph_json_body)
        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 fulfill the request.' 
                print 'Error code: ', e.code
                return 0
        else:
            response = json.loads(result.read()) 
            result.close()
            return response['result']
            #return response['result'][0]['graphs']

    #def get_host_item(self, hostname=""):
    #def get_host_item(self, hostid="", graphid=""):
    # 获取每个graph的item数
    def get_host_graph_item(self, graphid=""):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "item.get",
            "params": {
                "output": "extend",
                #"selectGraphs": ["name"],
                #"hostids": hostid,
                "graphids": graphid,
                #"host": hostname,
                #"search": {
                #    "key_": "system"
                #},
                "sortfield": "name"
            },
            "auth": Zabbix_Auth().user_login(),
            "id": 1
        })
        request = urllib2.Request(self.url,data)
        for key in self.header:
            request.add_header(key,self.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 "Number Of host items: ", len(response['result'])
            item_array = []
            for item in response['result']:
                #print item.get('itemid'),item.get('graphs'),item.get('name')
                item_array.append(item)
                #print '\t', item
                #item_host.append({item["name"]:item["itemid"]})
                #print "Host ID:",host['hostid'],"HostName:",host['name']
            return item_array
    
    def get_host_from_groupid(self, groupid=""):
        data = json.dumps({
           "jsonrpc":"2.0",
           "method":"host.get",
           "params":{
               "output":["hostid","name"],
               "groupids":groupid,
           },
            "auth": Zabbix_Auth().user_login(),
           "id":1,
        })
        request = urllib2.Request(self.url,data)
        for key in self.header:
            request.add_header(key,self.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 "Number Of Hosts: ", len(response['result'])
            group_host = []
            for host in response['result']:
                group_host.append({host["name"]:host["hostid"]})
                #print "Host ID:",host['hostid'],"HostName:",host['name']
            return group_host
       
    # 得到某个item所对应的历史数据,limit可以修改成其他的,但是为1表示只取最新的一条数据
    def get_items_history(self, itemsid=""):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "history.get",
            "params": {
                "output": "extend",
                "history": 0,
                "itemids": itemsid,
                "sortfield": "clock",
                "sortorder": "DESC",
                "limit": 1
            },
            "auth": Zabbix_Auth().user_login(),
            "id": 1
        });
        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 fulfill the request.'
                print 'Error code: ', e.code
        else:
            response = json.loads(result.read())
            result.close()
            print "Number Of items: ", len(response['result'])
            items_value = []
            for value in response['result']:
                items_value.append({u'itemid':value["itemid"], u'value':value["value"]})
            return items_value
       
    
    def get_graph_value(self, graphid):
        data = json.dumps({
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": { 
                       "selectItems": ["itemid"],
                        "filter": {"graph": graphid}
                },
                "auth": Zabbix_Auth().user_login(),
                "id": 1
                }
        )
        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 fulfill the request.' 
                print 'Error code: ', e.code
                return 0
        else:
            response = json.loads(result.read()) 
            result.close() 
            tmp = response['result'][0]['items']
            items = []
            for value in tmp:
                print value
            return "test"
        
    def get_alert_value(self,actionids=''): 
        data=json.dumps({
                        "jsonrpc": "2.0",
                        "method": "alert.get",
                        "params": {
                            "output": "extend",
                            "actionids": "7"
                        },
                        "auth": Zabbix_Auth().user_login(),
                        "id": 1
                        })
        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 'Reason: ', e.reason 
            elif hasattr(e, 'code'): 
                print 'Error code: ', e.code 
        else: 
            response = json.loads(result.read()) 
            result.close()
            for index in response['result']:
                print index
        
zabbix_tool = Zabbix_Utils()

##获取所有zabbix中分组
for group in zabbix_tool.get_hostgroup():
    for group_key in group:
        print group_key
        group_id = group[group_key]
        # 获取每个zabbix分组下的所有主机
        for host in zabbix_tool.get_host_from_groupid(group_id):
            #print "\t", host
            for host_key in host:
                print "\t", host_key
                host_id = host[host_key]
                # 获取每个zabbix每个主机的所有graph
                for graph in zabbix_tool.get_host_graph( host_id):
                    #for graph_key in graph:
                    print '\t\t', graph['graphid'], graph['name']
                    #获取每个graph的item数
                    for item in zabbix_tool.get_host_graph_item(graph['graphid']):
                        print '\t\t\t', item.get('itemid'), item.get('name'), item.get('prevvalue'), item.get('lastclock'), item.get('lastvalue'), item.get('units'), item.get('key_'), item.get('name'), item
                    


  

 

上面这些基本可以满足取出数据,然后自己通过RRDTool画图的需求,可惜我RRDTool不会使。

 

posted @ 2016-07-13 16:41  schangech  阅读(855)  评论(0编辑  收藏  举报