由於zabbix監控的主機雖爲同一個業務,但是由於其跨機房並且網絡爲爲16位,兩個機房導致zabbix的自動添加掃描的主機數量就差不多有12w多個,嚴重影響其效率和性能.
使用zabbix API的基本步驟如下:
連接http://x.x.x.x/api_jsonrpc.php,(在zabbix網頁文件的目錄下爲api_jsonrpc.php),提供用戶名和密碼,並標識HTTP頭部"Content-Type":"application/json",HTTP方法爲post.
獲取SESSION
通過SESSION建立後續連接.
提交POST數據,格式爲JSON,其中存放對應的API方法,獲取(提交)需要的數據
添加HOST示例(用python寫的示例,python>=2.6)
#!/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企業級分佈式監控系統>>,這書還是挺不錯的.嘿嘿....