众所周知,zabbix是一款强大的分布式监控系统,集各家所长于一体,得到了广大SA的认可。其强大的管理界面也极其方便,但是美中不足的是,如果同时有大批量(50台+)的服务器需要添加监控时,这时,其图形界面反而显得有些臃肿了,好在zabbix提供了一套强大的API管理接口,我们可以使用它快速地添加或删除成千上万台服务器了。
下面的流程图代表了Zabbix API 工作的典型工作流。验证(方法user.login)是获取验证ID的强制步骤。这个ID又允许我们调用API提供的任何权限允许的方法来进行操作。在之前的例子中没有提到user.logout方法,这也是一次验证ID能够重复使用的原因所在。使用user.logout方法后将会使验证ID失效,后面的操作将不能再使用此ID。
1. 首先获取所有模板及ID
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 |
#!/usr/bin/python #coding:utf-8 import json import urllib2 from urllib2 import URLError import sys,argparse class zabbix_api: def __init__(self): self.url = 'http://10.0.8.8/api_jsonrpc.php' self.header = {"Content-Type":"application/json"} def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "pengdongwen", #修改用户名 "password": "pengdongwen" #修改密码 }, "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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code else: response = json.loads(result.read()) result.close() #print response['result'] self.authID = response['result'] return self.authID def template_get(self,templateName=''): data = json.dumps({ "jsonrpc":"2.0", "method": "template.get", "params": { "output": "extend", "filter": { "name":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() #print response for template in response['result']: if len(templateName)==0: print "template : \033[31m%s\033[0m\t id : %s" % (template['name'], template['templateid']) else: self.templateID = response['result'][0]['templateid'] print "Template Name : \033[31m%s\033[0m "%templateName return response['result'][0]['templateid'] if __name__ == "__main__": zabbix=zabbix_api() zabbix_api().template_get() |
2. 根据模板ID获取某个模板关联的主机ID
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 |
#!/usr/bin/python #coding:utf-8 import json import urllib2 from urllib2 import URLError import sys,argparse class zabbix_api: def __init__(self): self.url = 'http://10.0.8.8/api_jsonrpc.php' self.header = {"Content-Type":"application/json"} def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "pengdongwen", #修改用户名 "password": "pengdongwen" #修改密码 }, "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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code else: response = json.loads(result.read()) result.close() self.authID = response['result'] return self.authID def host_get(self): data=json.dumps({ "jsonrpc": "2.0", "method": "host.get", "params": { "output": ["hostid","name"], "templateids":["10105"] }, "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()) #print response for host in response['result']: print "HostID : %s\t HostName : %s\t"%(host['hostid'],host['name']) result.close() #print "主机数量: \033[31m%s\033[0m"%(len(response['result'])) if __name__ == "__main__": zabbix=zabbix_api() zabbix.host_get() |
3. 根据主机ID获取主机IP地址
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 |
#!/usr/bin/python #coding:utf-8 import json import urllib2 from urllib2 import URLError import sys,argparse class zabbix_api: def __init__(self): self.url = 'http://10.0.8.8/api_jsonrpc.php' self.header = {"Content-Type":"application/json"} def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "pengdongwen", #修改用户名 "password": "pengdongwen" #修改密码 }, "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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code else: response = json.loads(result.read()) result.close() self.authID = response['result'] return self.authID def host_ip(self): data=json.dumps({ "jsonrpc": "2.0", "method": "hostinterface.get", "params": { "output": ["hostid","ip"], "hostids": ["10031"] }, "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()) #print response for host in response['result']: print "HostID: %s\t IP: %s\t"%(host['hostid'],host['ip']) result.close() print "主机数量: \033[31m%s\033[0m"%(len(response['result'])) if __name__ == "__main__": zabbix=zabbix_api() zabbix.host_ip() |
4. 获取触发器及事件
首先要搞清楚zabbix中事件的概念,当一个触发器被触发时就会产生一个事件,进而可能做各种报警。一个触发器会产生多个事件。
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 |
#!/usr/bin/python # coding:utf-8 import json import requests from requests import exceptions import urllib2 from urllib2 import URLError import sys, argparse class zabbix_api: def __init__(self): self.url = 'http://zabbix/api_jsonrpc.ph' self.header = {"Content-Type": "application/json"} def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "pdw", # 修改用户名 "password": "pdw" # 修改密码 }, "id": 0 }) request = requests.get(self.url, headers=self.header, data=data) response = json.loads(request.text) self.authID = response['result'] return self.authID def trigger_get(self): data = json.dumps({ "jsonrpc": "2.0", "method": "trigger.get", "params": { "output": [ "triggerid", "description", "priority", "withUnacknowledgedEvents" ], "filter": { "value": 1 }, "sortfield": "priority", "sortorder": "DESC", "min_severity": 1, "skipDependent": 1, "monitored": 1, "active": 1, "expandDescription": 1, "withUnacknowledgedEvents": 0, "selectHosts": ['host'], "selectGroups": ['name'], "only_true": 1 }, "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() print "Total: %s" % len(response['result']) for trigger in response['result']: print trigger def event_get(self, triggerid): data = json.dumps({ "jsonrpc": "2.0", "method": "event.get", "params": { "output": "extend", "select_acknowledges": "extend", "objectids": triggerid, "sortfield": ["clock", "eventid"], "sortorder": "DESC" }, "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() for event in response['result']: print event def event_ack(self, eventid): data = json.dumps({ "jsonrpc": "2.0", "method": "event.acknowledge", "params": { "eventids": eventid, "message": "ok", "action": 1 }, "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() print response if __name__ == "__main__": # 实例化zabbix_api类 zabbix = zabbix_api() # 获取trigger zabbix.trigger_get() # 根据trigger获取eventid #zabbix.event_get(26066) # 根据eventid确认事件 #zabbix.event_ack(7352182) |
当获取到这个事件后,也可以对这个事件进行ack确认操作。
4. 多功能API
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 348 |
#!/usr/bin/python #coding:utf-8 import json import urllib2 from urllib2 import URLError import sys,argparse class zabbix_api: def __init__(self): self.url = 'http://nh.monitor.ejuops.com/api_jsonrpc.php' self.header = {"Content-Type":"application/json"} def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "pengdongwen", #修改用户名 "password": "pengdongwen@eju" #修改密码 }, "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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code else: response = json.loads(result.read()) result.close() #print response['result'] self.authID = response['result'] return self.authID def host_get(self,hostName=''): data=json.dumps({ "jsonrpc": "2.0", "method": "host.get", "params": { "output": "extend", "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()) #print response result.close() print "主机数量: \033[31m%s\033[0m"%(len(response['result'])) for host in response['result']: status={"0":"OK","1":"Disabled"} available={"0":"Unknown","1":"available","2":"Unavailable"} #print host if len(hostName)==0: print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']]) else: print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']]) return host['hostid'] 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: #print result.read() response = json.loads(result.read()) result.close() #print response() for group in response['result']: if len(hostgroupName)==0: print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid']) else: print "hostgroup: \033[31m%s\033[0m\tgroupid : %s" %(group['name'],group['groupid']) self.hostgroupID = group['groupid'] return group['groupid'] def template_get(self,templateName=''): data = json.dumps({ "jsonrpc":"2.0", "method": "template.get", "params": { "output": "extend", "filter": { "name":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() #print response for template in response['result']: if len(templateName)==0: print "template : \033[31m%s\033[0m\t id : %s" % (template['name'], template['templateid']) else: self.templateID = response['result'][0]['templateid'] print "Template Name : \033[31m%s\033[0m "%templateName return response['result'][0]['templateid'] def hostgroup_create(self,hostgroupName): if self.hostgroup_get(hostgroupName): print "hostgroup \033[42m%s\033[0m is exist !"%hostgroupName sys.exit(1) data = json.dumps({ "jsonrpc": "2.0", "method": "hostgroup.create", "params": { "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() print "\033[042m 添加主机组:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids']) def host_create(self, hostip, hostgroupName, templateName): if self.host_get(hostip): print "\033[041m该主机已经添加!\033[0m" sys.exit(1) if self.hostgroup_get(hostgroupName): print "\033[041m该主机组存在!\033[0m" else: data = json.dumps({ "jsonrpc": "2.0", "method": "hostgroup.create", "params": { "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() #print "\033[042m 添加主机组:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids']) group_list=[] template_list=[] for i in hostgroupName.split(','): var = {} var['groupid'] = self.hostgroup_get(i) group_list.append(var) for i in templateName.split(','): var={} var['templateid']=self.template_get(i) template_list.append(var) 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": group_list, "templates": template_list, }, "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() print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids']) def host_disable(self,hostip): data=json.dumps({ "jsonrpc": "2.0", "method": "host.update", "params": { "hostid": self.host_get(hostip), "status": 1 }, "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() print '----主机现在状态------------' print self.host_get(hostip) def host_delete(self,hostid): hostid_list=[] #print type(hostid) for i in hostid.split(','): var = {} var['hostid'] = self.host_get(i) hostid_list.append(var) data=json.dumps({ "jsonrpc": "2.0", "method": "host.delete", "params": hostid_list, "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 Exception,e: print e else: result.close() print "主机 \033[041m %s\033[0m 已经删除 !"%hostid if __name__ == "__main__": zabbix=zabbix_api() parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]') parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机') parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组') parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息') parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组') parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号') parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机') parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号') parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0') if len(sys.argv)==1: print parser.print_help() else: args=parser.parse_args() if args.listhost != 'host' : if args.listhost: zabbix.host_get(args.listhost) else: zabbix.host_get() if args.listgroup !='group': if args.listgroup: zabbix.hostgroup_get(args.listgroup) else: zabbix.hostgroup_get() if args.listtemp != 'template': if args.listtemp: zabbix.template_get(args.listtemp) else: zabbix.template_get() if args.addgroup: zabbix.hostgroup_create(args.addgroup[0]) if args.addhost: zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2]) if args.disablehost: zabbix.host_disable(args.disablehost) if args.deletehost: zabbix.host_delete(args.deletehost[0]) |
<延伸>