1. 程式人生 > >一個python基於hostname關聯zabbix模版的自動化腳本

一個python基於hostname關聯zabbix模版的自動化腳本

一個python基於hostname關聯

最近在考慮做一套基於zabbix日常操作的python腳本:

所以最近需求zabbix監控基於主機hostname關聯模版,後來看了zabbixapi官網 (https://www.zabbix.com/documentation/2.0/manual/appendix/api/template/massadd) 覺得不難實現,就試著去實現了!

不多說了直接上腳本:

(env1) ?  ~ cat zabbix_add_template.py
#!/usr/bin/python
#-*- coding:utf-8 -*-
#__author__ == 'chenmingle'
import json
import sys
import urllib2
import argparse
from urllib2 import URLError
reload(sys)
sys.setdefaultencoding('utf-8')
class zabbix_api:
    def __init__(self):
        self.url = 'http://139.198.126.44:8088/zabbix/api_jsonrpc.php'
        self.header = {"Content-Type":"application/json"}
    def user_login(self):
        data = json.dumps({
                           "jsonrpc": "2.0",
                           "method": "user.login",
                           "params": {
                                      "user": "Admin",
                                      "password": "JZZabbix123!@#"
                                      },
                           "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 "\033[041m 認證失敗,請檢查URL !\033[0m",e.code
        except KeyError as e:
            print "\033[041m 認證失敗,請檢查用戶名密碼 !\033[0m",e
        else:
            response = json.loads(result.read())
            result.close()
            #print response['result']
            self.authID = response['result']
            return self.authID
    def hostid_get_hostip(self, hostId=''):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "hostinterface.get",
            "params": {
                "output": "extend",
                "filter": {"hostid": hostId}
            },
            "auth": self.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())
            # print response
            result.close()
            if not len(response['result']):
                print "\033[041m hostid \033[0m is not exist"
                return False
            #print "主機數量: \33[31m%s\33[0m" % (len(response['result']))
            for hostip in response['result']:
                #print hostip
                #if len(hostip) == 0:
                #    print "HostID : %s\t HostIp : %s \t Port : %s " % (hostip['hostid'], hostip['ip'], hostip['port'])
                #else:
                #    print "HostID : %s\t HostIp :\33[32m%s\33[0m \t Port :\33[31m%s\33[0m" % (
                #        hostip['hostid'], hostip['ip'], hostip['port'])
return hostip['ip']
    def host_get(self,hostName=''):
        data=json.dumps({
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                          "output": "extend",
                          #"filter":{"host":""}
                          "filter":{"host":hostName}
                          },
                "auth": self.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())
            #print reqponse
            result.close()
            if not len(response['result']):
                print "\033[041m %s \033[0m is not exist" % hostName
                return False
            print "主機數量: \033[31m%s\033[0m"%(len(response['result']))
            for host in response['result']:
                status={"0":"OK","1":"Disabled"}
                available={"0":"Unknown","1":"available","2":"Unavailable"}
                #print host
                if len(hostName)==0:
                    print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :%s \t Available :%s"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])
                else:
                    print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])
                    return host['hostid']
    def template_get(self,templateName=''):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method": "template.get",
                           "params": {
                                      "output": "extend",
                                      "filter": {
                                                 "name":templateName
                                                 }
                                      },
                           "auth":self.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 response
            if not len(response['result']):
                print "\033[041m %s \033[0m is not exist" % templateName
                return False
            for template in response['result']:
                if len(templateName)==0:
                    print "template : %s \t id : %s" % (template['name'], template['templateid'])
                else:
                    self.templateID = response['result'][0]['templateid']
                    print "Template Name :%s"%templateName
                    return response['result'][0]['templateid']
    def template_massadd(self, templateName, hostName):
        template_list = self.template_get(templateName)
        host_id = self.host_get(hostName)
        print host_id
        data = json.dumps({
                    "jsonrpc": "2.0",
                    "method": "template.massadd",
                    "params": {
                        "templates": [
                            {
                                "templateid": template_list,
                            }
                        ],
                        "hosts": [
                            {
                                "hostid": host_id
                            }
                        ]
                        },
                           "auth": self.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)
            response = json.loads(result.read())
            result.close()
            print "add %s to hosts: %s" % (templateName, hostName)
        except URLError as e:
            print "Error as ", e
        except KeyError as e:
            print "\033[041m 主機添加有誤,請檢查模板正確性或主機是否添加重復 !\033[0m",e
            print response
if __name__ == "__main__":
    zabbix=zabbix_api()
    parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
    parser.add_argument('-t','--template_messadd',dest='template_massadd',nargs=2,metavar=('Template01,Template02', 'hostName'),help='添>加主機,多個主機組或模板使用逗號')
    args = parser.parse_args()
    zabbix.template_massadd(args.template_massadd[0], args.template_massadd[1])


上面的腳本應該很容易看得明白的,不明白的可以隨時咨詢!

使用方法:

(env1) ?  ~ python zabbix_add_template.py -h
usage: zabbix_add_template.py [options]
zabbix api
optional arguments:
  -h, --help            show this help message and exit
  -t Template01,Template02 hostName, --template_messadd Template01,Template02 hostName
                        添>加主機,多個主機組或模板使用逗號


下面驗證下看看:

(env1) ?  ~ python zabbix_add_template.py -t 'Percona MySQL Server Template' testServer_WEB
Template Name :Percona MySQL Server Template
主機數量: 1
HostID : 10481 HostName : testServer_WEB HostIp : (IP地址加密,不能給你們看) Status :OK  Available :available
10481
add Percona MySQL Server Template to hosts: testServer_YK_WEB


技術分享圖片

一個python基於hostname關聯zabbix模版的自動化腳本