Zabbixへホスト追加
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
from zabbix.api import ZabbixAPI | |
from collections import defaultdict | |
def multi_dimension_dict(dimension, callable_obj=int): | |
""" | |
pythonで多次元連想配列を使う関数 | |
参照元: http://materia.jp/blog/20121119.html | |
""" | |
nodes = defaultdict(callable_obj) | |
for i in range(dimension-1): | |
p = nodes.copy() | |
nodes = defaultdict(lambda : defaultdict(p.default_factory)) | |
return nodes | |
def get_group_id(obj, host_group): | |
""" | |
引数で渡された `hostgroup` のグループIDを取得します。 | |
""" | |
# Method設定 | |
method = 'hostgroup.get' | |
# Query設定 | |
zquery = multi_dimension_dict(2) | |
zquery['output'] = 'extend' | |
zquery['filter']['name'] = [host_group] | |
# 実行 | |
zapi = obj | |
r = zapi.do_request(method, zquery) | |
return r | |
def create_host(obj, host_name, gid, display_name=None): | |
""" | |
Zabbixに監視ホストを追加します。 | |
ここでは追加するだけを目的とし、テンプレートは紐づけません。 | |
""" | |
# Method設定 | |
method = 'host.create' | |
# Query設定 | |
zquery = {} | |
zquery['host'] = host_name | |
if(display_name): zquery['name'] = display_name | |
zquery['interfaces'] = [{'type':1, 'main':1, 'useip':1, 'ip':'127.0.0.1', 'dns':'', 'port':'10050'}] | |
zquery['groups'] = [{'groupid':gid}] | |
zquery['inventory_mode'] = 0 | |
# 実行 | |
zapi = obj | |
r = zapi.do_request(method, zquery) | |
return r | |
if __name__ == '__main__': | |
""" | |
Zabbixサーバにホストを追加するスクリプト例 | |
追加するホストは `ホスト名:TEST-HOST, 表示名:TESTホスト` です。 | |
""" | |
# Zabbixサーバ情報 | |
zabbix_url = 'http://ZabbixサーバのIP/zabbix' | |
username = 'admin' | |
password = 'zabbix' | |
# グループ名 | |
host_group = 'TESTグループ' | |
# ホスト名 | |
host_name = 'TEST-HOST' | |
display_name = 'TESTホスト' | |
# Zabbixサーバログイン | |
zapi = ZabbixAPI(url=zabbix_url, user=username, password=password) | |
# グループIDを取得 | |
r = get_group_id(zapi, host_group) | |
gid = r['result'][0]['groupid'] | |
# ホストを追加 | |
r = create_host(zapi, host_name, gid, display_name) | |
print(r['result']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment