本帖最后由 monicazhang 于 2017-9-21 15:59 编辑
前言 现在许多Zabbix二次开发产品,都是"换汤不换药",大多以开发前端页面,数据来源于Zabbix库。而读取Zabbix数据有两个方法:读取数据库 与Zabbix API 本篇文章主要讲解如何用这两种方法进行Zabbix开发,拒绝重复性操作。
0x01 读取数据库
许多Zabbix使用者认为:读取数据库数据需要非常了解数据库结构,需要了解每个表在做什么;这是个错误的观点,你只需要简单的了解一些数据表在存储什么数据就OK了,利用Zabbix自带功能DEBUG模式找到需要执行的SQL语句。
▲ 开启方法
Administration > User groups > 勾选Debug mode
打开之后在每个页面右下角会出现一个Debug
开启之后就可以看到每一个功能所执行的SQL语句 ▲ 应用案例
需求:每周告警TOP10
实现:查询Events,DEBUG模式查看SQL语句,筛选统计出前10
SQL = """SELECT count(distinct e.eventid) as cnt_event, h.host, t.description, t.priorityFROM events e, hosts h, triggers t, functions f, items iWHERE h.hostid = i.hostid and i.itemid = f.itemid and t.triggerid=f.triggerid and t.triggerid=e.objectidand t.priority > 3and e.clock > %s GROUP BY h.host,t.triggerid,t.description,t.expression,t.priorityORDER BY cnt_event desc, h.host, t.description, t.triggerid;""" % weektime 效果图:
0x02 Zabbix API
相对于直接读取数据库,Zabbix API更容易入手也更安全,不足地方在于速度肯定比不上直接插库快,这里的安全是在不了解数据库结构的情况下,直接修改数据库可能会出错,那使用API肯定是安全的;
需要学习Zabbix API建议直接读官网文档:[ /documentation/3.0/manual/api]documentation/3.0/manual/api[/url]
Github上也有许多优秀的现成框架:
▲ 应用案例
需求:批量修改依赖
实现:查看对应API请求完成
# 代码片
# 登录与基类
def Login(self,user,passwd): @self.Base('user.login') def _GetAuth(user,passwd): return {"user": user,
"password": passwd} auth = _GetAuth(user,passwd)
if isinstance(auth,unicode): print("[.] Login OK") self.AUTH = auth
return self.AUTH
else: print("[!] Error Login")
def Base(self,method): def _Data(data): def _Dict(*args, **kw): D = {
"jsonrpc": "2.0",
"method": method,
"params": data(*args, **kw),
"id": 1, } D['auth'] = self.AUTH Dict = json.dumps(D) Post = self.ZabbixPost(Dict)
if 'error' in Post:
return Post['error']
else:
return Post['result']
return _Dict
return _Data
(再次拒绝重复性操作;上图为一个需要批量修改的需求,如果首领知道我是一个个添加,肯定会被↓→↓← + 重手一套带走) ▲ 应用案例 2
需求:批量添加web监控项
实现:把需要添加的信息填入excel或运维平台,通过读取信息请求API批量添加
# 读excel
import xlrdimport collections
def ReadExcel(filename): Data = xlrd.open_workbook(filename) Table = Data.sheets()[0] Nrows = Table.nrows Ncols = Table.ncols DataList = [] Dict = collections.OrderedDict() for x in xrange(Nrows): if x == 0 : continue for y in xrange(Ncols): Dict[Table.cell_value(0,y)] = Table.cell_value(x,y) DataList.append(Dict) Dict = collections.OrderedDict() return DataList
# 需求具体实现
def FastHttp(zabbix,TemplateName,Application,Name,StepUrl,StepsRequired,Denpen=None): HostID = zabbix.GetHostID("Zabbix Server")
if zabbix.GetHostID("Zabbix Server") else False if not HostID:
print "No find Host" exit() TemplateID = zabbix.GetTemplate(TemplateName) if zabbix.GetTemplate(TemplateName) \
else zabbix.CreateTemplate(TemplateName,HostID)
print "[-] %s TemplateID : %s " % (TemplateName,TemplateID) ApplicationID = zabbix.GetApplication(TemplateID)[Application] if Application in zabbix.GetApplication(TemplateID).keys() \
else zabbix.CreateApplication(Application,TemplateID)
print "[-] %s ApplicationID : %s " % (Application,ApplicationID) httpID = zabbix.GetHttp(HostID)[Name] if Name in zabbix.GetHttp(HostID).keys() else \ zabbix.CreateHttp(TemplateID,name=Name,stepNo="1",stepName=Name,stepUrl=StepUrl,applicationid=ApplicationID, stepFollow_redirects="0",stepRequiredString=StepsRequired) print "[-] %s HttpID : %s " % (Name,httpID) TriggersName = u"%s监控异常" % Name TriggersExpression = u"{%s:web.test.fail[%s].sum(#3)}>2" % (TemplateName,Name) TriggersSeverity = "4" AllTrigger = zabbix.GetTrigger(TemplateID) TriggersID = ''
if TriggersName in AllTrigger.keys():
print "[!] Trigger already exists : %s" % TriggersName
else: TriggersID = zabbix.CreateTrigger(TriggersName,TriggersExpression,TriggersSeverity,StepUrl)
print "[-] Create Trigger: %s" % TriggersID
if Denpen: DenpenName = u"%s监控异常" % Denpen DenpenID = AllTrigger[DenpenName] CreateDepen = zabbix.TriggerAdddepen(TriggersID,DenpenID)
print "[-] %s response: %s" %(TriggersID,CreateDepen)
原创:运维大部队
|