zabbix_addhost.py
12.1 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/python
# encoding:utf-8
#######################################################
# author: liuh 2018-10-28
# version: v1.0
# python version: 2
#######################################################
import json
import urllib2
from urllib2 import URLError
import sys
import xlrd
import getopt
class ZabbixTools:
def __init__(self, url, user, passwd):
self.url = url
self.header = {"Content-Type":"application/json"}
self.user = user
self.passwd = passwd
# 登陆验证
def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.user,
"password": self.passwd
},
"id": 0
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
print "Auth Failed, please Check your name and password:", e.code
else:
response = json.loads(result.read())
result.close()
self.authID = response['result']
return self.authID
# 获取主机
def host_get(self,hostName):
data = json.dumps({
"jsonrpc":"2.0",
"method":"host.get",
"params":{
"output":["hostid","name"],
"filter":{"host":hostName}
},
"auth":self.user_login(),
"id":1,
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server could not fulfill the request.'
print 'Error code: ', e.code
else:
response = json.loads(result.read())
result.close()
print "Number Of %s: " % hostName, len(response['result'])
lens=len(response['result'])
if lens > 0:
return response['result'][0]['name']
else:
return ""
# 获取主机组
def hostgroup_get(self, hostgroupName):
data = json.dumps({
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params":{
"output": "extend",
"filter": {
"name": [
hostgroupName,
]
}
},
"auth":self.user_login(),
"id":1,
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
lens=len(response['result'])
if lens > 0:
self.hostgroupID = response['result'][0]['groupid']
return response['result'][0]['groupid']
else:
print "no GroupGet result"
return ""
# 获取模板
def template_get(self, templateName):
data = json.dumps({
"jsonrpc":"2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"host": [
templateName,
]
}
},
"auth":self.user_login(),
"id":1,
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
self.templateID = response['result'][0]['templateid']
return response['result'][0]['templateid']
# 创建host
#def host_create(self, hostName,visibleName,hostIp,dnsName,proxyName, hostgroupName, templateName1, templateName2):
def host_create(self, hostName,visibleName,hostIp, hostgroupName, proxyName, templateName1, templateName2):
root_dict = {
"jsonrpc":"2.0",
"method":"host.create",
"params":{
"host": hostName,
"name": visibleName,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": hostIp,
"dns": "",
"port": "10050"
}
],
"groups": [
{
"groupid": self.hostgroup_get(hostgroupName)
}
],
# "templates": [
# {
# "templateid": self.template_get(templateName1)
# },
# {
# "templateid": self.template_get(templateName2)
# }
# ],
},
"auth": self.user_login(),
"id":1
}
if(proxyName != ""):
root_dict["params"]["proxy_hostid"] = self.proxy_get(proxyName)
templates = []
if(templateName1 != ""):
templates.append({"templateid": self.template_get(templateName1)})
if(templateName2 != ""):
templates.append({"templateid": self.template_get(templateName2)})
if len(templates) > 0:
root_dict["params"]["templates"] = templates
data = json.dumps(root_dict)
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "host : %s is created! id is %s\n" % (hostip, response['result']['hostids'][0])
self.hostid = response['result']['hostids']
return response['result']['hostids']
# zabbix_proxy获取函数
def proxy_get(self, ProxyName):
data = json.dumps({
"jsonrpc":"2.0",
"method": "proxy.get",
"params": {
"output": "extend",
"selectInterface": "extend",
"filter": {
"host": [ ProxyName, ]
}
},
"auth":self.user_login(),
"id":1,
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
self.templateID = response['result'][0]['proxyid']
return response['result'][0]['proxyid']
def usage():
print("""
useage: zabbix_addhost.py [options]
[+]--baseurl=[any] | zabbix web url | default: http://192.168.9.133:9210
[+]--ipstart=[any] | ip range start | default: 192.168.66.2
[+]--ipend=[any] | ip range end | default: 192.168.66.41
[+]--user=[any] | zabbix web login user | default: Admin
[+]--passwd=[any] | zabbix web login password | default: zabbix
[+]--hostgroup=[any] | host group name | default: tx1
[+]--proxyname=[any] | porxy name | default: ""
[+]--template1=[any] | template name 1 | default: "starnet_tx1_slave_tp"
[+]--template2=[any] | template name 2 | default: "Template OS Linux"
""")
# 程序的入口
if __name__ == "__main__":
try:
options,args = getopt.getopt(sys.argv[1:],"",["help","baseurl=","ipstart=", "ipend=", "user=",\
"passwd=", "hostgroup=", "proxyname=", "template1=", "template2="])
except getopt.GetoptError:
print("error: invalid args")
usage()
sys.exit(-1)
baseurl = "http://192.168.9.133:9210"
ipstart = "192.168.66.2"
ipend = "192.168.66.2"
user = "Admin"
passwd = "zabbix"
hostgroup = "tx1"
proxyname = ""
template1 = "starnet_tx1_slave_tp"
template2 = "Template OS Linux"
for name,value in options:
if name in ("--help"):
usage()
if name in ("--baseurl"):
baseurl = value
if name in ("--ipstart"):
ipstart = value
if name in ("--ipend"):
ipend = value
if name in ("--user"):
user = value
if name in ("--passwd"):
passwd = value
if name in ("--hostgroup"):
hostgroup = value
if name in ("--proxyname"):
proxyname = value
if name in ("--template1"):
template1 = value
if name in ("--template2"):
template2 = value
print("baseurl={}\n ipstart={}\n ipend={}\n user={}\n passwd={}\n hostgroup={}\n proxyname={}\n template1={}\n template2={}\n".format(\
baseurl, ipstart, ipend, user, passwd, hostgroup, proxyname, template1, template2))
url=baseurl+"/api_jsonrpc.php"
# # 实例化ZabbixTools对象
test = ZabbixTools(url, user, passwd)
sstrs = ipstart.split(".")
estrs = ipend.split(".")
ipbase = "{}.{}.{}".format(sstrs[0], sstrs[1], sstrs[2])
intstart = int(sstrs[3])
intend = int(estrs[3])
# ipbase = "192.168.66"
for i in range(intstart,intend+1):
hostip = "{}.{}".format(ipbase,i)
print(hostip)
hostname = proxyname+'_'+hostip
test.host_create( hostname,hostname,hostip, hostgroup, proxyname, template1, template2)