因爲zabbix監控的主機雖爲同一個業務,可是因爲其跨機房而且網絡爲爲16位,兩個機房致使zabbix的自動添加掃描的主機數量就差很少有12w多個,嚴重影響其效率和性能.php
使用zabbix API的基本步驟以下:python
鏈接http://x.x.x.x/api_jsonrpc.php,(在zabbix網頁文件的目錄下爲api_jsonrpc.php),提供用戶名和密碼,並標識HTTP頭部"Content-Type":"application/json",HTTP方法爲post.json
獲取SESSIONapi
經過SESSION創建後續鏈接.服務器
提交POST數據,格式爲JSON,其中存放對應的API方法,獲取(提交)須要的數據網絡
添加HOST示例(用python寫的示例,python>=2.6)app
#!/usr/bin/env python #coding=utf-8 import json import urllib2 import sys from urllib2 import Request,urlopen,URLError,HTTPError #zabbix的地址,用戶名,密碼 zabbix_url="http://x.x.x.x/api_jsonrpc.php" zabbix_header={"Content-Type":"application/json"} zabbix_user="admin" zabbix_pass="zabbix" auth_code="" #用戶認證信息,最終目的是須要獲得一個SESSIONID #下面是生成一個JSON格式的數據:用戶名和密碼 auth_data=json.dumps( { "jsonrpc":"2.0", "method":"user.login", "params": { "user":zabbix_user, "password":zabbix_pass }, "id":0 }) request = urllib2.Request(zabbix_url,auth_data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) try: result = urllib2.urlopen(request) except HTTPError,e: print 'The server couldn\'t fulfill the request,Error code: ' ,e.code except URLError,e: print 'We failed to reach a server.Reason:',e.reason else: response=json.loads(result.read()) result.close() if 'result' in response: auth_code=response['result'] else: print response['error']['data'] #下面是API的請求,方法是host.create建立一個主機,具體API的方法能夠參考官網的,上面很全 json_data={ "method":"host.create", "params":{'groups':[{'groupid':'8'}], 'host':'192.168.2.208', 'proxy_hostid':'10107', #代理服務器 'interfaces':[{'dns':'', 'ip':'192.168.2.208', 'main':1, 'port':'10050', 'type':1, 'useip':1 }], 'templates':[{'templateid':'10429'},{'templateid':'10129'}] #用到的模板 } } json_base={ "jsonrpc":"2.0", "auth":auth_code, "id":1 } json_data.update(json_base) if len(auth_code) == 0: sys.exit(1) if len(auth_code) != 0: get_host_data = json.dumps(json_data) request = urllib2.Request(zabbix_url,get_host_data) for key in zabbix_header: request.add_header(key,zabbix_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()) result.close() print response print "Number of hosts",len(response['result'])
5.其實主要仍是python和API的使用方法.提供一個思路,至於如何批量操做,只須要從這裏擴展就好了,文章參考吳兆鬆的<<Zabbix企業級分佈式監控系統>>,這書仍是挺不錯的.嘿嘿....分佈式