最近在考虑做一套基于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


image.png