#!/usr/bin/python
import
requests,json
from zabbix_api
import
ZabbixAPI
server=
"http://zabbix.cheyaoshicorp.com"
username=
"zhouhai"
password=
"zhouhai"
zapi = ZabbixAPI(server=server, path=
""
, log_level=0)
zapi.login(username, password)
def get_hostmacroid(host_name):
''
'
通过host_name获取当前主机的$TRAFFIC_THRESHOLD宏ID
''
'
hosts = zapi.host.get({
"output"
:
"extend"
,
"filter"
:{
"name"
:host_name}})
hostid = hosts[0].get(
'hostid'
)
host_macros = zapi.usermacro.get({
"output"
:
"extend"
,
"hostids"
:hostid})
macros = [_
for
_
in
host_macros
if
_.get(
'macro'
) ==
'{$TRAFFIC_THRESHOLD}'
]
hostmacroid = [macros[0].get(
'hostmacroid'
)]
if
len(macros) > 0
else
None
return
hostid, hostmacroid
def delete_host_macro(host_name):
hostid, hostmacroid = get_hostmacroid(host_name)
if
hostmacroid:
zapi.usermacro.delete(hostmacroid)
def create_host_macro(host_name, bandwidthout):
band = int(bandwidthout.replace(
'M'
,
''
))
if
band == 0:
return
hostid, hostmacroid = get_hostmacroid(host_name)
if
hostid:
zapi.usermacro.create({
"hostid"
: hostid,
"macro"
:
"{$TRAFFIC_THRESHOLD}"
,
"value"
:
'{0}K'
.
format
(band * 800)
})
def main():
''
'
1.删除主机的带宽宏
2.创建主机宏
''
'
url =
'http://cmdb.cheyaoshicorp.com/api/ecs'
r = requests.get(url)
ecss = json.loads(r.text)
for
_
in
ecss:
host_name = _.get(
'name'
)
bandwidthout = _.get(
'bandwidthout'
)
delete_host_macro(host_name)
create_host_macro(host_name, bandwidthout)
main()