1. 程式人生 > >Zabbix 調用API 批量添加主機等

Zabbix 調用API 批量添加主機等

token have rpc tools ann period 一次 ext 主機信息

今天介紹跟實驗兩種方法調用api接口去批量添加批量管理zabbix客戶端主機:
首先看官網介紹:
概觀
Zabbix API允許您以編程方式檢索和修改Zabbix的配置,並提供對歷史數據的訪問。它被廣泛用於:

創建新的應用程序以使用Zabbix;
將Zabbix與第三方軟件集成;
自動執行日常任務。
Zabbix API是基於Web的API,作為Web前端的一部分提供。它使用JSON-RPC 2.0協議,這意味著兩件事:

該API由一組獨立的方法的;
客戶端和API之間的請求和響應使用JSON格式進行編碼。
有關協議和JSON的更多信息可以在JSON-RPC 2.0規範和JSON格式主頁中找到。

結構體
該API由許多的方法,這些方法名義上分為不同的API。每種方法執行一個特定任務。例如,該host.create方法屬於主機 API,用於創建新主機。從歷史上看,API有時被稱為“類”。

大多數API包含至少四種方法:get,create,update和delete為恭敬地檢索,創建,更新和刪除數據,但某些API可以提供一個完全不同的一套方法。
執行請求
設置前端後,可以使用遠程HTTP請求來調用API。為此,您需要將HTTP POST請求發送到api_jsonrpc.php位於前端目錄中的文件。例如,如果您的Zabbix前端安裝在http://company.com/zabbix下,則調用該apiinfo.version方法的HTTP請求可能如下所示:

POST http://company.com/zabbix/api_jsonrpc.php HTTP / 1.1
Content-Type:application / json-rpc

{ “jsonrpc”: “2.0”, “方法”: “apiinfo.version”, “ID”:1, “AUTH”:NULL, “PARAMS”:{}}
該請求必須具有Content-Type標頭集合至這些值中的一個:application/json-rpc,application/json或application/jsonrequest。

您可以使用任何HTTP客戶端或JSON-RPC測試工具手動執行API請求,但是對於開發應用程序,我們建議您使用社區維護的庫之一。
示例工作流程
以下部分將向您詳細介紹一些用法示例。

認證
在您可以訪問Zabbix內部的任何數據之前,您需要登錄並獲取身份驗證令牌。這可以使用該user.login方法完成。我們假設您要以標準Zabbix Admin用戶身份登錄。然後您的JSON請求將如下所示:

{
“jsonrpc” : “2.0” ,
“method” : “user.login” ,
“params” : {
“user” : “Admin” ,
“password” : “zabbix”
} ,
“id” : 1 ,
“auth” : null
}~~
讓我們仔細看看請求對象。它具有以下屬性:

jsonrpc- API使用的JSON-RPC協議版本; Zabbix API實現了JSON-RPC 2.0版;
method- 被調用的API方法;
params- 將傳遞給API方法的參數;
id - 請求的任意標識符;
auth - 用戶認證令牌; 因為我們還沒有,所以它設置為null。
如果您正確提供了憑據,則API返回的響應將包含用戶身份驗證令牌:

{
“jsonrpc” : “2.0” ,
“result” : “0424bd59b807674191e7d77572075f33” ,
“id” : 1
}
響應對象又包含以下屬性:

jsonrpc - 再次,JSON-RPC協議的版本;
result - 方法返回的數據;
id - 相應請求的標識符。
檢索主機
我們現在有一個有效的用戶身份驗證令牌,可用於訪問Zabbix中的數據。例如,讓我們使用該host.get方法檢索所有已配置主機的ID,主機名和接口:

{
“jsonrpc” : “2.0” ,
“method” : “host.get” ,
“params” : {
“output” : [
“hostid” ,
“host”
] ,
“selectInterfaces” : [
“interfaceid” ,
“ip”
]
} ,
“id” : 2 ,
“auth” : “0424bd59b807674191e7d77572075f33”
}
請註意,該auth屬性現在設置為我們通過調用獲得的身份驗證令牌user.login。
響應對象將包含有關主機的請求數據:

{
“jsonrpc” : “2.0” ,
“result” : [
{
“hostid” : “10084” ,
“host” : “Zabbix server” ,
“interfaces” : [
{
“interfaceid” : “1” ,
“ip” : “127.0.0.1”
}
]
}
] ,
“id” : 2
}
出於性能原因,我們建議始終列出要檢索的對象屬性,並避免檢索所有內容。
創建一個新項目
讓我們使用從前一個請求獲得的數據在“Zabbix服務器”上創建一個新項目host.get。這可以通過使用以下item.create方法完成:

{
“jsonrpc” : “2.0” ,
“method” : “item.create” ,
“params” : {
“name” : “$ 1上的可用磁盤空間” ,
“key_ ” : “vfs.fs.size [/ home / joe /,free]“ ,
”hostid“ : ”10084“ ,
”type“ : 0 ,
”value_type“ : 3 ,
”interfaceid“ : ”1“ ,
”delay“ : 30
} ,
”auth“: “0424bd59b807674191e7d77572075f33” ,
“id” : 3
}
成功的響應將包含新創建的項的ID,可用於在以下請求中引用該項:

{
“jsonrpc” : “2.0” ,
“result” : {
“itemids” : [
“24759”
]
} ,
“id” : 3
}
該item.create方法以及其他創建方法也可以接受對象數組,並通過一次API調用創建多個項目。
創建多個觸發器
因此,如果create方法接受數組,我們可以添加多個觸發器,如下所示:

{
“jsonrpc” : “2.0” ,
“method” : “trigger.create” ,
“params” : [
{
“description” : “{HOST.NAME}上的處理器負載過高” ,
“表達式” : “{Linux server:system.cpu.load [percpu,avg1] .last()}> 5“ ,
} ,
{
”description“ : ”{HOST.NAME}上的進程太多“ ,
”表達式“ : ”{Linux server:proc .nu??m []。avg(5m)}> 300“ ,
}
] ,
”auth“: “0424bd59b807674191e7d77572075f33” ,
“id”: 4
}
成功的響應將包含新創建的觸發器的ID:

{
“jsonrpc” : “2.0” ,
“result” : {
“triggerids” : [
“17369” ,
“17370”
]
} ,
“id” : 4
}
更新項目
啟用項目,即將其狀態設置為“0”:

{
“jsonrpc” : “2.0” ,
“method” : “item.update” ,
“params” : {
“itemid” : “10092” ,
“status” : 0
} ,
“auth” : “0424bd59b807674191e7d77572075f33” ,
“id” : 5
}
成功的響應將包含更新項的ID:

{
“jsonrpc” : “2.0” ,
“result” : {
“itemids” : [
“10092”
]
} ,
“id” : 5
}
該item.update方法以及其他更新方法也可以接受對象數組並使用一個API調用更新多個項目。
更新多個觸發器
啟用多個觸發器,即將其狀態設置為0:

{
“jsonrpc” : “2.0” ,
“method” : “trigger.update” ,
“params” : [
{
“triggerid” : “13938” ,
“status” : 0
} ,
{
“triggerid” : “13939” ,
“狀態“ : 0
}
” ,
“auth” : “0424bd59b807674191e7d77572075f33” ,
“id” : 6
}
成功的響應將包含更新的觸發器的ID:

{
“jsonrpc” : “2.0” ,
“result” : {
“triggerids” : [
“13938” ,
“13939”
]
} ,
“id” : 6
}
這是更新的首選方法。一些API方法host.massupdate允許編寫更簡單的代碼,但不建議使用這些方法,因為它們將在未來的版本中刪除。
錯誤處理
到目前為止,我們所嘗試的一切都運行良好。但是如果我們嘗試對API進行不正確的調用會發生什麽?讓我們嘗試通過調用創建另一個主機,host.create但省略必需groups參數。

{
“jsonrpc” : “2.0” ,
“method” : “host.create” ,
“params” : {
“host” : “Linux server” ,
“interfaces” : [
{
“type” : 1 ,
“main” : 1 ,
“useip” : 1 ,
“ip” : “192.168.3.1” ,
“dns” : “” ,
“port” : “10050”
}
]
} ,
“id” : 7 ,
“auth”: “0424bd59b807674191e7d77572075f33”
}
然後,響應將包含一條錯誤消息:

{
“jsonrpc” : “2.0” ,
“error” : {
“code” : - 32602 ,
“message” : “無效的參數。” ,
“data” : “沒有主機組” Linux服務器\“。”
} ,
“id” : 7
}
如果發生錯誤,而不是result屬性,響應對象將包含error具有以下數據的屬性:

code - 錯誤代碼;
message - 簡短的錯誤摘要;
data - 更詳細的錯誤消息。
錯誤可能在不同情況下發生,例如,使用不正確的輸入值,會話超時或嘗試訪問不存在的對象。您的應用程序應該能夠優雅地處理這些類型的錯誤。

API版本
為了簡化API版本控制,從Zabbix 2.0.4開始,API的版本與Zabbix本身的版本相匹配。您可以使用該apiinfo.version方法找出您正在使用的API的版本。這對於調整應用程序以使用特定於版本的功能非常有用。

我們保證主要版本內部的功能向後兼容性。在主要版本之間進行向後不兼容的更改時,我們通常會在下一版本中將舊功能保留為已棄用,並且僅在之後的版本中將其刪除。有時,我們可能會刪除主要版本之間的功能而不提供任何向後兼容性。重要的是,您永遠不要依賴任何已棄用的功能,並盡快遷移到更新的替代方案。

您可以在API更改日誌中跟蹤對API所做的所有更改。

上邊在官網上介紹的是幾個調用方法結合上邊的我們自己來根據需求寫一個py腳本:
Zabbix可以通過自發現添加主機,不過有時候不準確,通過API添加會更加準確!

使用效果:
技術分享圖片

Excel 格式:

技術分享圖片

cat zabbix_hosts.py

#!/usr/local/bin/python
#coding:utf-8

import json
import urllib2
from urllib2 import URLError
import sys
import xlrd

class ZabbixTools:
def init(self):
self.url = ‘http://10.10.147.183/api_jsonrpc.php‘
self.header = {"Content-Type":"application/json"}

def user_login(self): 
    data = json.dumps({ 
                       "jsonrpc": "2.0", 
                       "method": "user.login", 
                       "params": { 
                                  "user": "admin", 
                                  "password": "zabbix" 
                                  }, 
                       "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 "Auth Failed, please Check your name and password:", e.code 
    else: 
        response = json.loads(result.read()) 
        result.close() 
        self.authID = response[‘result‘] 
        return self.authID 

def host_get(self,hostName): 
    data = json.dumps({ 
                       "jsonrpc":"2.0", 
                       "method":"host.get", 
                       "params":{ 
                                 "output":["hostid","name"], 
                                 "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()) 
        result.close() 
        print "Number Of %s: " % hostName, len(response[‘result‘]) 
        lens=len(response[‘result‘]) 
        if lens > 0:
            return response[‘result‘][0][‘name‘]
        else:
            return ""

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: 
        response = json.loads(result.read()) 
        result.close() 

        lens=len(response[‘result‘]) 
        if lens > 0:
            self.hostgroupID = response[‘result‘][0][‘groupid‘]
            return response[‘result‘][0][‘groupid‘]
        else:
            print "no GroupGet result"
            return ""

def template_get(self, templateName): 
    data = json.dumps({ 
                       "jsonrpc":"2.0", 
                       "method": "template.get", 
                       "params": { 
                                  "output": "extend", 
                                  "filter": { 
                                             "host": [ 
                                                      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() 
        self.templateID = response[‘result‘][0][‘templateid‘] 
        return response[‘result‘][0][‘templateid‘] 

def host_create(self, hostName,visibleName,hostIp,dnsName,proxyName, hostgroupName, templateName1, templateName2): 
    data = json.dumps({ 
                       "jsonrpc":"2.0", 
                       "method":"host.create", 
                       "params":{ 
                                 "host": hostName, 
                                 "name": visibleName, 
                                 "proxy_hostid": self.proxy_get(proxyName),
                                 "interfaces": [ 
                                                    { 
                                                        "type": 1, 
                                                        "main": 1, 
                                                        "useip": 1, 
                                                        "ip": hostIp, 
                                                        "dns": dnsName, 
                                                        "port": "10050" 
                                                    } 
                                                ], 
                                "groups": [ 
                                                { 
                                                    "groupid": self.hostgroup_get(hostgroupName) 
                                                } 
                                           ], 
                                "templates": [ 
                                                { 
                                                    "templateid": self.template_get(templateName1)

                                                },
                                                { 

                                                    "templateid": self.template_get(templateName2) 
                                                } 
                                              ], 
                                 }, 
                       "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 "host : %s is created!   id is  %s\n" % (hostip, response[‘result‘][‘hostids‘][0]) 
        self.hostid = response[‘result‘][‘hostids‘] 
        return response[‘result‘][‘hostids‘] 

def proxy_get(self, ProxyName):
    data = json.dumps({
                       "jsonrpc":"2.0",
                       "method": "proxy.get",
                       "params": {
                                  "output": "extend",
                                  "selectInterface": "extend",
                                  "filter": {
                                      "host": [ ProxyName, ]
                                  }
                                  },
                       "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()
        self.templateID = response[‘result‘][0][‘proxyid‘]
        return response[‘result‘][0][‘proxyid‘]

if name == "main":

test = ZabbixTools() 

workbook = xlrd.open_workbook(‘test.xlsx‘)
for row in xrange(workbook.sheets()[0].nrows):
    hostname=workbook.sheets()[0].cell(row,0).value
    visible=workbook.sheets()[0].cell(row,1).value
    hostip=workbook.sheets()[0].cell(row,2).value
    dnsname=workbook.sheets()[0].cell(row,3).value
    proxy=workbook.sheets()[0].cell(row,4).value
    hostgroup=workbook.sheets()[0].cell(row,5).value
    hosttemp=workbook.sheets()[0].cell(row,6).value
    hosttemp1=workbook.sheets()[0].cell(row,7).value

hostgroup=hostgroup.strip()

    hostnameGet=test.host_get(hostname)
    if hostnameGet.strip()==‘‘:
        test.host_create(hostname,visible,hostip,dnsname,proxy,hostgroup,hosttemp,hosttemp1)
    else:
        print "%s have exist! Cannot recreate !\n" % hostnameGet

上述是根據表格來定義的那 自定義呢:
結合參考三個腳本:
登陸腳本:
#!/usr/bin/env python
import urllib2
import json
#定義URL賬戶密碼
url = ‘http://zabbixip/zabbix/api_jsonrpc.php‘
username = ‘admin‘
password = ‘password‘
#定義通過HTTP方式訪問API地址的函數,後面每次請求API的各個方法都會調用這個函數
def requestJson(url,values):
data = json.dumps(values)
req = urllib2.Request(url, data, {‘Content-Type‘: ‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
output = json.loads(response.read())
#print output
try:
message = output[‘result‘]
except:
message = output[‘error‘][‘data‘]
print message
quit()

return output[‘result‘]

#API接口認證的函數,登錄成功會返回一個Token
def authenticate(url, username, password):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘user.login‘,
‘params‘: {
‘user‘: username,
‘password‘: password
},
‘id‘: ‘0‘
}
idvalue = requestJson(url,values)
return idvalue
定義函數腳本:
#!/usr/bin/env python
#coding=utf-8
import sys
import argparse
import urllib2
import json

#定義更新action函數
def mediatypeupdate(mediatypeid,status,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘mediatype.update‘,
‘params‘: {
"mediatypeid": mediatypeid,
"status": status
},
‘auth‘: auth,
‘id‘: ‘1‘
}
output = requestJson(url,values)
#定義讀取狀態函數
def triggerget(auth):
values = {‘jsonrpc‘: ‘2.0‘,
"method":"trigger.get",
"params": {
"output": [
"triggerid",
"description",
"priority"
],
"filter": {
"value": 1
},
"expandData":"hostname",
"sortfield": "priority",
"sortorder": "DESC"
},
‘auth‘: auth,
‘id‘: ‘2‘
}
output = requestJson(url,values)
return output

#定義通過ip獲取主機id的函數
def ipgetHostsid(ip,url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘host.get‘,
‘params‘: {
‘output‘: [ "host" ],
‘filter‘: {
‘ip‘: ip
},
},
‘auth‘: auth,
‘id‘: ‘3‘
}
output = requestJson(url,values)
return output

#定義通過主機id獲取開啟關閉監控函數
def idupdatehost(status,hostid,url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘host.update‘,
‘params‘: {
"hostid": hostid,
"status": status
},
‘auth‘: auth,
‘id‘: ‘4‘
}
output = requestJson(url,values)
return output
#定義通過項目hostid獲取itemid函數
def getHostsitemsid(hostid,itemsname,url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: "item.get",
"params": {
"output": ["itemids"],
"hostids": hostid,
"filter":{
"key_": itemsname,
},
},

          ‘auth‘: auth,
          ‘id‘: ‘5‘
          }
output = requestJson(url,values)
if len(output)==0:
    return output
else:
    return output[0][‘itemid‘]

#定義通過項目id獲取監控項目最近值信息的函數
def getHostsitemsvalue(itemid,url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: "history.get",
"params": {
"output": "extend",
"history":3,
"itemids":itemid,
"sortfield": "clock",
"sortorder": "DESC",
"limit":1,
},

          ‘auth‘: auth,
          ‘id‘: ‘6‘
          }
output = requestJson(url,values)
if len(output)==0:
    return output
else:
    return output[0]["value"]

#定義更新讀取狀態action函數
def mediatypeget(mediatypeid,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘mediatype.get‘,
‘params‘: {
"output": "extend",

          "filter": {
                    "mediatypeid":mediatypeid,
                     },
          },

          ‘auth‘: auth,
          ‘id‘: ‘7‘
          }
output = requestJson(url,values)
if len(output)==0:
    return output
else:
    return output[0][‘status‘]

#定義maintenance維修模式host函數
def maintenancecreate(maintenancename,active_since,active_till,hostid,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘maintenance.create‘,
‘params‘: {
"name": maintenancename,
"active_since": active_since,
"active_till": active_till,
"hostids": [
hostid
],
"timeperiods": [
{
"timeperiod_type": 0,
"every": 1,
"dayofweek": 64,
"start_time": 64800,
"period": 3600
}
]
},
‘auth‘: auth,
‘id‘: ‘8‘
}
output = requestJson(url,values)

#定義通過模糊獲取關閉主機信息函數
def disabledhostget(url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘host.get‘,
"params": {
"output": ["host"],
‘selectInterfaces‘: [ "ip" ],
"filter": {
"status":1
}
},
‘auth‘: auth,
‘id‘: ‘9‘
}
output = requestJson(url,values)
return output

#定義maintenance維修模式group函數
def maintenancecreategroup(maintenancename,active_since,active_till,groupid,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘maintenance.create‘,
‘params‘: {
"name": maintenancename,
"active_since": active_since,
"active_till": active_till,
"groupids": [
groupid
],
"timeperiods": [
{
"timeperiod_type": 0,
"every": 1,
"dayofweek": 64,
"start_time": 64800,
"period": 3600
}
]
},
‘auth‘: auth,
‘id‘: ‘10‘
}
output = requestJson(url,values)

#定義通過host groups named 獲取groupid
def groupnameGroupid(groupname,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘hostgroup.get‘,
"params": {
"output": "extend",
"filter": {
"name": [
groupname
]
}
},
‘auth‘: auth,
‘id‘: ‘11‘
}
output = requestJson(url,values)
return output

#定義模糊查詢維護主機
def maintenanceget(url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘maintenance.get‘,
"params": {
"output": "extend",
},
‘auth‘: auth,
‘id‘: ‘12‘
}
output = requestJson(url,values)
return output

#定義批量恢復處於維護主機
def maintenancedelete(maintenanceid,url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘maintenance.delete‘,
"params": [
maintenanceid
],
‘auth‘: auth,
‘id‘: ‘13‘
}
output = requestJson(url,values)
return output

#定義通過hostid獲取graphid的函數
def getgraphid(hostid,graphname,url,auth):
values = {‘jsonrpc‘: ‘2.0‘,
‘method‘: ‘graph.get‘,
‘params‘: {
"output": "name",
"hostids": hostid,
"sortfield": "name",
‘filter‘: {
"name": graphname
},

                      },
                      ‘auth‘: auth,
                      ‘id‘: ‘14‘
                      }
    output = requestJson(url,values)
    return output

調用執行腳本:
#!/usr/bin/env python
#coding=utf-8
import urllib2
import sys
import json
import argparse
from login import
from function import

#登陸zabbix獲取auth
auth = authenticate(url, username, password)
#狀態0是啟用監控,1是禁用監控
status=1
#定義操作ip
hostip=‘192.168.1.100‘
#通過hostip獲取zabbix hostid
hostids=ipgetHostsid(hostip,url,auth)
hostid=hostids[0][‘hostid‘]
#通過主機id開啟關閉監控
idupdatehost(status,hostid,url,auth)

Zabbix 調用API 批量添加主機等