####因公司需求,須要根據主機名稱(hostname)模糊匹配查詢出來,進行批量添加聚合圖形(網卡流量監控)php
zabbix api hosts.get
返回全部從數據庫裏面返回出來的hostsidzabbix api graph.get
(圖形模版) 來匹配graphid
返回出來的name
爲模版名稱(這個很重要)graphid
再去請求 zabbix api screen.add
建立聚合圖形 當前目錄下建立三個.py文件python
QuerySet.py ### 查詢數據庫返回host主機 parame.py ### 請求的參數以及 mysql用戶,密碼 zabbixy用戶,密碼 screen_api.py ### 請求內容,返回結果
1: parame.py:mysql
# -*- coding:utf-8 -*- mysql_user = 'root' mysql_host = 'localhost' mysql_pass = 'your MySQL Password' zabbix_user = 'your Zabbix user' zabbix_pass = 'your zabbix Password' host_get = { "jsonrpc": "2.0", "method": "host.get", ###此處爲請求主機返回hostsid 的請求參數,當前爲空,後期會append 進去 "params": { "filter": { "host": [ ] } }, "id": 1 } graph_get = { "jsonrpc": "2.0", "method": "graph.get", ###獲取主機圖形的方法 "params": { "output": "extend", "hostids":[], "sortfield": "name" }, "id": 1 } screen_add = { "jsonrpc": "2.0", "method": "screen.create",###建立圖形方法 "params": { "hsize": 2, "vsize": 60, "screenitems": [ ] }, "id": 1 }
2: QuerySet.py:sql
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql as mysql import sys import re import parame def kwargs(args): ###鏈接數據庫 conn = mysql.connect( host = parame.mysql_host, ###parame文件裏面定義的host port = 3306, user = parame.mysql_user, ###parame文件裏面定義的user passwd = parame.mysql_pass, ###parame文件裏面定義的passwd db = 'zabbix', ) cur = conn.cursor() ###模糊查詢傳遞進來的參數例如 cmb-he-sjz1-123-34-5- response = cur.execute('select host from hosts where host like %s',args) result1 = [ i for i in cur.fetchmany(response)] if len(result1) == 0: return False cur.close() conn.commit() conn.close() result = [] ###此處能夠省略,因公司需求,名稱前面帶VIP的主機名不須要監控 for x in result1: if re.match('VIP',x[0]): pass else: result.append(x) ###排序,這塊能夠無視,將數據庫查詢出來的主機排序從小到大,一條命令就能夠搞定 ###sorted(hosts, key=lambda x: int(x.split("-")[6])) ### 由於每一個公司的主機名定義不一致,這塊你們 若是沒有排序需求 刪掉就能夠,直接return result after = [re.search('(.*?)-(.*?)-(.*?)-(.*?)-(.*?)-(.*?)-(.*?)',x[0]).group() for x in result] before = [int(y[0].split('-')[6]) for y in result] before.sort() response = [] z = 0 for result in after: response.append(result + str(before[z])) z += 1 return response if __name__ == '__main__': try: params = sys.argv[1] print(kwargs(params + '%')) except Exception as e: raise TypeError
2: screen_api.py:數據庫
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys import json import time import requests import parame import sys import re from QuerySet import kwargs class Api: def __init__(self): self.url = 'http://your addres /api_jsonrpc.php' self.headers = {'Content-Type': 'application/json'} auth = { "jsonrpc": "2.0", "method": "user.login", "params": { "user": parame.zabbix_user, ###驗證 "password":parame.zabbix_pass }, "id": 1, "auth":None, } response = requests.post(self.url,data=json.dumps(auth),headers=self.headers) self.authid = json.loads(response.text)['result'] ### auth的id def get_host(self,hosts): #數據庫傳遞進來的主機參數 一大堆~ data = parame.host_get data['auth'] = self.authid ###將返回id 寫進去 接口會驗證這個惟一 if hosts: ### 判斷是否爲空 爲空說明沒有找到主機 直接退出 pass else: print("result not found") sys.exit(10) hosts = sorted(hosts, key=lambda x: int(x.split("-")[6])) ###這塊是排序 QuerySet 已經作過了 不必再寫 for host in hosts: data['params']['filter']['host'].append(host) 將主機加入參數裏面 response = requests.post(self.url,data=json.dumps(data),headers=self.headers) lists = json.loads(response.text)['result'] result = [ lists[i]['hostid'] for i in range(len(lists)) ] return result ###返回主機hostsid def graph_get(self,res): ###請求主機圖形結果 hosts_id = self.get_host(res) ### 講hostsid 賦值給hosts_id data = parame.graph_get data['auth'] = self.authid for hosts in hosts_id: data['params']['hostids'].append(hosts) response = requests.post(self.url,data=json.dumps(data),headers=self.headers) graph_id = json.loads(response.text)['result'] result = [] for index in range(len(graph_id)): ###循環遍及判斷是不是網卡圖形,需求不一樣意此處能夠不用re 大家直接 append 就好 if re.search('Network traffic on em.',graph_id[index]['name']): result.append(graph_id[index]['graphid']) elif re.search('eth',graph_id[index]['name']): result.append(graph_id[index]['graphid']) else: pass return result def screen_add(self,graph_ids,screen_name): ###建立圖形 response = self.graph_get(graph_ids) x = 0 ### x爲行 此處的定義 取決於parame.screen_add 裏面的hsize 和vsize 最多爲 hsize - 1 or vsize -1 y = 0 ### y爲列 parame.screen_add['params']['name'] = screen_name parame.screen_add['auth'] = self.authid for value in response: parame.screen_add['params']['screenitems'].append({ "resourcetype": 0, "resourceid": value, "width": "500", ###寬高度 "height": "100", "rowspan": 1, "colspan": 1, "x": x, "y": y }) if x == 1: ###此處判斷 咱們需求只須要兩行一列 等於1 x爲0 x = 0 y += 1 else: x += 1 time.sleep(0.01) response = requests.post(self.url,data=json.dumps(parame.screen_add),headers=self.headers) print(response.text) if __name__ == '__main__': try: func = Api() res = kwargs("%" + str(sys.argv[4]) + "%") ###數據庫傳遞的參數 func.screen_add(res,str(sys.argv[2])) ### 聚合圖形羣組名 except Exception as e: print(e) print('--name 聚合圖形組名 --hostname 匹配加入的主機') sys.exit(1)
##展現結果
json
此刻正是咱們須要的結果,有問題 歡迎在下方留言 QQ:1301927919api