脚本内容:
#!/usr/bin/python #-*- coding:utf8 -*- import json,sys,argparse from zabbix_api import ZabbixAPI server = "http://172.16.206.128/zabbix" username = "Admin" password = "zabbix" zapi = ZabbixAPI(server=server, path="", log_level=0) zapi.login(username, password) def get_args(): parser = argparse.ArgumentParser() parser.add_argument("-H", "--host", help="host name") parser.add_argument("-i", "--ip", help="host ip") parser.add_argument("-g", "--group", help="group name") parser.add_argument("-p", "--proxy", help="proxy host name") parser.add_argument("-t", "--templates", help="template name") # 解析所传入的参数 args = parser.parse_args() if not args.host: args.host = raw_input(‘host: ‘) if not args.ip: args.ip = raw_input(‘ip: ‘) if not args.templates: args.templates = raw_input(‘templates: ‘) return args def get_proxy_id(proxy): get_proxy_id = zapi.proxy.get( { "output": "proxyid", "selectInterface": "extend", "filter": { "host": proxy } } ) proxy_id=get_proxy_id[0][‘proxyid‘] return proxy_id def get_group_id(groups): group_id = zapi.hostgroup.get( { "output": "groupid", "filter": { "name":groups.split(",") } } ) return group_id def get_templates_id(templates): templates_id = zapi.template.get( { "output": "templateid", "filter": { "host":templates.split(",") } } ) return templates_id def create_host_with_proxy(hostname,group_id,templates_id,ip,proxy_id): host_create = zapi.host.create( { "host":hostname, "groups":group_id, "templates":templates_id, "interfaces":[ { "type":1, "main":1, "useip":1, "ip":ip, "dns":"", "port":"10050" } ], "proxy_hostid":proxy_id, "status":0 } ) return "host add success!" def create_host_without_proxy(hostname,group_id,templates_id,ip): host_create = zapi.host.create( { "host": hostname, "groups": group_id, "templates": templates_id, "interfaces":[ { "type":1, "main":1, "useip":1, "ip":ip, "dns":"", "port":"10050" } ], "status":0 } ) return "host add success!" if __name__ == "__main__": args = get_args() hostname = args.host ip = args.ip group_id = get_group_id(args.group) templates_id = get_templates_id(args.templates) if args.proxy: proxy_id = get_proxy_id(args.proxy) print create_host_with_proxy(hostname,group_id,templates_id,ip,proxy_id) else: print create_host_without_proxy(hostname,group_id,templates_id,ip)
脚本内容解释:
要使用本脚本,需要安装zabbix-api模块
脚本思路:
通过zabbix API添加host,需要知道以下信息:
hostname:主机名(不是可见名)
ip:主机IP
group_ip:host所属组的组id
templates_id:host关联模板的模板id
proxy_id:如果是通过proxy添加主机,则需要给出proxy_id,这个是可选项,所以我写了两个函数来区分有proxy和没有proxy的情况
hostname、ip这些可以直接通过命令行传参获取到,但是group_id、templates_id、proxy_id需要通过zabbix API的方法去获取到,比如:group_id需要事先知道group name,才能通过api查询到,脚本中我对于如何获取group_id、templates_id、proxy_id都用函数去实现了,所以在命令行传参时,只需要传递group name、templates name、proxy name就可以获取到对应的id了。
如果不清楚参数是怎么获取的,请查阅argparse模块相关资料
参考资料:https://github.com/CNSRE/Zabbix-PyZabbix/blob/master/zabbix_host_add.py
本文出自 “zengestudy” 博客,请务必保留此出处http://zengestudy.blog.51cto.com/1702365/1850578
原文地址:http://zengestudy.blog.51cto.com/1702365/1850578