众所周知,zabbix是一款强大的分布式监控系统,集各家所长于一体,得到了广大SA的认可。其强大的管理界面也极其方便,但是美中不足的是,如果同时有大批量(50台+)的服务器需要添加监控时,这时,其图形界面反而显得有些臃肿了,好在zabbix 提供了一套强大的API管理接口,我们可以使用它快速地添加成千上万台服务器。

根据日常工作中常用到zabbix的功能,整理以下功能

1.基于zabbix 官方 api
2.提供查询单个或者多个host、hostgroup、template功能
3.提供增加host,hostgroup功能
4.提供disable host功能
5.增加删除host 功能

代码如下

  1#!/usr/bin/python
  2#coding:utf-8
  3import json
  4import urllib2
  5from urllib2 import URLError
  6import sys,argparse
  7class zabbix_api:
  8    def __init__(self):
  9        self.url = 'http://localhost/api_jsonrpc.php' #修改URL
 10        self.header = {"Content-Type":"application/json"}
 11    def user_login(self):
 12        data = json.dumps({
 13                           "jsonrpc": "2.0",
 14                           "method": "user.login",
 15                           "params": {
 16                                      "user": "Admin", #修改用户名
 17                                      "password": "zabbix" #修改密码
 18                                      },
 19                           "id": 0
 20                           })
 21        request = urllib2.Request(self.url, data)
 22        for key in self.header:
 23            request.add_header(key, self.header[key])
 24        try:
 25            result = urllib2.urlopen(request)
 26        except URLError as e:
 27            print "33[041m 用户认证失败,请检查 !33[0m", e.code
 28        else:
 29            response = json.loads(result.read())
 30            result.close()
 31            #print response['result']
 32            self.authID = response['result']
 33            return self.authID
 34    def host_get(self,hostName=''):
 35        data=json.dumps({
 36                "jsonrpc": "2.0",
 37                "method": "host.get",
 38                "params": {
 39                          "output": "extend",
 40                          "filter":{"host":hostName}
 41                          },
 42                "auth": self.user_login(),
 43                "id": 1
 44                })
 45        request = urllib2.Request(self.url,data)
 46        for key in self.header:
 47            request.add_header(key, self.header[key])
 48        try:
 49            result = urllib2.urlopen(request)
 50        except URLError as e:
 51            if hasattr(e, 'reason'):
 52                print 'We failed to reach a server.'
 53                print 'Reason: ', e.reason
 54            elif hasattr(e, 'code'):
 55                print 'The server could not fulfill the request.'
 56                print 'Error code: ', e.code
 57        else:
 58            response = json.loads(result.read())
 59            #print response
 60            result.close()
 61            print "主机数量: 33[31m%s33[0m"%(len(response['result']))
 62            for host in response['result']:
 63                    status={"0":"OK","1":"Disabled"}
 64            available={"0":"Unknown","1":"available","2":"Unavailable"}
 65            #print host
 66            if len(hostName)==0:
 67                        print "HostID : %st HostName : %st Status :33[32m%s33[0m t Available :33[31m%s33[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
 68            else:
 69                        print "HostID : %st HostName : %st Status :33[32m%s33[0m t Available :33[31m%s33[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
 70                return host['hostid']
 71    def hostgroup_get(self, hostgroupName=''):
 72        data = json.dumps({
 73                           "jsonrpc":"2.0",
 74                           "method":"hostgroup.get",
 75                           "params":{
 76                                     "output": "extend",
 77                                     "filter": {
 78                                                "name": hostgroupName
 79                                                }
 80                                     },
 81                           "auth":self.user_login(),
 82                           "id":1,
 83                           })
 84        request = urllib2.Request(self.url,data)
 85        for key in self.header:
 86            request.add_header(key, self.header[key])
 87        try:
 88            result = urllib2.urlopen(request)
 89        except URLError as e:
 90            print "Error as ", e
 91        else:
 92            #print result.read()
 93            response = json.loads(result.read())
 94            result.close()
 95            #print response()
 96            for group in response['result']:
 97                if  len(hostgroupName)==0:
 98                    print "hostgroup:  33[31m%s33[0m tgroupid : %s" %(group['name'],group['groupid'])
 99            else:
100                    print "hostgroup:  33[31m%s33[0mtgroupid : %s" %(group['name'],group['groupid'])
101                    self.hostgroupID = group['groupid']
102                    return group['groupid']
103    def template_get(self,templateName=''):
104        data = json.dumps({
105                           "jsonrpc":"2.0",
106                           "method": "template.get",
107                           "params": {
108                                      "output": "extend",
109                                      "filter": {
110                                                 "name":templateName
111                                                 }
112                                      },
113                           "auth":self.user_login(),
114                           "id":1,
115                           })
116        request = urllib2.Request(self.url, data)
117        for key in self.header:
118            request.add_header(key, self.header[key])
119        try:
120            result = urllib2.urlopen(request)
121        except URLError as e:
122            print "Error as ", e
123        else:
124            response = json.loads(result.read())
125            result.close()
126            #print response
127            for template in response['result']:
128                if len(templateName)==0:
129                    print "template : 33[31m%s33[0mt  id : %s" % (template['name'], template['templateid'])
130                else:
131                    self.templateID = response['result'][0]['templateid']
132            print "Template Name :  33[31m%s33[0m "%templateName
133                    return response['result'][0]['templateid']
134    def hostgroup_create(self,hostgroupName):
135        if self.hostgroup_get(hostgroupName):
136            print "hostgroup  33[42m%s33[0m is exist !"%hostgroupName
137            sys.exit(1)
138        data = json.dumps({
139                          "jsonrpc": "2.0",
140                          "method": "hostgroup.create",
141                          "params": {
142                          "name": hostgroupName
143                          },
144                          "auth": self.user_login(),
145                          "id": 1
146                          })
147        request=urllib2.Request(self.url,data)
148        for key in self.header:
149            request.add_header(key, self.header[key])
150        try:
151            result = urllib2.urlopen(request)
152        except URLError as e:
153            print "Error as ", e
154        else:
155            response = json.loads(result.read())
156            result.close()
157            print "33[042m 添加主机组:%s33[0m  hostgroupID : %s"%(hostgroupName,response['result']['groupids'])
158    def host_create(self, hostip, hostgroupName, templateName):
159        if self.host_get(hostip):
160        print "33[041m该主机已经添加!33[0m"
161        sys.exit(1)
162        group_list=[]
163        template_list=[]
164        for i in hostgroupName.split(','):
165            var = {}
166            var['groupid'] = self.hostgroup_get(i)
167            group_list.append(var)
168        for i in templateName.split(','):
169            var={}
170            var['templateid']=self.template_get(i)
171            template_list.append(var)
172        data = json.dumps({
173                           "jsonrpc":"2.0",
174                           "method":"host.create",
175                           "params":{
176                                     "host": hostip,
177                                     "interfaces": [
178                                     {
179                                     "type": 1,
180                                     "main": 1,
181                                     "useip": 1,
182                                     "ip": hostip,
183                                     "dns": "",
184                                     "port": "10050"
185                                      }
186                                     ],
187                                   "groups": group_list,
188                                   "templates": template_list,
189                                     },
190                           "auth": self.user_login(),
191                           "id":1
192        })
193        request = urllib2.Request(self.url, data)
194        for key in self.header:
195            request.add_header(key, self.header[key])
196        try:
197            result = urllib2.urlopen(request)
198        except URLError as e:
199            print "Error as ", e
200        else:
201            response = json.loads(result.read())
202            result.close()
203            print "添加主机 : 33[42m%s31[0m tid :33[31m%s33[0m" % (hostip, response['result']['hostids'])
204    def host_disable(self,hostip):
205        data=json.dumps({
206        "jsonrpc": "2.0",
207        "method": "host.update",
208        "params": {
209        "hostid": self.host_get(hostip),
210        "status": 1
211        },
212        "auth": self.user_login(),
213        "id": 1
214        })
215        request = urllib2.Request(self.url,data)
216            for key in self.header:
217                request.add_header(key, self.header[key])
218            try:
219                result = urllib2.urlopen(request)
220            except URLError as e:
221                print "Error as ", e
222            else:
223                response = json.loads(result.read())
224                result.close()
225                print '----主机现在状态------------'
226            print self.host_get(hostip)
227    def host_delete(self,hostid):
228        hostid_list=[]
229        #print type(hostid)
230        for i in hostid.split(','):
231            var = {}
232            var['hostid'] = self.host_get(i)
233            hostid_list.append(var)
234        data=json.dumps({
235                "jsonrpc": "2.0",
236                "method": "host.delete",
237                "params": hostid_list,
238                "auth": self.user_login(),
239                "id": 1
240                })
241        request = urllib2.Request(self.url,data)
242        for key in self.header:
243            request.add_header(key, self.header[key])
244        try:
245            result = urllib2.urlopen(request)
246        except Exception,e:
247            print  e
248        else:
249            result.close()
250            print "主机 33[041m %s33[0m  已经删除 !"%hostid
251if __name__ == "__main__":
252    zabbix=zabbix_api()
253    parser=argparse.ArgumentParser(description='zabbix  api ',usage='%(prog)s [options]')
254    parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
255    parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
256    parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
257    parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
258    parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号')
259    parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机')
260    parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号')
261    parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
262    if len(sys.argv)==1:
263        print parser.print_help()
264    else:
265        args=parser.parse_args()
266        if args.listhost != 'host' :
267            if args.listhost:
268                zabbix.host_get(args.listhost)
269            else:
270                zabbix.host_get()
271        if args.listgroup !='group':
272            if args.listgroup:
273                zabbix.hostgroup_get(args.listgroup)
274            else:
275                zabbix.hostgroup_get()
276        if args.listtemp != 'template':
277            if args.listtemp:
278                zabbix.template_get(args.listtemp)
279            else:
280                zabbix.template_get()
281        if args.addgroup:
282            zabbix.hostgroup_create(args.addgroup[0])
283        if args.addhost:
284            zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
285        if args.disablehost:
286            zabbix.host_disable(args.disablehost)
287        if args.deletehost:
288            zabbix.host_delete(args.deletehost[0])

点此下载上面的代码

用法如下

 1直接执行 python zabbix_api.py
 2    usage: zabbix_api.py [options]
 3    zabbix api
 4    optional arguments:
 5      -h, --help            show this help message and exit
 6      -H [LISTHOST], --host [LISTHOST]
 7                            查询主机
 8      -G [LISTGROUP], --group [LISTGROUP]
 9                            查询主机组
10      -T [LISTTEMP], --template [LISTTEMP]
11                            查询模板信息
12      -A ADDGROUP, --add-group ADDGROUP
13                            添加主机组
14      -C 192.168.2.1 test01,test02 Template01,Template02, --add-host 192.168.2.1 test01,test02 Template01,Template02
15                            添加主机,多个主机组或模板使用分号
16      -d 192.168.2.1, --disable 192.168.2.1
17                            禁用主机
18      -D 192.168.2.1 [192.168.2.1 ...], --delete 192.168.2.1 [192.168.2.1 ...]
19                            删除主机,多个主机之间用分号
20      -v, --version         show program's version number and exit

示例

 1#!/usr/bin/python
 2#新增帮助信息,可直接执行脚本
 3zabbix=zabbix_api()
 4#获取所有主机列表
 5 zabbix.host_get()
 6#查询单个主机列表
 7 zabbix.host_get('192.168.2.1')
 8#获取所有主机组列表
 9 zabbix.hostgroup_get()
10#查询单个主机组列表
11 zabbix.hostgroup_get('test01')
12#获取所有模板列表
13 zabbix.template_get()
14#查询单个模板信息
15 zabbix.template_get('Template OS Linux')
16#添加一个主机组
17zabbix.hostgroup_create('test01')
18#添加一个主机,支持将主机添加进多个组,多个模板,多个组、模板之间用逗号隔开,如果添加的组不存在,新创建组
19zabbix.host_create('192.168.2.1', 'test01', 'Template OS Linux')
20zabbix.host_create('192.168.2.1', 'Linux servers,test01 ', 'Template OS Linux,Template App MySQL')
21#禁用一个主机
22 zabbix.host_disable('192.168.2.1')
23#删除host,支持删除多个,之间用逗号
24zabbix.host_delete('192.168.2.1,192.168.2.2')

注:以上代码摘自互联网,个人感觉还是有点糙,主要同未实现增加主机别名和IP对应的功能。这里记下,以后在此基础上再做些优化。