zabbix3.0 批量更新主机关联的模板

简介:

逻辑是

host.get 获取hostid 

template.get 获取目前主机已经有的模板id

template_get_new 获取新模板的id

host.update 更新


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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
1. 登陆
# !/usr/bin/env python
# coding:utf-8
import  json
import  urllib2
# based url and required header
url  =  "http://zabbix's ip/api_jsonrpc.php"
header  =  { "Content-Type" "application/json" }
# auth user and password
data  =  json.dumps(
{
     "jsonrpc" "2.0" ,
     "method" "user.login" ,
     "params" : {
     "user" "139" ,
     "password" "xxxxxx"
},
"id" 0
})
# create request object
request  =  urllib2.Request(url,data)
for  key  in  header:
     request.add_header(key,header[key])
# auth and get authid
try :
     result  =  urllib2.urlopen(request)
except  urllib2.URLError as e:
     print  "Auth Failed, Please Check Your Name And Password:" ,e.code
else :
     response  =  json.loads(result.read())
     result.close()
     print  "Auth Successful. The Auth ID Is:" ,response[ 'result' ]
 
输出
Auth Successful. The Auth  ID  Is: b307f26d7874e4171b96cdfc463fe08f
 
2.zabbix 批量更新主机关联的模板
 
# !/usr/bin/env python
# coding:utf-8
import  json
import  urllib2
from  urllib2  import  URLError
import  sys
class  zabbixtools:
     def  __init__( self ):
         self .url  =  "http://zabbix.a.com/api_jsonrpc.php"
         self .header  =  { "Content-Type" "application/json" }
         self .authID  =  self .user_login()
     def  user_login( self ):
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "user.login" ,
                     "params" : {
                         "user" "139" ,
                         "password" "xxxxxx"
                         },
                     "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()
             authID  =  response[ 'result' ]
             return  authID
 
     def  get_data( self ,data,hostip = ""):
         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
             return  0
         else :
             response  =  json.loads(result.read())
             result.close()
             return  response
 
     def  host_get( self ,hostip):
         # hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
         data  =  json.dumps(
             {
                 "jsonrpc" "2.0" ,
                 "method" "host.get" ,
                 "params" : {
                     "output" : [ "hostid" "name" "status" "host" ],
                     "filter" : { "host" : [hostip]}
                 },
                 "auth" self .authID,
                 "id" 1
             })
         res  =  self .get_data(data)[ 'result' ]
         if  (res ! =  0 and  ( len (res) ! =  0 ):
             # for host in res:
             print  type (res)
             host  =  res[ 0 ]
             if  host[ 'status' = =  '1' :
                 print  "\t" "\033[1;31;40m%s\033[0m"  %  "Host_IP:" "\033[1;31;40m%s\033[0m"  %  host[ 'host' ].ljust(
                     15 ),  '\t' "\033[1;31;40m%s\033[0m"  %  "Host_Name:" "\033[1;31;40m%s\033[0m"  %  host[ 'name' ].encode(
                     'UTF8' ),  '\t' "\033[1;31;40m%s\033[0m"  %  u '未在监控状态' .encode( 'UTF8' )
                 return  host[ 'hostid' ]
             elif  host[ 'status' = =  '0' :
                 print  "\t" "\033[1;32;40m%s\033[0m"  %  "Host_IP:" "\033[1;32;40m%s\033[0m"  %  host[ 'host' ].ljust(
                     15 ),  '\t' "\033[1;32;40m%s\033[0m"  %  "Host_Name:" "\033[1;32;40m%s\033[0m"  %  host[ 'name' ].encode(
                     'UTF8' ),  '\t' "\033[1;32;40m%s\033[0m"  %  u '在监控状态' .encode( 'UTF8' )
                 return  host[ 'hostid' ]
             print
         else :
             print  '\t' "\033[1;31;40m%s\033[0m"  %  "Get Host Error or cannot find this host,please check !"
             return  0
 
     def  host_del( self ):
         hostip  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter Your Check Host:Host_ip :' )
         hostid  =  self .host_get(hostip)
         if  hostid  = =  0 :
             print  '\t' , "\033[1;31;40m%s\033[0m"  %  "This host cannot find in zabbix,please check it !"
             sys.exit()
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "host.delete" ,
                     "params" : [{ "hostid" : hostid}],
                     "auth" self .authID,
                     "id" 1
                 })
         res  =  self .get_data(data)[ 'result' ]
         print  type (res)
         if  'hostids'  in  res.keys():
             print  "\t" , "\033[1;32;40m%s\033[0m"  %  "Delet Host:%s success !"  %  hostip
         else :
             print  "\t" , "\033[1;31;40m%s\033[0m"  %  "Delet Host:%s failure !"  %  hostip
     def  hostgroup_get( self ):
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "hostgroup.get" ,
                     "params" : {
                         "output" "extend" ,
                         },
                     "auth" self .authID,
                     "id" 1 ,
                     })
         res  =  self .get_data(data)
         if  'result'  in  res.keys():
             res  =  res[ 'result' ]
             if  (res ! = 0 or  ( len (res) ! =  0 ):
                 print  "\033[1;32;40m%s\033[0m"  %  "Number Of Group: " "\033[1;31;40m%d\033[0m"  %  len (res)
                 for  host  in  res:
                     print  "\t" , "HostGroup_id:" ,host[ 'groupid' ], "\t" , "HostGroup_Name:" ,host[ 'name' ].encode( 'UTF8' )
                 print
         else :
             print  "Get HostGroup Error,please check !"
 
     def  template_get( self ,hostid):
         templateid_list  =  []
 
         data  =  json.dumps(
             {
                 "jsonrpc" "2.0" ,
                 "method" "template.get" ,
                 "params" : {
                     "output" "hostid" ,
                     "hostids" : hostid,
                     # "filter": {"host": ["Template MongoDB Discovery"]}
                 },
                 "auth" self .authID,
                 "id" 1 ,
             })
         res  =  self .get_data(data)   # ['result']
         print  res
         if  'result'  in  res.keys():
             res  =  res[ 'result' ]
             for  host  in  res:
                 var  =  {}
                 print  host[ 'templateid' ]
                 var[ 'templateid' =  host[ 'templateid' ]
                 templateid_list.append(var)
         return  templateid_list
         '''
         if 'result' in res.keys():
             res = res['result']
             if (res != 0) or (len(res) != 0):
                 print "\033[1;32;40m%s\033[0m" % "Number Of Template: ", "\033[1;31;40m%d\033[0m" % len(res)
                 for host in res:
                     print "\t", "Template_id:", host['templateid'], "\t", "Template_Name:", host['name'].encode('GBK')
                 print
         else:
             print "Get Template Error,please check !"
         '''
         def  template_get_new( self ):
     templateid_list  =  []
 
     data  =  json.dumps(
         {
             "jsonrpc" "2.0" ,
             "method" "template.get" ,
             "params" : {
                 "output" "hostid" ,
                 # "hostids": hostid,
                 "filter" : { "host" : [ "Template MongoDB Discovery" ]}
             },
             "auth" self .authID,
             "id" 1 ,
         })
     res  =  self .get_data(data)   # ['result']
     print  res
     if  'result'  in  res.keys():
         res  =  res[ 'result' ]
         for  host  in  res:
             var  =  {}
             print  host[ 'templateid' ]
             var[ 'templateid' =  host[ 'templateid' ]
             templateid_list.append(var)
     return  templateid_list
 
 
 
     def  host_create( self ):
         hostip  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter your:Host_ip :' )
         groupid  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter your:Group_id :' )
         templateid  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter your:Tempate_id :' )
         g_list = []
         t_list = []
         for  in  groupid.split( ',' ):
             var  =  {}
             var[ 'groupid' =  i
             g_list.append(var)
         for  in  templateid.split( ',' ):
             var  =  {}
             var[ 'templateid' =  i
             t_list.append(var)
         if  hostip  and  groupid  and  templateid:
             data  =  json.dumps(
                     {
                         "jsonrpc" "2.0" ,
                         "method" "host.create" ,
                         "params" : {
                             "host" : hostip,
                             "interfaces" : [
                                 {
                                     "type" 1 ,
                                     "main" 1 ,
                                     "useip" 1 ,
                                     "ip" : hostip,
                                     "dns" : "",
                                     "port" "10050"
                                 }
                             ],
                             "groups" : g_list,
                             "templates" : t_list,
                     },
                         "auth" self .authID,
                         "id" 1 ,
                         })
             res  =  self .get_data(data,hostip)
             if  'result'  in  res.keys():
                 res  =  res[ 'result' ]
                 if  'hostids'  in  res.keys():
                     print  "\033[1;32;40m%s\033[0m"  %  "Create host success"
             else :
                 print  "\033[1;31;40m%s\033[0m"  %  "Create host failure: %s"  %  res[ 'error' ][ 'data' ]
         else :
             print  "\033[1;31;40m%s\033[0m"  %  "Enter Error: ip or groupid or tempateid is NULL,please check it !"
 
     def  host_update( self ):
         data  =  json.dumps(
             {
                 "jsonrpc" "2.0" ,
                 "method" "host.update" ,
                 "params" : {
                     "hostid" 10178 ,
                     "templates" 10180 ,
                     "status" 0 ,
                 },
                 "auth" self .authID,
                 "id" 1 ,
             })
         res  =  self .get_data(data)
         if  'result'  in  res.keys():
             res  =  res[ 'result' ]
             print  res
 
     def  host_update_template( self ,hostid,templateid):
         # hostid=['10178']
         # templateid = ['1001','10110','10180']
 
         data  =  json.dumps(
             {
                 "jsonrpc" "2.0" ,
                 "method" "host.update" ,
                 "params" : {
                     # "hostid": 10178,
                     # "templates": [{"templateid":10180},{"templateid":10110},{"templateid":10001}],
                     "hostid" : hostid,
                     "templates" : templateid,
                     "status" 0 ,
                 },
                 "auth" self .authID,
                 "id" 1 ,
             })
         res  =  self .get_data(data)
         print  res
         if  'result'  in  res.keys():
             res  =  res[ 'result' ]
             print  res
 
def  main():
     test  =  zabbixtools()
     hostid  =  test.host_get(hostip = '192.1.1.121' )
     print  type (hostid)
     templateid  =  test.template_get(hostid)
     print  templateid
     templatedid_new  =  test.template_get_new()
         print  templatedid_new
         for  id  in  templatedid_new:
             if  id  in  templateid:
                 print  "0K"
             else :
                 templateid.append( id )
         test.host_update_template(hostid, templateid)
     test.host_update_template(hostid,templateid)
     # print hostid
     # test.host_update_template()
     # test.hostgroup_get()
     # test.host_del()
     # test.host_create()
     # test.host_update()
     #test.host_getbyhost()
 
 
 
if  __name__  = =  "__main__" :
     main()


wKiom1nfJBGSj2RmAABQp1m-gKQ791.png


注意的地方

1."filter": {"host": [hostip]} 官网的例子,不要随便写filter,要看清楚再写,别乱尝试

2.hostids 这个要多去官网看看

3.create和update的时候,有些值需要是这种格式的,请千万别搞错了

[{'templateid': u'10001'}, {'templateid': u'10110'}, {'templateid': u'10140'}, {'templateid': u'10141'}, {'templateid': u'10180'}]


好像批量没有实现,继续写一个test方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def  test():
     test  =  zabbixtools()
     newlist  =  [{ '192.1.1.121' "Template MongoDB Discovery" }, { '192.1.1.124' "Template Redis Auto Discovery" }]
     for  in  newlist:
         for  key, value  in  i.iteritems():
             print  key, value
             host  =  key
             newtemplateid  =  value
             templatedid_new  =  test.template_get_new(newtemplateid)
             print  templatedid_new
             hostid  =  test.host_get(host)
             print  type (hostid)
             templateid  =  test.template_get(hostid)
             print  templateid
             print  "last ............."
             for  id  in  templatedid_new:
                 if  id  in  templateid:
                     print  "0K"
                 else :
                     templateid.append( id )
             test.host_update_template(hostid, templateid)


j_0057.gif



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1971760,如需转载请自行联系原作者

相关文章
|
3月前
|
关系型数据库 MySQL 数据库
MySQL数据库-关联删除
MySQL数据库-关联删除
19 0
|
监控
zabbix配置自动发现主机和自动关联模板
zabbix配置自动发现主机和自动关联模板
287 0
zabbix配置自动发现主机和自动关联模板
|
SQL 数据库
动态批量新建SQL数据库中的表
动态批量新建SQL数据库中的表
140 0
|
SQL 数据库
动态批量删除SQL数据库中的表
动态批量删除SQL数据库中的表
179 0
【视频】配置信息管理 的 使用方法(六):实现添加、修改、查询
   这个是使用配置信息管理实现添加、修改、查询的方法。    感谢 svnhost.cn 提供空间    
684 0