zabbix批量更新主机关联的模板

背景

zabbix的前台页面其实已经功能非常强大了,但特别情况下还是无法满足我们的需求的。

例如同事跑来找我说,想批量对一批主机管理一个新的模板,但这些主机不在同一个主机组,

即没办法利用前台页面的批量更新的。所有我看了下,就只能借助了zabbix api去处理了。

思路

思路其实很简单了:

  • 读取目标文件,遍历所有的主机

  • 查询出当前主机已经关联的模板

  • 对主机进行更新,在原有关联模板的基础上追加新的模块

涉及API

  • host.get

  • template.get

  • host.update

大致就如上三个api就足够完成我们的要求了。

具体实现方法

最近翻书发现一个很不错的python库,pyzabbix,实现的非常巧妙,于是我放弃了自己造轮子的打算。

回头有空和大家一起分享下,这里就不罗嗦了。

工具有了,思路有了,那怕具体实现么?

实现1:

#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
# Last modified: 2014-09-25 20:07
# Author: kevin
# Mail: huangsicong@letv.com
# propose:  批量刷新host关联的模版
import MySQLdb
import sys
import os
import copy
import time
import logging
import logging.config

from pyzabbix import ZabbixAPI
from configure import *

zabbix_server = "http://125.1*2.*1.*3/zabbix/"
zabbix_user = "zabbix_api_*c"
zabbix_passwd = "m*b*yhPl*9zR"

def connect_zabbix_db_init():
    try:
            conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=port)
            cur=conn.cursor()
            conn.select_db('zabbix')
            cur.execute('set names utf8')
            return cur
    except MySQLdb.Error,e:
            logging.error("Mysql Error %d: %s" % (e.args[0], e.args[1]))
            
def connect_zabbix_db_close(cur):
    cur.close()

def get_host_template(cur,hostid):
    sql = 'select ht.templateid from hosts_templates ht, hosts h where  h.hostid = ht.hostid and h.hostid=%s' %(hostid)
    cur.execute(sql)
    template_list = cur.fetchall()
    return template_list

cur = connect_zabbix_db_init()
zapi = ZabbixAPI(zabbix_server)
zapi.login(zabbix_user,zabbix_passwd)

'''获取需要添加的模版的templateid'''
res = zapi.template.get(filter={'host':'syslog addition_EmbedThunderMan'})
#res 返回结果[{u'hostid': u'11661', u'templateid': u'11661'}]
templateid = res[0]['templateid']
templateid = int(templateid)

f = open('host_updata_template.txt')
for host in f:
        host = host.strip()
        '''获取host对应的hostid'''
        res = zapi.host.get(filter={'host':host})
        #res 返回'''[{u'hostid': u'18666'}]'''
        hostid = res[0]['hostid']
        '''获取host原有的模版templateid'''
        res = get_host_template(cur,hostid)
        template_old = [ int(m[0]) for m in res]
        print template_old
        template_old_format= [{'templateid':int(m[0])} for m in res]
        if templateid in template_old:
                continue
        template_new = copy.deepcopy(template_old_format)
        template_new.append({'templateid':templateid})
        res = zapi.host.update(hostid=hostid,templates=template_new)
        print res

connect_zabbix_db_close(cur)

实现1主要是当时大致看了下,没有找到获取主机管理的模板的api,所有就写了条

sql去获取的,主机和模板的对应关系其实就是保存在hosts_templates中,知道这个

其实就没有特别要说的了。

实现2是国庆在家整理文档时,又看了下zabbix 的api,发现其实template.get就

足够满足我们的需求了。所有就在原来的基础上写了一个新的版本,具体看代码吧。

实现2:

#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
# Last modified: 2014-10-05 12:02
# Author: kevin
# Mail: huangsicong@letv.com
# propose:  批量刷新host管理的模版
import os
import copy

from pyzabbix import ZabbixAPI

zabbix_server = "http://125.1*2.*1.*3/zabbix/"
zabbix_user = "zabbix_api_*c"
zabbix_passwd = "m*b*yhPl*9zR"

zapi = ZabbixAPI(zabbix_server)
zapi.login(zabbix_user,zabbix_passwd)

'''获取需要添加的模版的templateid'''
res = zapi.template.get(filter={'host':'syslog addition_EmbedThunderMan'})
#res 返回结果[{u'hostid': u'11661', u'templateid': u'11661'}]
templateid = res[0]['templateid']
templateid = int(templateid)

f = open('host_updata_template.txt')
for host in f:
        host = host.strip()
        '''获取host对应的hostid'''
        res = zapi.host.get(filter={'host':host})
        #res 返回'''[{u'hostid': u'18666'}]'''
        try:
                hostid = res[0]['hostid']
        except:
                continue
        '''获取host原有的模版templateid'''
        res = zapi.template.get(output="hostid",selectParentTemplates="refer",hostids=hostid)
        template_old = [ int(m['templateid']) for m in res]
        template_old_format= [{'templateid':int(m['templateid'])} for m in res]
        print '-'*100
        print template_old_format
        if templateid in template_old:
                continue
        template_new = copy.deepcopy(template_old_format)
        template_new.append({'templateid':templateid})
        res = zapi.host.update(hostid=hostid,templates=template_new)
        print template_new

看看是不是更简洁了,而且维护性更强了。

运行结果:

----------------------------------------------------------------------------------------------------
[{'templateid': 11661}, {'templateid': 12625}, {'templateid': 15369}, {'templateid': 17510}, {'templateid': 18002}, {'templateid': 61604}]
[{'templateid': 11661}, {'templateid': 12625}, {'templateid': 15369}, {'templateid': 17510}, {'templateid': 18002}, {'templateid': 61604}, {'templateid': 61614}]
----------------------------------------------------------------------------------------------------
[{'templateid': 11661}, {'templateid': 12625}, {'templateid': 15369}, {'templateid': 17510}, {'templateid': 18002}, {'templateid': 61604}]
[{'templateid': 11661}, {'templateid': 12625}, {'templateid': 15369}, {'templateid': 17510}, {'templateid': 18002}, {'templateid': 61604}, {'templateid': 61614}]
----------------------------------------------------------------------------------------------------
[{'templateid': 11661}, {'templateid': 12625}, {'templateid': 15369}, {'templateid': 17510}, {'templateid': 18002}, {'templateid': 61604}]
[{'templateid': 11661}, {'templateid': 12625}, {'templateid': 15369}, {'templateid': 17510}, {'templateid': 18002}, {'templateid': 61604}, {'templateid': 61614}]

One Response to “zabbix批量更新主机关联的模板”

Leave a Reply

Your email address will not be published. Required fields are marked *


To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax