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不会使。

时间: 2024-11-05 19:36:03

Zabbix API学习_工具篇的相关文章

Zabbix API学习_认证篇

zabbix很多都是可以直接通过 zabbix api 来进行辅助操作. 官方文档地址:https://www.zabbix.com/documentation 通过API操作,都必须组认证,拿到了认证token之后,才能进行相应操作: #-*- coding:utf-8 -*- ''' Created on 2016-6-8 @author: ''' import json import urllib2 from urllib2 import URLError class Zabbix_Aut

Caffe学习系列——工具篇:神经网络模型结构可视化

Caffe学习系列--工具篇:神经网络模型结构可视化 在Caffe中,目前有两种可视化prototxt格式网络结构的方法: 使用Netscope在线可视化 使用Caffe提供的draw_net.py 本文将就这两种方法加以介绍 1. Netscope:支持Caffe的神经网络结构在线可视化工具 Netscope是个支持prototxt格式描述的神经网络结构的在线可视工具,网址:  http://ethereon.github.io/netscope/quickstart.html  它可以用来可

【机器学习算法应用和学习_2_理论篇】2.2 M_分类_逻辑回归

一.原理阐述 算法类型:监督学习_分类算法 输入:数值型或标称型(标称型需要独热编码) V1.0 用回归方式解决二分类问题,通过引入一个Sigmoid函数将中间y值映射到实际二分类的y值上. 二.算法选择 三.算法过程 1.Sigmoid函数是一个x值域是(-∞,+∞),y值域是(0,1)的单调递增函数: 2.预测y值>0.5为1类,<0.5为0类,y值也可以解释为为1和0类的概率: 3.同样使用“最小二乘”概念,求得最佳方程,得到目标函数: 4.要使得目标函数达到最小,需要采用一种称为“梯度

学习笔记-性能测试-工具篇-LR-初识

关于LR的基本信息网上都能搜到,这里就不再赘述. loadrunner的安装准备 windows环境: 前提条件: 内存:2G,硬盘空闲空间10G,安装完成后实际只占不到2G 支持winXP  SP3;32位与64位win7浏览器支持IE6-8,IE9,firefox3 若以前安装过LoadRunner,则将其卸载. 下载好需要的部件然后通过安装程序进行安装 关于破解细节,详情请百度或者谷歌. 这里找到一篇关于LR11的安装篇: http://www.cnblogs.com/yangxia-te

学习笔记-性能测试-工具篇-LR-12的安装

进入LR的官方网站下载好最新的两个版本 两个安装文件: 先解压到同一文件夹 点击安装程序,选择安装的路径会自动安装: 安装完成后出现三个主要组件: 学习笔记-性能测试-工具篇-LR-12的安装,布布扣,bubuko.com

STL学习_配接器篇

STL学习_配接器篇 定义 配接器(Adapter)在STL组件的灵活组合运用功能上,扮演着轴承.转换器的角色.它事实上是一种设计模式.即将一个class的接口转换为另一个class的接口,使原本因接口不兼容而不能合作的classes,可以一起运作. 分类 STL所提供的各种适配器中,改变仿函数(functors)接口者,称为function adapter:改变容器(containers)接口者,称为container adapter:改变迭代器(iterators)接口者,称为iterato

野兽的Angular Api 学习、翻译及理解 - - ngIf、ngSwitch、ngHide/ngShow

野兽的 ng api 学习 - - ngIf.ngSwitch.ngHide/ngShow 在组合这些ng指令写到一篇文章里的时候,基本是有规则的,野兽把功能相似相近的一类大多会组合到一起,方便理解和记忆. 这篇的三个指令也都是对DOM元素的操作,页面上显示/隐藏的判断,添加/移除的判断. ngIf ngIf指令会根据指定的表达式返回的boolean类型值对该元素做添加到/移除出Dom树的操作. 格式:ng-if=“value” value:表达式  返回结果为boolean类型. 使用代码:

用zabbix生成awstats图表以及通过Python调zabbix API自动化操作

awstats作为一款日志分析软件,功能不错,但是界面过于简单,也没有图表功能,这里我采取了一种变通的方法,将awstats的分析结果(pv.hits(文件数).bandwidth.visits(独立ip))添加到zabbix,并通过zabbix生成趋势图表. 在前两篇文章中,我们队awstats的使用及其工作方式进行了简明扼要的介绍:awstats对每个站点进行分析之后,会生成一个"awstats012016.txt"格式的"数据库"文件:awstats的展示页面

无线安全专题_攻击篇--MAC泛洪攻击

上一篇讲解了无线安全专题_攻击篇--干扰通信,没在首页待多长时间就被拿下了,看来之后不能只是讲解攻击实战,还要进行技术原理和防御方法的讲解.本篇讲解的是局域网内的MAC泛洪攻击,这种攻击方式主要目的是窃取局域网中的通信数据,例如ftp的账号和密码,下面的实战也是以此为例子.接下来按照原理,场景,攻击实战,防御方法的层次步骤进行讲解. 一.MAC泛洪攻击的原理 MAC泛洪攻击主要是利用局域网交换机的mac学习和老化机制. 1.1交换机的工作流程如下: 局域网中的pc1发送数据帧给pc2,经过交换机