zabbix 二次開發之同步CMDB主機和模板繫結

2021-09-03 10:34:31 字數 3520 閱讀 4006

最近在做zabbix的二次開發;發現zabbix在做自動化方便提供了強悍的支援,下面分享下cmdb和zabbix打通,把cmdb平台裡面的所有機器同步到zabbix資料庫,然後進行批量的模板繫結:

開發環境:

zabbix :2.4

python:flask框架.前端bootstrap,jquey:

實現思路:

一、在cmdb表和zabbix主機表裡面建立第三張管理的表(定義叫快取表);利用zabbix api把資料庫裡面的host插入到第三張快取表;然後通過和cmdb庫裡面的比較把沒有在快取表裡的資料插入到快取表,再同步到zabbix 資料庫。

二、繫結模板使用host.update 這個api,但是這個api在繫結後面的模板之後會刪除已經繫結的模板,所以這裡我們先遍歷出前面所有的模板,然後把前面和後面的一起繫結。

快取表的models結構:

class zbhost(db.model):

__tablename__    = 'zbhost'

id            = db.column(db.integer, primary_key=true)

cmdb_hostid      = db.column(db.integer, index=true, unique = true)

hostid         = db.column(db.integer, index=true, unique = true)

host          = db.column(db.string(50))

ip           = db.column(db.string(32))

獲取資料:

def init_cmdb():

#取host (在server表裡)

hosts = api_action("server.get")

for h in hosts:

data = 

db.session.query(zbhost).filter_by(ip=h['inner_ip']).update(data)

db.session.commit()

#更新到cache表, ip

def init_zabbix():

#第一步 取出所有host,要ip,host,id

zb_hosts =  zabbix_server.get_hosts()

zb_hosts_inte***ce = zabbix_server.get_inte***ce([z['hostid'] for z in zb_hosts])

#    data = 

for h in zb_hosts:

h['ip'] = zb_hosts_inte***ce[h['hostid']]

###資料插入資料庫

db.session.add(zbhost(**h))

db.session.commit()

同步主機到zabbix:

@main.route("/resource/monitor/ajax/sync_host_to_zabbix", methods=['post'])

def sync_host_to_zabbix():

#接收引數

zabbix 介面:

到這裡同步主機完成;下面的批量繫結模板:

def link_template(self, hostid, templateids):

templates = 

for id in templateids:

print templates

print hostid

try:

ret = self.zb.host.update(hostid=hostid, templates=templates)

return ret

except exception as e:

return e.message

檢視:@main.route("/monitor/ajax/link_zabbix_template", methods=['post'])

def link_zabbix_template():

if request.method == "post":

#1、獲取前端資料

params = dict(request.form)

#hostids = params['hostids'][0].split(',')

template_ids = params['template_ids'][0].split(',')

ret_data = link_template(hostids, template_ids)

error = none

for r in ret_data:

try:

hostids.remove(r['hostids'][0])

except exception, e:

error = e.message

if not hostids:

return "1"

else:

return error

return "500"

主機繫結模板:

繫結之後:

登入zabbix檢視:

到此zabbix基本的同步主機,繫結模板已經完成;zabbix提供了非常優秀的api,我們可以用來實現很多我們需要的功能;上面的步驟已經基本上完成了我們日常說需要的功能;當然還有解綁模板刪除主機,新增維護週期等等;

Zabbix二次開發 01基礎

最近有個想法 想做乙個zabbix資料的二次呈現,所以來寫一下zabbix的api的內容。先說下zabbix api的認證基礎。zabbix api開始扮演著越來越重要的角色,尤其是在整合第三方軟體和自動化日常任務時。zabbix api為批量操作 第三方軟體整合以及其他作用提供可程式設計介面。za...

Zabbix二次開發 01基礎

最近有個想法 想做乙個zabbix資料的二次呈現,所以來寫一下zabbix的api的內容。先說下zabbix api的認證基礎。zabbix api開始扮演著越來越重要的角色,尤其是在整合第三方軟體和自動化日常任務時。zabbix api為批量操作 第三方軟體整合以及其他作用提供可程式設計介面。za...

Zabbix二次開發時常用到zabbix資料庫字段

1 zabbix web頁面中 配置 動作 事件源 觸發器 中的狀態,這個是用來報警發郵件或簡訊的,在資料庫中表中可以直接修改,sql語句為 update zabbix.actions set status 1 where name email 欄位status值為1時是關閉,0時為啟用,name為...