鍍金池/ 教程/ Python/ python 調(diào)用 zabbix 的 api 接口添加主機(jī)、查詢(xún)組、主機(jī)、模板
通過(guò) memcached 實(shí)現(xiàn)領(lǐng)號(hào)排隊(duì)功能及 python 隊(duì)列實(shí)例
利用 pypy 提高 python 腳本的執(zhí)行速度及測(cè)試性能
Python FAQ3-python 中 的原始(raw)字符串
Mongodb 千萬(wàn)級(jí)數(shù)據(jù)在 python 下的綜合壓力測(cè)試及應(yīng)用探討
Parallel Python 實(shí)現(xiàn)程序的并行多 cpu 多核利用【pp 模塊】
python simplejson 模塊淺談
服務(wù)端 socket 開(kāi)發(fā)之多線(xiàn)程和 gevent 框架并發(fā)測(cè)試[python 語(yǔ)言]
python Howto 之 logging 模塊
python 之 MySQLdb 庫(kù)的使用
關(guān)于 python 調(diào)用 zabbix api 接口的自動(dòng)化實(shí)例 [結(jié)合 saltstack]
python 之利用 PIL 庫(kù)實(shí)現(xiàn)頁(yè)面的圖片驗(yàn)證碼及縮略圖
Python 通過(guò) amqp 消息隊(duì)列協(xié)議中的 Qpid 實(shí)現(xiàn)數(shù)據(jù)通信
python 中用 string.maketrans 和 translate 巧妙替換字符串
python linecache 模塊讀取文件用法詳解
Python 批量更新 nginx 配置文件
python 計(jì)算文件的行數(shù)和讀取某一行內(nèi)容的實(shí)現(xiàn)方法
python+Django 實(shí)現(xiàn) Nagios 自動(dòng)化添加監(jiān)控項(xiàng)目
多套方案來(lái)提高 python web 框架的并發(fā)處理能力
python 寫(xiě)報(bào)警程序中的聲音實(shí)現(xiàn) winsound
python 調(diào)用 zabbix 的 api 接口添加主機(jī)、查詢(xún)組、主機(jī)、模板
對(duì) Python-memcache 分布式散列和調(diào)用的實(shí)現(xiàn)
使用 python 構(gòu)建基于 hadoop 的 mapreduce 日志分析平臺(tái)
一個(gè)腳本講述 python 語(yǔ)言的基礎(chǔ)規(guī)范,適合初學(xué)者
Python 編寫(xiě)的 socket 服務(wù)器和客戶(hù)端
如何將 Mac OS X10.9 下的 Python2.7 升級(jí)到最新的 Python3.3
python 監(jiān)控文件或目錄變化
報(bào)警監(jiān)控平臺(tái)擴(kuò)展功能 url 回調(diào)的設(shè)計(jì)及應(yīng)用 [python 語(yǔ)言]
Python 處理 cassandra 升級(jí)后的回滾腳本
python 實(shí)現(xiàn) select 和 epoll 模型 socket 網(wǎng)絡(luò)編程
關(guān)于 B+tree (附 python 模擬代碼)
通過(guò) python 和 websocket 構(gòu)建實(shí)時(shí)通信系統(tǒng)[擴(kuò)展 saltstack 監(jiān)控]

python 調(diào)用 zabbix 的 api 接口添加主機(jī)、查詢(xún)組、主機(jī)、模板

zabbix 有一個(gè) API 接口,可以調(diào)用這些幾口來(lái)自動(dòng)添加主機(jī),查詢(xún) zabbix 中監(jiān)控的主機(jī),監(jiān)控的模板、監(jiān)控的主機(jī)組等信息,使用也非常的方便。以下是用 python 調(diào)用 zabbix 的 API 接口來(lái)實(shí)現(xiàn)上述功能:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib2
import sys
class zabbixtools:
    def __init__(self):
        self.url = "http://192.168.100.200/zabbix/api_jsonrpc.php"
        self.header = {"Content-Type": "application/json"}
        self.authID = self.user_login()
    def user_login(self):
        data = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "user.login",
                    "params": {
                        "user": "Admin",
                        "password": "zabbix"
                        },
                    "id": 0
                    })
        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 "Auth Failed, Please Check Your Name And Password:",e.code
        else:
            response = json.loads(result.read())
            result.close()
            authID = response['result']
            return authID
    def get_data(self,data,hostip=""):
        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
    def host_get(self,hostip):
        #hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
        data = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "host.get",
                    "params": {
                        "output":["hostid","name","status","host"],
                        "filter": {"host": [hostip]}
                        },
                    "auth": self.authID,
                    "id": 1
                })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            #for host in res:
            host = res[0]
            if host['status'] == '1':
                print "\t","\033[1;31;40m%s\033[0m" % "Host_IP:","\033[1;31;40m%s\033[0m" % host['host'].ljust(15),'\t',"\033[1;31;40m%s\033[0m" % "Host_Name:","\033[1;31;40m%s\033[0m" % host['name'].encode('GBK'),'\t',"\033[1;31;40m%s\033[0m" % u'未在監(jiān)控狀態(tài)'.encode('GBK')
                return host['hostid']
            elif host['status'] == '0':
                print "\t","\033[1;32;40m%s\033[0m" % "Host_IP:","\033[1;32;40m%s\033[0m" % host['host'].ljust(15),'\t',"\033[1;32;40m%s\033[0m" % "Host_Name:","\033[1;32;40m%s\033[0m" % host['name'].encode('GBK'),'\t',"\033[1;32;40m%s\033[0m" % u'在監(jiān)控狀態(tài)'.encode('GBK')
                return host['hostid']
            print
        else:
            print '\t',"\033[1;31;40m%s\033[0m" % "Get Host Error or cannot find this host,please check !"
            return 0
    def host_del(self):
        hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
        hostid = self.host_get(hostip)
        if hostid == 0:
            print '\t',"\033[1;31;40m%s\033[0m" % "This host cannot find in zabbix,please check it !"
            sys.exit()
        data = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "host.delete",
                    "params": [{"hostid": hostid}],
                    "auth": self.authID,
                    "id": 1
                })
        res = self.get_data(data)['result']
        if 'hostids' in res.keys():
            print "\t","\033[1;32;40m%s\033[0m" % "Delet Host:%s success !" % hostip
        else:
            print "\t","\033[1;31;40m%s\033[0m" % "Delet Host:%s failure !" % hostip
    def hostgroup_get(self):
        data = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "hostgroup.get",
                    "params": {
                        "output": "extend",
                        },
                    "auth": self.authID,
                    "id": 1,
                    })
        res = self.get_data(data)
        if 'result' in res.keys():
            res = res['result']
            if (res !=0) or (len(res) != 0):
                print "\033[1;32;40m%s\033[0m" % "Number Of Group: ", "\033[1;31;40m%d\033[0m" % len(res)
                for host in res:
                    print "\t","HostGroup_id:",host['groupid'],"\t","HostGroup_Name:",host['name'].encode('GBK')
                print
        else:
            print "Get HostGroup Error,please check !"
    def template_get(self):
        data = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "template.get",
                    "params": {
                        "output": "extend",
                        },
                    "auth": self.authID,
                    "id": 1,
                    })
        res = self.get_data(data)#['result']
        if 'result' in res.keys():
            res = res['result']
            if (res !=0) or (len(res) != 0):
                print "\033[1;32;40m%s\033[0m" % "Number Of Template: ", "\033[1;31;40m%d\033[0m" % len(res)
                for host in res:
                    print "\t","Template_id:",host['templateid'],"\t","Template_Name:",host['name'].encode('GBK')
                print
        else:
            print "Get Template Error,please check !"
    def host_create(self):
        hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Host_ip :')
        groupid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Group_id :')
        templateid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Tempate_id :')
        g_list=[]
        t_list=[]
        for i in groupid.split(','):
            var = {}
            var['groupid'] = i
            g_list.append(var)
        for i in templateid.split(','):
            var = {}
            var['templateid'] = i
            t_list.append(var)
        if hostip and groupid and templateid:
            data = json.dumps(
                    {
                        "jsonrpc": "2.0",
                        "method": "host.create",
                        "params": {
                            "host": hostip,
                            "interfaces": [
                                {
                                    "type": 1,
                                    "main": 1,
                                    "useip": 1,
                                    "ip": hostip,
                                    "dns": "",
                                    "port": "10050"
                                }
                            ],
                            "groups": g_list,
                            "templates": t_list,
                    },
                        "auth": self.authID,
                        "id": 1,
                        })
            res = self.get_data(data,hostip)
            if 'result' in res.keys():
                res = res['result']
                if 'hostids' in res.keys():
                    print "\033[1;32;40m%s\033[0m" % "Create host success"
            else:
                print "\033[1;31;40m%s\033[0m" % "Create host failure: %s" % res['error']['data']
        else:
            print "\033[1;31;40m%s\033[0m" % "Enter Error: ip or groupid or tempateid is NULL,please check it !"
def main():
    test = zabbixtools()
    #test.template_get()
    #test.hostgroup_get()
    #test.host_get()
    test.host_del()
    #test.host_create()
if __name__ == "__main__":
    main()

相關(guān)的材料的可以參考官方文檔。這個(gè)只是一些功能模塊,包含獲取主機(jī),主機(jī)組、模板、刪除主機(jī)等功能,可以根據(jù)需要進(jìn)行調(diào)整,實(shí)現(xiàn) zabbix 的批量化和自動(dòng)化管理。因?yàn)槭窃?linux 運(yùn)行,所以設(shè)置了輸出終端的字體顏色方便區(qū)分,如果不需要,自行刪除即可。