#!/usr/bin/python #coding:utf-8 from zabbix_api import ZabbixAPI import json server="http://172.16.206.130/zabbix" username="Admin" password="zabbix" zapi = ZabbixAPI(server=server,path="",log_level=0) zapi.login(username,password) info=[{"name": "ECS0001", "ip": "172.16.206.128", "bandwidthout": "1M", "internet_ip": "", "team": "Tank", "id": "i-23zmvm8uz"},{"name ": "ECS0007","ip": "172.16.206.130", "bandwidthout": "1M", "internet_ip": "120.54.6.78", "team": "Tesla", "id": "i-23s02ihno"}] macro_list = [] for I in info: visible_name = I[‘name‘] band = I[‘bandwidthout‘] # print visible_name,band if band != "0M": ##计算出网络带宽宏的值 network_threshold = str(int(int(band.strip(‘M‘))*0.8*1000)) + ‘K‘ # print network_threshold ##通过主机可见名查找hostid hostinfo=zapi.host.get({"output":"extend","filter":{"name":visible_name}}) hostid=hostinfo[0][‘hostid‘] ##通过hostid获取主机的所有宏 host_macro_get=zapi.usermacro.get({"output":"extend","hostids":hostid}) if len(host_macro_get) ==0: host_macro_create=zapi.usermacro.create({"hostid":hostid,"macro":"{$NETWORK_THRESHOLD}","value":network_threshold}) print "host %s has no macro,but create a new macro" % visible_name else: for X in host_macro_get: macro = X[‘macro‘] macro_list.append(macro) if "{$NETWORK_THRESHOLD}" not in macro_list: ##通过hostid创建主机宏 host_macro_create=zapi.usermacro.create({"hostid":hostid,"macro":"{$NETWORK_THRESHOLD}","value":network_threshold}) print "host $s add a macro" % visible_name else: ##获取主机上{$NETWORK_THRESHOLD}宏的值 for Y in host_macro_get: if Y[‘macro‘] == ‘{$NETWORK_THRESHOLD}‘: current_network_threshold_value = Y[‘value‘] macro_id = Y[‘hostmacroid‘] if network_threshold == current_network_threshold_value: print "The current macro value on host %s is latest" %visible_name else: ##更新NETWORK_THRESHOLD宏的值 host_macro_update=zapi.usermacro.update({"hostmacroid":macro_id,"value":network_threshold}) print "macro value on host %s updated" %visible_name else: print "The host %s has no internet_ip" % visible_name
需求:对所有云主机添加公网带宽监控,但不是每一台主机都有公网IP,有公网IP的主机的带宽也不完全相同,比如有的是1M,有的是5M,带宽监控的阈值为带宽值*0.8。例如1M的带宽,监控的阈值为0.8M。(注意:经过测试,在zabbix的trigger中这是0.8M,不会发出告警,但是阈值为大于1M的小数时又可以告警,怀疑是小于1M时,zabbix自动将单位换成K导致的。后来索性在定义带宽监控阈值时将单位统一为K,并且一定要为整数。如1300K可以,但是1300.5K则不会告警。)
脚本思路:监控阈值在每台主机上去添加主机宏,不是手动添加,而是通过zabbix API为主机添加宏。
具体的过程如下:
通过CMDB接口拿到所有主机的信息,包括zabbix主机可见名和带宽信息,做判断,公网带宽为0M时,不添加主机宏。当不为0M时,先判断主机上是否存着这个宏,如果不存在则创建这个宏,如果存在,先比较该宏的值是否和由的带宽值计算出的告警阈值相等,如果相等,表示带宽没有更新过,不做处理。如果不相等,则表示带宽是调整过的,需要更新主机宏上的带宽阈值。
时间: 2024-10-08 08:04:50