zabbix批量操作

利用zabbix-api来实现zabbix的主机的批量添加,主机的查找,删除等等操作。

代码如下:

  1 #!/usr/bin/env python
  2 #-*- coding: utf-8 -*-
  3 
  4 import json
  5 import sys
  6 import urllib2
  7 import argparse
  8 
  9 from urllib2 import URLError
 10 
 11 reload(sys)
 12 sys.setdefaultencoding('utf-8')
 13 
 14 class zabbix_api:
 15     def __init__(self):
 16         #self.url
 17 
 18 
 19 
 20 
 21 
 22         #self.url = 'http://zabbix.weimob.com/api_jsonrpc.php'
 23         self.url = 'http://zb.qeeyou.cn:81/api_jsonrpc.php'
 24         self.header = {"Content-Type":"application/json"}
 25 
 26 
 27     def user_login(self):
 28         data = json.dumps({
 29                            "jsonrpc": "2.0",
 30                            "method": "user.login",
 31                            "params": {
 32                                       "user": "admin",
 33                                       "password": "zp1@663400"
 34                                       },
 35                            "id": 0
 36                            })
 37 
 38         request = urllib2.Request(self.url, data)
 39 
 40         for key in self.header:
 41             request.add_header(key, self.header[key])
 42 
 43         try:
 44             result = urllib2.urlopen(request)
 45         except URLError as e:
 46             print "33[041m 认证失败,请检查URL !33[0m",e.code
 47         except KeyError as e:
 48             print "33[041m 认证失败,请检查用户名密码 !33[0m",e
 49         else:
 50             response = json.loads(result.read())
 51             result.close()
 52             #print response['result']
 53             self.authID = response['result']
 54             return self.authID
 55 
 56     def hostid_get_hostname(self, hostId=''):
 57         data = json.dumps({
 58             "jsonrpc": "2.0",
 59             "method": "host.get",
 60             "params": {
 61                 "output": "extend",
 62                 "filter": {"hostid": hostId}
 63             },
 64             "auth": self.user_login(),
 65             "id": 1
 66         })
 67         request = urllib2.Request(self.url, data)
 68         for key in self.header:
 69             request.add_header(key, self.header[key])
 70         try:
 71             result = urllib2.urlopen(request)
 72         except URLError as e:
 73             if hasattr(e, 'reason'):
 74                 print 'We failed to reach a server.'
 75                 print 'Reason: ', e.reason
 76             elif hasattr(e, 'code'):
 77                 print 'The server could not fulfill the request.'
 78                 print 'Error code: ', e.code
 79         else:
 80             response = json.loads(result.read())
 81             #print response
 82             result.close()
 83 
 84             if not len(response['result']):
 85                 print "hostId is not exist"
 86                 return False
 87 
 88             #print "主机数量: 33[31m%s33[0m" % (len(response['result']))
 89             host_dict=dict()
 90             for host in response['result']:
 91                 status = {"0": "OK", "1": "Disabled"}
 92                 available = {"0": "Unknown", "1": "available", "2": "Unavailable"}
 93                 #if len(hostId) == 0:
 94                 #    print "HostID : %s	 HostName : %s	 Status :33[32m%s33[0m 	 Available :33[31m%s33[0m" % (
 95                 #        host['hostid'], host['name'], status[host['status']], available[host['available']])
 96                 #else:
 97                 #    print "HostID : %s	 HostName : %s	 Status :33[32m%s33[0m 	 Available :33[31m%s33[0m" % (
 98                 #        host['hostid'], host['name'], status[host['status']], available[host['available']])
 99                 host_dict['name']=host['name']
100                 host_dict['status']=status[host['status']]
101                 host_dict['available']=available[host['available']]
102                 return host_dict
103     def proxy_get(self):
104         data=json.dumps({
105             "jsonrpc": "2.0",
106             "method": "proxy.get",
107             "params": {
108             "output": "extend",
109              "selectInterfaces": "extend",
110              "selectHosts": "extend"
111                },
112            "auth": self.user_login(),
113             "id": 1
114 })
115         request = urllib2.Request(self.url, data)
116         for key in self.header:
117             request.add_header(key, self.header[key])
118         try:
119             result = urllib2.urlopen(request)
120         except  URLError as e:
121             print "Error as ", e
122         else:
123             response = json.loads(result.read())
124             result.close()
125         #print response
126             for i in range(len(response['result'])):
127                 for j in range(len(response['result'][i]['hosts'])):
128                     r=response['result'][i]['hosts'][j]
129             #print r
130                     print " proxy_host: %s	 proxy_ID: %s 	host: %s	 hostid: %s" %(response['result'][i]['host'],response['result'][i]['proxyid'],r['host'],r['hostid'])
131     def hostid_get_hostip(self, hostId=''):
132         data = json.dumps({
133             "jsonrpc": "2.0",
134             "method": "hostinterface.get",
135             "params": {
136                 "output": "extend",
137                 "filter": {"hostid": hostId}
138             },
139             "auth": self.user_login(),
140             "id": 1
141         })
142         request = urllib2.Request(self.url, data)
143         for key in self.header:
144             request.add_header(key, self.header[key])
145         try:
146             result = urllib2.urlopen(request)
147         except URLError as e:
148             if hasattr(e, 'reason'):
149                 print 'We failed to reach a server.'
150                 print 'Reason: ', e.reason
151             elif hasattr(e, 'code'):
152                 print 'The server could not fulfill the request.'
153                 print 'Error code: ', e.code
154         else:
155             response = json.loads(result.read())
156             # print response
157             result.close()
158 
159             if not len(response['result']):
160                 print "33[041m hostid 33[0m is not exist"
161                 return False
162 
163             #print "主机数量: 33[31m%s33[0m" % (len(response['result']))
164             for hostip in response['result']:
165                 #print hostip
166                 #if len(hostip) == 0:
167                 #    print "HostID : %s	 HostIp : %s 	 Port : %s " % (hostip['hostid'], hostip['ip'], hostip['port'])
168                 #else:
169                 #    print "HostID : %s	 HostIp :33[32m%s33[0m 	 Port :33[31m%s33[0m" % (
170                 #        hostip['hostid'], hostip['ip'], hostip['port'])
171                 return hostip['ip']
172 
173     def host_get(self,hostName=''):
174         data=json.dumps({
175                 "jsonrpc": "2.0",
176                 "method": "host.get",
177                 "params": {
178                           "output": "extend",
179                           #"filter":{"host":""}
180                           "filter":{"host":hostName}
181                           },
182                 "auth": self.user_login(),
183                 "id": 1
184                 })
185         request = urllib2.Request(self.url,data)
186         for key in self.header:
187             request.add_header(key, self.header[key])
188 
189         try:
190             result = urllib2.urlopen(request)
191         except URLError as e:
192             if hasattr(e, 'reason'):
193                 print 'We failed to reach a server.'
194                 print 'Reason: ', e.reason
195             elif hasattr(e, 'code'):
196                 print 'The server could not fulfill the request.'
197                 print 'Error code: ', e.code
198         else:
199             response = json.loads(result.read())
200             #print reqponse
201             result.close()
202 
203             if not len(response['result']):
204                 print "33[041m %s 33[0m is not exist" % hostName
205                 return False
206 
207             print "主机数量: 33[31m%s33[0m"%(len(response['result']))
208             for host in response['result']:
209                 status={"0":"OK","1":"Disabled"}
210                 available={"0":"Unknown","1":"available","2":"Unavailable"}
211                 #print host
212                 if len(hostName)==0:
213                     print "HostID : %s	 HostName : %s	 HostIp : %s	 Status :%s 	 Available :%s"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])
214                 else:
215                     print "HostID : %s	 HostName : %s	 HostIp : %s	 Status :33[32m%s33[0m 	 Available :33[31m%s33[0m"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])
216                     return host['hostid']
217 
218     def hostip_get(self, hostIp=''):
219         data = json.dumps({
220             "jsonrpc": "2.0",
221             "method": "hostinterface.get",
222             "params": {
223                 "output": "extend",
224                 "filter": {"ip": hostIp}
225             },
226             "auth": self.user_login(),
227             "id": 1
228         })
229         request = urllib2.Request(self.url, data)
230         for key in self.header:
231             request.add_header(key, self.header[key])
232 
233         try:
234             result = urllib2.urlopen(request)
235         except URLError as e:
236             if hasattr(e, 'reason'):
237                 print 'We failed to reach a server.'
238                 print 'Reason: ', e.reason
239             elif hasattr(e, 'code'):
240                 print 'The server could not fulfill the request.'
241                 print 'Error code: ', e.code
242         else:
243             response = json.loads(result.read())
244             # print response
245             result.close()
246 
247             if not len(response['result']):
248                 print "33[041m hostip 33[0m is not exist"
249                 return False
250 
251             print "主机数量: 33[31m%s33[0m" % (len(response['result']))
252             for hostip in response['result']:
253                 host = self.hostid_get_hostname(hostip['hostid'])
254                 if len(hostip) == 0:
255                     print "HostID : %s	 HostName : %s	 HostIp : %s	 Status :33[32m%s33[0m 	 Available :33[31m%s33[0m"%(hostip['hostid'],host['name'],hostip['ip'],host['status'],host['available'])
256                 else:
257                     print "HostID : %s	 HostName : %s	 HostIp : %s	 Status :33[32m%s33[0m 	 Available :33[31m%s33[0m"%(hostip['hostid'],host['name'],hostip['ip'],host['status'],host['available'])
258                     return hostip['hostid']
259 
260     def hostgroup_get(self, hostgroupName=''):
261         data = json.dumps({
262                            "jsonrpc":"2.0",
263                            "method":"hostgroup.get",
264                            "params":{
265                                      "output": "extend",
266                                      "filter": {
267                                                 "name": hostgroupName
268                                                 }
269                                      },
270                            "auth":self.user_login(),
271                            "id":1,
272                            })
273 
274         request = urllib2.Request(self.url,data)
275         for key in self.header:
276             request.add_header(key, self.header[key])
277 
278         try:
279             result = urllib2.urlopen(request)
280         except URLError as e:
281             print "Error as ", e
282         else:
283             # result.read()
284             response = json.loads(result.read())
285             result.close()
286             #print response()
287             if not len(response['result']):
288                 print "33[041m %s 33[0m is not exist" % hostgroupName
289                 return False
290 
291             for group in response['result']:
292                 if  len(hostgroupName)==0:
293                     print "hostgroup:  33[31m%s33[0m 	groupid : %s" %(group['name'],group['groupid'])
294                 else:
295                     print "hostgroup:  33[31m%s33[0m	groupid : %s" %(group['name'],group['groupid'])
296                     self.hostgroupID = group['groupid']
297             return group['groupid']
298 
299     def template_get(self,templateName=''):
300         data = json.dumps({
301                            "jsonrpc":"2.0",
302                            "method": "template.get",
303                            "params": {
304                                       "output": "extend",
305                                       "filter": {
306                                                  "name":templateName
307                                                  }
308                                       },
309                            "auth":self.user_login(),
310                            "id":1,
311                            })
312 
313         request = urllib2.Request(self.url, data)
314         for key in self.header:
315             request.add_header(key, self.header[key])
316 
317         try:
318             result = urllib2.urlopen(request)
319         except URLError as e:
320             print "Error as ", e
321         else:
322             response = json.loads(result.read())
323             result.close()
324             #print response
325             if not len(response['result']):
326                 print "33[041m %s 33[0m is not exist" % templateName
327                 return False
328 
329             for template in response['result']:
330                 if len(templateName)==0:
331                     print "template : %s 	 id : %s" % (template['name'], template['templateid'])
332                 else:
333                     self.templateID = response['result'][0]['templateid']
334                     print "Template Name :%s"%templateName
335                     return response['result'][0]['templateid']
336 
337     def hostgroup_create(self,hostgroupName):
338         if self.hostgroup_get(hostgroupName):
339             print "hostgroup  33[42m%s33[0m is exist !" % hostgroupName
340             sys.exit(1)
341 
342         data = json.dumps({
343                           "jsonrpc": "2.0",
344                           "method": "hostgroup.create",
345                           "params": {
346                           "name": hostgroupName
347                           },
348                           "auth": self.user_login(),
349                           "id": 1
350                           })
351         request=urllib2.Request(self.url,data)
352 
353         for key in self.header:
354             request.add_header(key, self.header[key])
355 
356         try:
357             result = urllib2.urlopen(request)
358         except URLError as e:
359             print "Error as ", e
360         else:
361             response = json.loads(result.read())
362             result.close()
363             print "添加主机组:%s  hostgroupID : %s"%(hostgroupName,self.hostgroup_get(hostgroupName))
364 #添加主机到特定的组特定的模板
365     def host_create(self, hostIp, hostgroupName, templateName, hostName):
366         if self.host_get(hostName) or self.hostip_get(hostIp):
367             print "该主机已经添加!"
368             sys.exit(1)
369 
370         group_list=[]
371         template_list=[]
372         for i in hostgroupName.split(','):
373             var = {}
374             var['groupid'] = self.hostgroup_get(i)
375             group_list.append(var)
376         for i in templateName.split(','):
377             var={}
378             var['templateid']=self.template_get(i)
379             template_list.append(var)
380 
381         data = json.dumps({
382                            "jsonrpc":"2.0",
383                            "method":"host.create",
384                            "params":{
385                                      "host": hostName,
386                                      "interfaces": [
387                                      {
388                                      "type": 1,
389                                      "main": 1,
390                                      "useip": 1,
391                                      "ip": hostIp,
392                                      "dns": "",
393                                      "port": "10050"
394                                       }
395                                      ],
396                                    "groups": group_list,
397                                    "templates": template_list,
398                                      },
399                            "auth": self.user_login(),
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 "add host : %s id :%s" % (hostIp, hostName)
411         except URLError as e:
412             print "Error as ", e
413         except KeyError as e:
414             print "33[041m 主机添加有误,请检查模板正确性或主机是否添加重复 !33[0m",e
415             print response
416 
417     def host_disable(self,hostip):
418         data=json.dumps({
419                 "jsonrpc": "2.0",
420                 "method": "host.update",
421                 "params": {
422                 "hostid": self.host_get(hostip),
423                 "status": 1
424                 },
425                 "auth": self.user_login(),
426                 "id": 1
427                 })
428         request = urllib2.Request(self.url,data)
429         #opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(TerminalPassword()))
430         for key in self.header:
431                 request.add_header(key, self.header[key])
432         try:
433             result = urllib2.urlopen(request)
434             #result = opener.open(request)
435         except URLError as e:
436             print "Error as ", e
437         else:
438             response = json.loads(result.read())
439             result.close()
440             print '------------主机现在状态------------'
441             print self.host_get(hostip)
442 
443     def host_enable(self,hostip):
444         data=json.dumps({
445             "jsonrpc": "2.0",
446             "method": "host.update",
447             "params": {
448             "hostid": self.host_get(hostip),
449             "status": 0
450             },
451             "auth": self.user_login(),
452             "id": 1
453             })
454         request = urllib2.Request(self.url,data)
455         for key in self.header:
456             request.add_header(key, self.header[key])
457         try:
458             result = urllib2.urlopen(request)
459             #result = opener.open(request)
460         except URLError as e:
461             print "Error as ", e
462         else:
463             response = json.loads(result.read())
464             result.close()
465             print '------------主机现在状态------------'
466             print self.host_get(hostip)
467 
468     def host_delete(self,hostNames):
469         hostid_list=[]
470         for hostName in hostNames.split(','):
471             hostid = self.host_get(hostName=hostName)
472             if not hostid:
473                 print "主机 33[041m %s33[0m  删除失败 !" % hostName
474                 sys.exit()
475             hostid_list.append(hostid)
476 
477         data=json.dumps({
478                 "jsonrpc": "2.0",
479                 "method": "host.delete",
480                 "params": hostid_list,
481                 "auth": self.user_login(),
482                 "id": 1
483                 })
484 
485         request = urllib2.Request(self.url,data)
486         for key in self.header:
487             request.add_header(key, self.header[key])
488 
489         try:
490             result = urllib2.urlopen(request)
491             result.close()
492             print "主机 33[041m %s33[0m  已经删除 !" % hostName
493         except Exception,e:
494             print  e
495 
496 if __name__ == "__main__":
497     zabbix=zabbix_api()
498     parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
499     parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
500     parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
501     parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
502     parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
503     parser.add_argument('-C','--add-host',dest='addhost',nargs=4,metavar=('192.168.2.1', 'groupname', 'Template01,Template02', 'hostName'),help='添加主机,多个主机组或模板使用逗号')
504     parser.add_argument('-d','--disable',dest='disablehost',nargs='+',metavar=('sh-aa-01'),help='禁用主机,填写主机名,多个主机名之间用逗号')
505     parser.add_argument('-e','--enable',dest='enablehost',nargs=1,metavar=('sh-aa-01'),help='开启主机')
506     parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('sh-aa-01'),help='删除主机,多个主机之间用逗号')
507     parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
508 
509     if len(sys.argv) == 1:
510         #print parser.print_help()
511         #print zabbix.host_get(hostName='bbb')
512         #print zabbix.hostip_get(hostIp='127.0.0.1')
513         #print zabbix.hostid_get_hostname(hostId='10108')
514         #print zabbix.hostid_get_hostid(hostId='10105')
515         #print zabbix.hostgroup_get(hostgroupName='Linux servers')
516         #print zabbix.hostgroup_get(hostgroupName='aaa')
517         # ...
518         print zabbix.host_delete('hz-aaa-02')
519     else:
520         args = parser.parse_args()
521         if args.listhost != 'host':
522             if args.listhost:
523                 zabbix.host_get(args.listhost)
524             else:
525                 zabbix.host_get()
526         if args.listgroup != 'group':
527             if args.listgroup:
528                 zabbix.hostgroup_get(args.listgroup)
529             else:
530                 zabbix.hostgroup_get()
531         if args.listtemp != 'template':
532             if args.listtemp:
533                 zabbix.template_get(args.listtemp)
534             else:
535                 zabbix.template_get()
536         if args.addgroup:
537             zabbix.hostgroup_create(args.addgroup[0])
538         if args.addhost:
539             zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2], args.addhost[3])
540         if args.disablehost:
541             zabbix.host_disable(args.disablehost)
542         if args.deletehost:
543             zabbix.host_delete(args.deletehost[0])
zbx_tool.py
 1 #!/usr/bin/env python
 2 #-*- coding: utf-8 -*-
 3 
 4 #!/usr/bin/env python
 5 #-*- coding: utf-8 -*-
 6 
 7 import os
 8 import sys
 9 import argparse
10 
11 # 导入zabbix_tool.py的zabbix_api类
12 from zbx_tool import zabbix_api
13 import subprocess
14 hostfile=dict()
15 reload(sys)
16 sys.setdefaultencoding('utf-8')
17 
18 host_file = 'target'
19 #base_templates = ""
20 cmd = 'python zbx_tool.py'
21 
22 # 实例化zabbix_api
23 zabbix=zabbix_api()
24 def open_file():
25     with open ('/etc/ansible/zhangdianke/zabbix/Tengxunode.txt','rb') as f:
26         for ip in f.readlines():
27             getHostName(ip.strip())
28 def getHostName(ip):
29     a="ansible "
30     b=ip
31     c=" -i /etc/ansible/zhangdianke/zabbix/tengxunode.txt -m shell -a 'cat /etc/myshell/new_baseinfo |grep hostname'|awk -F ' = ' {'print $2'}|sed -n 2p"
32     command=a+b+c
33     subp=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE)
34                                 #with open("gethost.txt",'a+')as f:
35                                     #hostfile=dict()
36     for line in subp.stdout.readlines():
37         hostfile[line.rstrip('
')]=ip
38 def create_hosts():
39     groups = raw_input("Please Input Group Name: ")
40     add_templates = raw_input("Please Input Template Name: ")
41     templates = add_templates
42     cmd1 = cmd + ' -A ' + groups   #python zbx_tool.py -A groupname
43     os.system(cmd1)
44 
45 
46     for key in hostfile:
47         cmd2 = cmd + ' --add-host ' + hostfile[key] + ' ' + groups + ' ' +templates + ' ' + key
48         os.system(cmd2)
49 
50 def get_hosts():
51    with open(host_file) as fb:
52        [zabbix.host_get(line.strip()) for line in fb]
53 def get_hostip():
54     with open(host_file) as fb:
55        [zabbix.hostip_get(line.strip()) for line in fb]
56 def delete_hosts():
57    with open(host_file) as fb:
58        [zabbix.host_delete(line.strip()) for line in fb]
59 
60 def enable_hosts():
61    with open(host_file) as fb:
62        [zabbix.host_enablee(line.strip()) for line in fb]
63 
64 def disable_hosts():
65    with open(host_file) as fb:
66        [zabbix.host_disable(line.strip()) for line in fb]
67 def proxy_get_hosts():
68     zabbix.proxy_get()
69 
70 if __name__ == "__main__":
71     #with open ('/etc/ansible/zhangdianke/zabbix/Tengxunode.txt','rb') as f:
72     #    for ip in f.readlines():
73                                 #i=str(i)
74     #        print ip
75     #        getHostName(ip.strip())
76     if len(sys.argv) == 1 or sys.argv[1] == '-h':
77         print "you need a argv,like:"
78         print """
79         python zbx_cli.py -A #批量添加主机,请确保每台主机22端口开放
80         python zbx_cli.py -B #得到所有代理的主机信息
81         python zbx_cli.py -C #批量查询主机,确保target文件格式正确
82         python zbx_cli.py -D #批量删除主机,确保target文件格式正确
83         python zbx_cli.py -e #批量开启主机,确保target文件格式正确
84         python zbx_cli.py -d #批量禁止主机,确保target文件格式正确
85         """
86     else:
87         if sys.argv[1] == '-A':
88             open_file()
89             create_hosts()
90         elif sys.argv[1] == '-B':
91             proxy_get_hosts()
92         elif sys.argv[1] == '-C':
93             get_hosts()
94         elif sys.argv[1] == '-D':
95             delete_hosts()
96         elif sys.argv[1] == '-e':
97             disable_hosts()
98         elif sys.argv[1] == '-d':
99             enable_hosts()
zbx_cli

 求某个组的总流量grpsum["VIP-XM-B","net.if.in[eth0]",last,0]

原文地址:https://www.cnblogs.com/Dicky-Zhang/p/6135247.html