要求:利用zabbix api去获取指定模板下的监控项,然后获取自己需要的监控项,根据监控项获取触发器的表达式,修改触发器的出发时间为9:00-11:30,13:00-15:30
思路讲解:
首先利用zabbix api中的template.get方法获取指定模板的templateid,然后利用item.key方法指定参数为templateids,就可以获取到templateid下的itemid,itemkey,itemname等数据,然后根据自己需要筛选出自己需要的item以及相关的数据,后面再根据trigger.get方法,其中itemids参数就可以获取到triggerid以及expression(表达式),最后根据trigger.update方法,指定triggerids参数,就可以修改expression(表达式)。
详细代码:
#!/usr/bin/env python
#coding=utf-8
#Function:Get the trigger for the specified template and change the trigger time to 9:00-11:30 and 13:00-15:30
#导入模块,urllib2是一个模拟浏览器HTTP方法的模块
import json
import urllib2
import sys
import re
from urllib2 import Request, urlopen, URLError, HTTPError
#url and url header
ip="10.10.30.232"
zabbix_url="http://{0}/zabbix/api_jsonrpc.php".format(ip)
zabbix_header = {"Content-Type":"application/json"}
zabbix_user = "admin"
zabbix_pass = "zabbix"
auth_code = ""
match_item=['mktdt00 update', 'mktdt01 update', 'mktdt03 update', 'file.size', 'file.modify.time']
#auth user and password
def get_auth_id():
auth_data = json.dumps(
{
"jsonrpc":"2.0",
"method":"user.login",
"params":
{
"user":zabbix_user,
"password":zabbix_pass
},
"id":0
})
# create request object
request = urllib2.Request(zabbix_url,auth_data)
for key in zabbix_header:
request.add_header(key,zabbix_header[key])
#auth and get authid
try:
result = urllib2.urlopen(request)
except HTTPError, e:
print 'The server couldn\'t fulfill the request, Error code: ', e.code
except URLError, e:
print 'We failed to reach a server.Reason: ', e.reason
else:
response=json.loads(result.read())
result.close()
if 'result' in response:
auth_code=response['result']
return auth_code
else:
print response['error']['data']
return 0
#Get his id based on the name of the template
# return templateid
def get_template_id(auth_code):
json_data={
"method":"template.get",
"params":{
"output": "templateid",
"filter":{
"host":["Template App HQCloud UT5"],
}
}
}
json_base={
"jsonrpc":"2.0",
"auth":auth_code,
"id":1
}
json_data.update(json_base)
if len(auth_code) == 0:
sys.exit(1)
if len(auth_code) != 0:
get_host_data = json.dumps(json_data)
# create request object
request = urllib2.Request(zabbix_url,get_host_data)
for key in zabbix_header:
request.add_header(key,zabbix_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())
result.close()
#print(json.dumps(response,indent=4))
#print (response["result"][0]["templateid"])
return response["result"][0]["templateid"]
#Get the following monitoring items based on the id of the template
# return itemid itemname itemkey item_complete_key
def get_item_key(auth_code, templateid):
json_data={
"method":"item.get",
"params":{
"templateids":templateid,
"output": [
"itemid",
"name",
"key_"
],
}
}
json_base={
"jsonrpc":"2.0",
"auth":auth_code,
"id":1
}
json_data.update(json_base)
if len(auth_code) == 0:
sys.exit(1)
if len(auth_code) != 0:
get_host_data = json.dumps(json_data)
# create request object
request = urllib2.Request(zabbix_url,get_host_data)
for key in zabbix_header:
request.add_header(key,zabbix_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())
result.close()
item_id=[]
item_name=[]
item_ckey=[]
item_key=[]
pattern=re.compile(r'\[(.*?)\]')
for i in range(len(response["result"])):
item_id.append(response["result"][i]["itemid"].encode('utf-8'))
item_name.append(response["result"][i]["name"].encode('utf-8'))
item_ckey.append(response["result"][i]["key_"].encode('utf-8'))
temp=re.findall(pattern, response["result"][i]["key_"].encode('utf-8'))
item_key.append(temp[0])
return item_id, item_name, item_ckey, item_key
#Filter out the items that need to be modified
# return modified_item_id modified_item_key modified_item_complete_key
def handle_item_stat(item_id, item_name, item_ckey, item_key):
match_item_id=[]
match_item_ckey=[]
match_item_key=[]
for item in match_item:
for i in range(len(item_name)):
if item==item_name[i]:
match_item_id.append(item_id[i])
match_item_ckey.append(item_ckey[i])
match_item_key.append(item_key[i])
return match_item_id, match_item_ckey, match_item_key
#Get the id and expression of the trigger based on the id of the monitored item
# return triggerid trigger_expression
def get_triggerid(auth_code, itemid):
json_data={
"method":"trigger.get",
"params":{
"itemids":itemid,
"output": [
"triggerid",
"expression"
],
"expandExpression": True
}
}
json_base={
"jsonrpc":"2.0",
"auth":auth_code,
"id":1
}
json_data.update(json_base)
if len(auth_code) == 0:
sys.exit(1)
if len(auth_code) != 0:
get_host_data = json.dumps(json_data)
# create request object
request = urllib2.Request(zabbix_url,get_host_data)
for key in zabbix_header:
request.add_header(key,zabbix_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())
result.close()
triggerid = response["result"][0]["triggerid"].encode('utf-8')
expression = response["result"][0]["expression"].encode('utf-8')
return triggerid, expression
#The trigger time of the trigger expression is added to the trigger expression based on the original trigger expression.
# flag 0 represent time exist;1 represent time not exist
# return new_expression
def modify_expresssion(expression, key, ckey, flag):
key = '[' + key + ']'
pattern=re.compile(r'\[(.*?)\]')
alter_expression = re.sub(pattern, key, expression)
template="{Template App HQCloud UT5:"
template_key= template + ckey
expre=" and (({0}.time(){1}>093000 and {2}.time(){3}<113000) or ({4}.time(){5}>130000 and {6}.time(){7}<153000))".format(template_key,'}',template_key,'}',template_key,'}',template_key,'}')
if expre not in alter_expression:
expre = alter_expression + expre
flag=1
return expre,flag
#Modify the expression of the trigger based on the id of the trigger
def modify_trigger_expression(auth_code, triggerid, ee):
json_data={
"method":"trigger.update",
"params":{
"triggerid": triggerid,
"expression": ee,
}
}
json_base={
"jsonrpc":"2.0",
"auth":auth_code,
"id":1
}
json_data.update(json_base)
if len(auth_code) == 0:
sys.exit(1)
if len(auth_code) != 0:
get_host_data = json.dumps(json_data)
# create request object
request = urllib2.Request(zabbix_url,get_host_data)
for key in zabbix_header:
request.add_header(key,zabbix_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())
result.close()
print(json.dumps(response,indent=4))
def main():
auth_code = get_auth_id()
templateid = get_template_id(auth_code)
item_id, item_name, item_ckey, item_key = get_item_key(auth_code, templateid)
match_item_id, match_item_ckey, match_item_key = handle_item_stat(item_id, item_name, item_ckey, item_key)
#Process each monitoring item
for i in range(len(match_item_id)):
triggerid, expression = get_triggerid(auth_code, match_item_id[i])
new_expression, flag = modify_expresssion(expression,match_item_key[i],match_item_ckey[i],0)
if flag==1:
modify_trigger_expression(auth_code, triggerid, new_expression)
if __name__=='__main__':
main()
注意:利用trigger.get方法时,获取的是表达式的id,并不能获取具体的信息,所以我们需要利用expandExpression参数,其可以使得表达式展开,这样就可以得到具体的表达式。