首页 > 代码库 > zabbix利用api批量添加item,并且批量配置添加graph

zabbix利用api批量添加item,并且批量配置添加graph

关于zabbix的API见,zabbixAPI

1item批量添加

我是根据我这边的具体情况来做的,本来想在模板里面添加item,但是看了看API不支持,只是支持在host里面添加,所以我先在一个host里面添加,然后在将item全部移动到模板里。

具体步骤就不说了,直接上代码:

为了快速完成,代码写的有点乱,也没怎么处理异常,算是第一版吧,有时间在优化  1 #!/usr/bin/env python

  2 #-*- coding: utf-8 -*-
  3 
  4 import json
  5 import sys
  6 import urllib2
  7 import argparse
  8 from urllib2 import URLError
  9 
 10 reload(sys)
 11 sys.setdefaultencoding(utf-8)
 12 
 13 class zabbix_api:
 14     def __init__(self):
 15         #self.url
 16         #self.url = http://zabbix.weimob.com/api_jsonrpc.php
 17         self.url = http://xxxxxx/api_jsonrpc.php‘  #zabbix地址
 18         self.header = {"Content-Type":"application/json"}
 19     def user_login(self):
 20         data =http://www.mamicode.com/ json.dumps({
 21                            "jsonrpc": "2.0",
 22                            "method": "user.login",
 23                            "params": {
 24                                       "user": "admin", #账号
 25                                       "password": "admin" #密码
 26                                       },
 27                            "id": 0
 28                            })
 29 
 30         request = urllib2.Request(self.url, data)
 31 
 32         for key in self.header:
 33             request.add_header(key, self.header[key])
 34 
 35         try:
 36             result = urllib2.urlopen(request)
 37         except URLError as e:
 38             print "\033[041m 认证失败,请检查URL !\033[0m",e.code
 39         except KeyError as e:
 40             print "\033[041m 认证失败,请检查用户名密码 !\033[0m",e
 41         else:
 42             response = json.loads(result.read())
 43             result.close()
 44             #print response[result]
 45             self.authID = response[result]
 46             return self.authID
 47     def host_get(self,hostName=‘‘):
 48         data=http://www.mamicode.com/json.dumps({
 49                 "jsonrpc": "2.0",
 50                 "method": "host.get",
 51                 "params": {
 52                           "output": "extend",
 53                           #"output": "selectInterfaces",
 54                           #"filter":{"host":""}
 55                           "filter":{"host":hostName}
 56                           },
 57                 "auth": self.user_login(),
 58                 "id": 1
 59                 })
 60         request = urllib2.Request(self.url,data)
 61         for key in self.header:
 62             request.add_header(key, self.header[key])
 63 
 64         try:
 65             result = urllib2.urlopen(request)
 66         except URLError as e:
 67             if hasattr(e, reason):
 68                 print We failed to reach a server.
 69                 print Reason: , e.reason
 70             elif hasattr(e, code):
 71                 print The server could not fulfill the request.
 72                 print Error code: , e.code
 73         else:
 74             response = json.loads(result.read())
 75             #print reqponse
 76             result.close()
 77 
 78 
 79             #print "主机数量: \033[31m%s\033[0m"%(len(response[result]))
 80             #print response
 81             #print response[result]
 82             #print response[result][templateid]
 83             for host in response[result]:
 84                 #print host[hostid]
 85                 c=host[hostid]
 86             return  c
 87 
 88 
 89     def host_interin(self,host_id):
 90 
 91         data=http://www.mamicode.com/json.dumps({
 92                      "jsonrpc": "2.0",
 93                      "method": "hostinterface.get",
 94                      "params": {
 95                           "output": "extend",
 96                            #"hostids": "11270",
 97                             "hostids": host_id,
 98                            #"filter":{"host":hostip},
 99 
100                                },
101                      "auth": self.user_login(),
102                         "id": 1
103                                 })
104         request = urllib2.Request(self.url,data)
105         for key in self.header:
106             request.add_header(key, self.header[key])
107 
108         try:
109             result = urllib2.urlopen(request)
110         except URLError as e:
111             if hasattr(e, reason):
112                 print We failed to reach a server.
113                 print Reason: , e.reason
114             elif hasattr(e, code):
115                 print The server could not fulfill the request.
116                 print Error code: , e.code
117         else:
118             response = json.loads(result.read())
119             #print reqponse
120             result.close()
121             #print response
122             #print response[result]
123             for host in response[result]:
124                 b=host[interfaceid]
125         return b
126 
127     def create_item(self,hostid,interfaceid,key_name,key):
128     #def create_item(self):
129         data =http://www.mamicode.com/ json.dumps({
130                            "jsonrpc": "2.0",
131                            "method": "item.create",
132                            "params":{
133                                #"name": "pingsd",
134                                "name": key_name,
135                                #"key_": "pingsd_Ip",
136                                "key_":key,
137                                #"hostid": "11270",
138                                "hostid": hostid,
139                                #"interfaceid": "1206",
140                                "interfaceid": interfaceid,
141                                 #"templateid": "11668",
142                                 "type": 0,
143                                 "value_type": 0,
144                                "date_type": 0,
145                                "delay": 60,
146                                "history": 7,
147                                "trends": 90,
148                                "status": 0,
149                                "applications": [
150                                    "18211"
151                                ],
152                            },
153                            "auth": self.user_login(),
154                            "id":1
155                         })
156         request = urllib2.Request(self.url, data)
157         for key in self.header:
158             request.add_header(key, self.header[key])
159 
160         try:
161             result = urllib2.urlopen(request)
162             response = json.loads(result.read())
163             result.close()
164             print success
165             print response
166             #for host in response[result]:
167                 #print
168         except Exception,e:
169             print  e
170     def get_application(self):
171         data=http://www.mamicode.com/json.dumps({
172             "jsonrpc": "2.0",
173              "method": "application.get",
174               "params": {
175               "output": "extend",
176               "hostids": "11270",
177               "sortfield": "name"
178                         },
179              "auth": self.user_login(),
180              "id": 1
181         })
182 
183         request = urllib2.Request(self.url,data)
184         for key in self.header:
185             request.add_header(key, self.header[key])
186 
187         try:
188             result = urllib2.urlopen(request)
189         except URLError as e:
190             if hasattr(e, reason):
191                 print We failed to reach a server.
192                 print Reason: , e.reason
193             elif hasattr(e, code):
194                 print The server could not fulfill the request.
195                 print Error code: , e.code
196         else:
197             response = json.loads(result.read())
198             #print reqponse
199             result.close()
200             print response
201             for host in response[result]:
202                 print host[applicationid]
203                 print host[name]
204     def graph_create(self,ping_id,loss_id,ping_name):
205         data =http://www.mamicode.com/ json.dumps({
206                        "jsonrpc": "2.0",
207                         "method": "graph.create",
208                        "params": {
209                         "name": ping_name,
210                         "width": 900,
211                         "height": 200,
212                        "gitems": [
213                               {
214                           "itemid": ping_id,
215                            "color": "00AA00",
216                            "sortorder": "0"
217                            },
218                         {
219                         "itemid": loss_id,
220                         "color": "3333FF",
221                          "sortorder": "1"
222                          }
223                              ]
224                         },
225                    "auth": self.user_login(),
226                   "id": 1
227                   })
228         request = urllib2.Request(self.url, data)
229         for key in self.header:
230             request.add_header(key, self.header[key])
231 
232         try:
233             result = urllib2.urlopen(request)
234             response = json.loads(result.read())
235             result.close()
236             print success
237             print response
238         except Exception,e:
239             print  e
240     def get_item_id(self,hostid):
241         data=http://www.mamicode.com/json.dumps({
242 
243                       "jsonrpc": "2.0",
244                        "method": "item.get",
245                        "params": {
246                           "output": "extend",
247                           "hostids": hostid,
248                      #"search": {
249                      #"key_": "system"
250                      # },
251                       "sortfield": "name"
252                        },
253                        "auth": self.user_login(),
254                          "id": 1,
255                         })
256 
257         request = urllib2.Request(self.url,data)
258         for key in self.header:
259             request.add_header(key, self.header[key])
260 
261         try:
262             result = urllib2.urlopen(request)
263         except URLError as e:
264             if hasattr(e, reason):
265                 print We failed to reach a server.
266                 print Reason: , e.reason
267             elif hasattr(e, code):
268                 print The server could not fulfill the request.
269                 print Error code: , e.code
270         else:
271             response = json.loads(result.read())
272             #print reqponse
273             result.close()
274             print response
275             for host in response[result]:
276                 print host[itemid],host[name]
277 
278                 #print
279 
280 
281 obj = zabbix_api()
282 #ret=obj.host_get(txgzvpc2)
283 #print ret
284 #obj.get_item_id(ret)
300 print "===================创建graph========================="
301 with open("ping_or") as f:
302     ping_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
303 with open("loss_or") as f:
304     loss_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
305 with open(file1) as f:
306     ip=[(r.rstrip("\r\n")) for r in f.readlines()]
307 for i in range(len(ping_id1)):
308     print ping_id1[i],loss_id1[i],ip[i]
309     obj.graph_create(ping_id1[i],loss_id1[i],ip[i])
310 print "=====================创建graph=============================="
311 #说明:file里面是graph的名字。ping_or,losss_or分别是itemid
312 #for key in hosfile:
313 
314 #    print key
315  #   print ip
316     #obj.graph_create(key,hosfile[key])
317 
318 #ret1=obj.host_interin(ret)
319 #print ret1
320 #obj.get_application()
321 #obj.create_item()
322 
323 ‘‘‘
324 file1=sys.argv[1]
325 file2=sys.argv[2]
326 file3=sys.argv[3]
327 
328 ip=open(file1,r).readline().strip(\r\n)
329 ping_id1=open(file2,r).readline().strip(\r\n)
330 loss_id1=open(file3,r).readline().strip(\r\n)
331 ret=obj.host_get(txgzvpc25)
332 print ret
333 ret1=obj.host_interin(ret)
334 print ret1
335 ‘‘‘
336 ‘‘‘
337 print "==============添加item======================================="
338 if __name__ == __main__:
339     obj = zabbix_api()
340     ret=obj.host_get(‘alivpx11-88)  #主机的hostname
341     print ret
342     ret1=obj.host_interin(ret)
343     print ret1
344     with open (file,rb) as f:   #file里面是key和那个名字,我这里为了方便,让他们一样了
345             for i in f.readlines():
346                 obj.create_item(ret,ret1,i.strip(\r\n),i.strip(\r\n))
347 
348 print "==============添加item======================================="
349 ‘‘‘
350 
351 
352 
353 
354 
355 
356 
357 
358 
359 
360 ‘‘‘
361 
362 
363 
364 
365 
366 
367 
368 
369 
370 
371 
372 
373 
374 
375 
376 
377 
378     def graph_create(self):
379         data =http://www.mamicode.com/ json.dumps({
380                        "jsonrpc": "2.0",
381                         "method": "graph.create",
382                        "params": {
383                         "name": "MySQL bandwidth",
384                         "width": 900,
385                         "height": 200,
386                        "gitems": [
387                               {
388                           "itemid": "22828",
389                            "color": "00AA00",
390                            "sortorder": "0"
391                            },
392                         {
393                         "itemid": "22829",
394                         "color": "3333FF",
395                          "sortorder": "1"
396                          }
397                              ]
398                         },
399                    "auth": "038e1d7b1735c6a5436ee9eae095879e",
400                   "id": 1
401                   })
402         request = urllib2.Request(self.url, data)
403         for key in self.header:
404             request.add_header(key, self.header[key])
405 
406         try:
407             result = urllib2.urlopen(request)
408             response = json.loads(result.read())
409             result.close()
410             print success
411         except Exception,e:
412             print  e
413 ‘‘‘
414 ‘‘‘
415 if __name__ == __main__:
416 
417     obj = zabbix_api()
418 #ret=obj.create_item()
419 #print ret
420     ret=obj.host_get(txgzvpc1-1)
421 print ret
422 #obj.host_interin(x.x.x.x)
423 ‘‘‘
424 ‘‘‘
425     def get_template_id(self):
426         data=http://www.mamicode.com/json.dumps({
427             "jsonrpc": "2.0",
428              "method": "template.get",
429               "params": {
430              "output": "extend",
431              "filter": {
432               "host": [
433                 "ceshitemplate",
434                       ]
435                         }
436                       },
437              "auth": self.user_login(),
438              "id": 1
439         })
440 
441         request = urllib2.Request(self.url,data)
442         for key in self.header:
443             request.add_header(key, self.header[key])
444 
445         try:
446             result = urllib2.urlopen(request)
447         except URLError as e:
448             if hasattr(e, reason):
449                 print We failed to reach a server.
450                 print Reason: , e.reason
451             elif hasattr(e, code):
452                 print The server could not fulfill the request.
453                 print Error code: , e.code
454         else:
455             response = json.loads(result.read())
456             #print reqponse
457             result.close()
458             print response
459             for host in response[result]:
460                 print host[templateid]
461 
462     def get_application(self):
463         data=http://www.mamicode.com/json.dumps({
464             "jsonrpc": "2.0",
465              "method": "application.get",
466               "params": {
467               "output": "extend",
468               "hostids": "11270",
469               "sortfield": "name"
470                         },
471              "auth": self.user_login(),
472              "id": 1
473         })
474 
475         request = urllib2.Request(self.url,data)
476         for key in self.header:
477             request.add_header(key, self.header[key])
478 
479         try:
480             result = urllib2.urlopen(request)
481         except URLError as e:
482             if hasattr(e, reason):
483                 print We failed to reach a server.
484                 print Reason: , e.reason
485             elif hasattr(e, code):
486                 print The server could not fulfill the request.
487                 print Error code: , e.code
488         else:
489             response = json.loads(result.read())
490             #print reqponse
491             result.close()
492             print response
493             for host in response[result]:
494                 print host[applicationid]
495                 print host[name]
496 ‘‘‘
497 #obj.host_interin(‘x.x.x.x)
498 #obj.get_template_id()
499 #obj.get_application()
500 
501
285 ‘‘‘
286 hosfile=dict()
287 with open("ping_or") as f:
288     ping_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
289 print ping_id1
290 
291 with open("loss_or") as f:
292     loss_id1=[(r.rstrip("\r\n")) for r in f.readlines()]
293 print loss_id1
294 for i in range(len(ping_id1)):
295     hosfile[ping_id1[i]]=loss_id1[i]
296 
297 print hosfile
298 ‘‘‘
502 50

 

zabbix利用api批量添加item,并且批量配置添加graph