1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
| #!/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)
|