zabbix API 的介紹與應用

利用zabbix的API功能可以方便地通過其他程序調用zabbix,從而實現靈活的擴展Zabbix方式。

一、zabbixAPI簡介

  Zabbix的API具有重要的功能,爲第三方調用zabbix、批量操作提供可編程接口,從而輕鬆地用於自己的業務系統,將zabbix監控系統與運維繫統相集成。zabbix API是基於前端HTTP協議實現的,也就是可以通過HTTP請求實現的API,數據傳輸採用JSON RPC協議。

  JSON-RPC是基於JSON的跨語言遠程調用協議,比XML-RPC、Webservice等基於文本的協議傳輸數據量要小;相比Hessian、java-RPC等二進制協議更便於調試、實現、擴展、是非常優秀的一種遠程調用協議。目前主流語言都已有JSON-RPC的實現框架,java語言中較好的JSON-RPC實現框架有jsonrpc4j、Jproxy、JSON-RPC,其中jsonrpc4j既可以獨立使用,又可以與Spring無縫結合,比較適合用於基於Spring的項目開發

二、zabbix API的簡單使用

zabbix api相關:官方文檔:https://www.zabbix.com/documentation/2.4/manual/api/

1、使用user.login方法
params後面的用戶名和密碼是zabbix的web界面登錄名和密碼!!!  
#curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"user.login","params":{"user":"admin","password":"密碼xxx"},"auth": null,"id":0}' http://10.0.18.12/zabbix/api_jsonrpc.php
HTTP/1.1 200 OK
Date: Mon, 24 Oct 2016 10:33:34 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST
Access-Control-Max-Age: 1000
Content-Length: 68
Connection: close
Content-Type: application/json

{"jsonrpc":"2.0","result":"a21db81b19908971f9a8518b5092b414","id":0}
執行OK:
到zabbix庫中查看session
mysql> select * from zabbix.sessions;
+----------------------------------+--------+------------+--------+
| sessionid                        | userid | lastaccess | status |
+----------------------------------+--------+------------+--------+
| 0123b9ec3295562c23a13bc87e8f8b28 |      1 | 1457432079 |      0 |
| 0b13dce7637ea03667b2cae9199db559 |      2 | 1477302663 |      0 |
| 0e2ef1a01dca95bc23171d314d82f1c8 |      1 | 1469440342 |      0 |
| 1a6439ab2bcdd6e6a4dd549e02a09173 |      1 | 1473418801 |      0 |
| 294643838565c4b2c57902c06f0e6e12 |      2 | 1477302700 |      0 |
| 4062d9f3a89a14f734ea73299130a19f |      1 | 1465352471 |      0 |
| 5d14d651069a95c30f313753dfdcd541 |      1 | 1477304346 |      0 |
| 5f2cbe9a9c406f1053ffe8fd7c98e376 |      1 | 1477302828 |      1 |
| 750f97a0b59b00f8ea1a2af05e52c7c8 |      1 | 1464612638 |      0 |
| 910945f4f8ba5b27489c963e73619039 |      1 | 1477363990 |      0 |
| 925832711e34d009245232da998d9382 |      1 | 1453813826 |      0 |
| 986a8661ecab7676fd8716da60c1f9f0 |      1 | 1477375294 |      0 |
| a1d15429a29ae56e8a347647ba600d51 |      1 | 1453814055 |      0 |
| a21db81b19908971f9a8518b5092b414 |      1 | 1477305214 |      0 |   ##可以看到了
| a43e362ed8268af31d8b15c8d3234acb |      1 | 1476275454 |      0 |
| b29b878a0868f344896b78f5cf843a5c |      2 | 1477302723 |      0 |
| b55a3b569c95b9158ec5bf67b8c4870f |      1 | 1476434671 |      0 |
| c4703a34d0afe9130cbb921995ad4f7e |      1 | 1473669065 |      0 |
| db2111abc2e6d96f6baaaa5089a538c1 |      1 | 1453962136 |      0 |
+----------------------------------+--------+------------+--------+
19 rows in set (0.00 sec)
2、使用host.get方法
這裏host留空,表示查看所有的
#curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"host.get","params":{"output":"hostid","selectGroups":"extend","filter":{"host":""}},"auth":"a21db81b19908971f9a8518b5092b414","id":1}' http://10.0.18.12/zabbix/api_jsonrpc.php
HTTP/1.1 200 OK
Date: Tue, 25 Oct 2016 06:49:20 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST
Access-Control-Max-Age: 1000
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json

{"jsonrpc":"2.0","result":[{"hostid":"10084","groups":[{"groupid":"4","name":"Zabbix servers","internal":"0","flags":"0"}]},{"hostid":"10105","groups":[{"groupid":"2","name":"Linux servers","internal":"0","flags":"0"}]},{"hostid":"10106","groups":
………………………… 太多了
…………………………
查看Linux servers組,如下:
#curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"host.get","params":{"output":"extend","filter":{"host":"Linux servers"}},"auth":"a21db81b19908971f9a8518b5092b414","id":1}' http://10.0.18.12/zabbix/api_jsonrpc.php
HTTP/1.1 200 OK
Date: Tue, 25 Oct 2016 06:27:19 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST
Access-Control-Max-Age: 1000
Content-Length: 36
Connection: close
Content-Type: application/json

{"jsonrpc":"2.0","result":[],"id":1}

3、查看zabbix監控的hosts,這裏有一個腳本

#cat zabbixgethost.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php"  #10.0.18.12是我自己的zabbix serverip
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin"              #web界面進入zabbix的用戶名
zabbix_pass   = "xxxx"               #web界面進入zabbix的密碼
auth_code     = ""
 
#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={ 
        "method":"host.get", 
        "params":{ 
                "output": "extend",
        } 
    }
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
if len(auth_code) == 0:
    sys.exit(1)
if len(auth_code) != 0:
    get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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'])
執行:
#python zabbixgethost.py
{u'jsonrpc': u'2.0', u'result': [{u'available': u'1', u'maintenance_type': u'0', u'ipmi_errors_from': u'0', u'ipmi_username': u'', u'snmp_disable_until': u'0', u'ipmi_authtype': u'-1', u'ipmi_disable_until':
……………………  省略
'10267', u'name': u'datainsight_backstage1', u'jmx_errors_from': u'0', u'jmx_disable_until': u'0', u'flags': u'0', u'error': u'', u'maintenance_from': u'0', u'errors_from': u'0'}], u'id': 1}
Number Of Hosts:  160
一共有160臺主機!

4、使用api批量添加新主機

腳本如下:

#cat zabbixhostcreate.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""

#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={
    "method": "host.create",
    "params": {
        "host": "",                    #新主機hostname,這裏留空爲了批量添加
        "interfaces": [
            {
                "type": 1,
                "main": 1,
                "useip": 1,
                "ip": "",              #新主機ip地址,這裏留空爲了批量添加
                "dns": "",
                "port": "10050"        #zabbix client 端口
            }
        ],
        "groups": [
            {
                "groupid": "2"         #組id
            } 
        ],
        "templates": [
            {
                "templateid": "10001"  #模板id
            }
        ],
        "inventory": {
            "macaddress_a": "",
            "macaddress_b": ""
        }
    }
}
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
print json_data
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
with open("serverlist.txt") as f:      #這裏是一個從serverlist獲取新hosts的hostname和ip的方法
    data=f.readlines()
f.close()
for line in data:
    host,ip=line.split()
    json_data['params']['host']=host
    json_data['params']['interfaces'][0]['ip']=ip
    print json_data                    #到這裏結束
    if len(auth_code) == 0:
        sys.exit(1)
    if len(auth_code) != 0:
        get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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']) 
 
開始批量添加
#cat serverlist.txt  #將需要加入監控的新主機按照如下格式寫入serverlist文件中
point_soa1 10.1.12.177
point_soa2 10.1.12.178
執行:
#python  zabbixhostcreate.py
{'jsonrpc': '2.0', 'params': {'templates': [{'templateid': '10001'}], 'host': '', 'interfaces': [{'ip': '', 'useip': 1, 'dns': '', 'main': 1, 'type': 1, 'port': '10050'}], 'groups': [{'groupid': '2'}], 'inventory': {'macaddress_b': '', 'macaddress_a': ''}}, 'method': 'host.create', 'auth': u'550390eace5ebcd60168d791c38b4f0d', 'id': 1}
{'jsonrpc': '2.0', 'params': {'templates': [{'templateid': '10001'}], 'host': 'point_soa1', 'interfaces': [{'ip': '10.1.12.177', 'useip': 1, 'dns': '', 'main': 1, 'type': 1, 'port': '10050'}], 'groups': [{'groupid': '2'}], 'inventory': {'macaddress_b': '', 'macaddress_a': ''}}, 'method': 'host.create', 'auth': u'550390eace5ebcd60168d791c38b4f0d', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'hostids': [u'10289']}, u'id': 1}
Number Of Hosts:  1
{'jsonrpc': '2.0', 'params': {'templates': [{'templateid': '10001'}], 'host': 'point_soa2', 'interfaces': [{'ip': '10.1.12.178', 'useip': 1, 'dns': '', 'main': 1, 'type': 1, 'port': '10050'}], 'groups': [{'groupid': '2'}], 'inventory': {'macaddress_b': '', 'macaddress_a': ''}}, 'method': 'host.create', 'auth': u'550390eace5ebcd60168d791c38b4f0d', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'hostids': [u'10290']}, u'id': 1}
Number Of Hosts:  1
可以看到一共添加了2臺host!到zabbix的web界面查看,是添加成功的!

但是以上的批量添加的腳本只能實現添加一個模板,即Template OS Linux (id爲10001)這個基本模板,如果想添加2個後者多個模板,需要使用下面這個改動過的腳本,如下:

#cat zabbixhostcreate2.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""

#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
template_list=["10001","10107"]   #定義list,寫入模板id
json_data={
    "method": "host.create",
    "params": {
        "host": "",
        "interfaces": [
            {
                "type": 1,
                "main": 1,
                "useip": 1,
                "ip": "",
                "dns": "",
                "port": "10050"
            }
        ],
        "groups": [
            {
                "groupid": "2"
            }
        ],
        "templates": template_list,  #由之前的改爲了list格式
        "inventory": {
            "macaddress_a": "",
            "macaddress_b": ""
        }
    }
}
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
print json_data
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
with open("serverlist.txt") as f:
    data=f.readlines()
f.close()
for line in data:
    host,ip=line.split()
    json_data['params']['host']=host
    json_data['params']['interfaces'][0]['ip']=ip
    print json_data
    if len(auth_code) == 0:
        sys.exit(1)
    if len(auth_code) != 0:
        get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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']) 
執行腳本如下:
#cat serverlist.txt
cmk_bs1 10.1.12.210
cmk_bs2 10.1.12.211
cmk_soa2 10.1.12.209
開始執行:
#python zabbixhostcreate2.py
{'jsonrpc': '2.0', 'params': {'templates': [{'templateid': '10001'}], 'host': '', 'interfaces': [{'ip': '', 'useip': 1, 'dns': '', 'main': 1, 'type': 1, 'port': '10050'}], 'groups': [{'groupid': '2'}], 'inventory': {'macaddress_b': '', 'macaddress_a': ''}}, 'method': 'host.create', 'auth': u'550390eace5ebcd60168d791c38b4f0d', 'id': 1}
{'jsonrpc': '2.0', 'params': {'templates': ['10001', '10107'], 'host': 'cmk_bs1', 'interfaces': [{'ip': '10.1.12.210', 'useip': 1, 'dns': '', 'main': 1, 'type': 1, 'port': '10050'}], 'groups': [{'groupid': '2'}], 'inventory': {'macaddress_b': '', 'macaddress_a': ''}}, 'method': 'host.create', 'auth': u'60341ac795bc16de28993f0ce5ad7ee6', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'hostids': [u'10286']}, u'id': 1}
Number Of Hosts:  1
{'jsonrpc': '2.0', 'params': {'templates': ['10001', '10107'], 'host': 'cmk_bs2', 'interfaces': [{'ip': '10.1.12.211', 'useip': 1, 'dns': '', 'main': 1, 'type': 1, 'port': '10050'}], 'groups': [{'groupid': '2'}], 'inventory': {'macaddress_b': '', 'macaddress_a': ''}}, 'method': 'host.create', 'auth': u'60341ac795bc16de28993f0ce5ad7ee6', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'hostids': [u'10287']}, u'id': 1}
Number Of Hosts:  1
{'jsonrpc': '2.0', 'params': {'templates': ['10001', '10107'], 'host': 'cmk_soa2', 'interfaces': [{'ip': '10.1.12.209', 'useip': 1, 'dns': '', 'main': 1, 'type': 1, 'port': '10050'}], 'groups': [{'groupid': '2'}], 'inventory': {'macaddress_b': '', 'macaddress_a': ''}}, 'method': 'host.create', 'auth': u'60341ac795bc16de28993f0ce5ad7ee6', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'hostids': [u'10288']}, u'id': 1}
Number Of Hosts:  1
添加了3臺主機,並且爲每臺主機添加了2個模板!

5、批量刪除host

腳本如下:

#cat zabbixhostdelete.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""
 
#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={ 
        "method":"host.delete", 
        "params":['']        #留空是爲了批量刪除
    }
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
with open("deletelist.txt") as f:      #刪除列表從deletelist中獲取
    data=f.readlines()
f.close()
for line in data:
    id=line.split()
    json_data['params']=id
    print json_data                    #到此結束
    if len(auth_code) == 0:
        sys.exit(1)
    if len(auth_code) != 0:
        get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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']) 
批量刪除:
mysql> select hostid,host from hosts where host='point_soa1';
+--------+------------+
| hostid | host       |
+--------+------------+
|  10292 | point_soa1 |
+--------+------------+
1 row in set (0.00 sec)
mysql> select hostid,host from hosts where host='point_soa2';
+--------+------------+
| hostid | host       |
+--------+------------+
|  10290 | point_soa2 |
+--------+------------+
1 row in set (0.00 sec)      
將查到的hostid寫入到deletelist.txt中,如下:
#cat deletelist.txt
10290
10292
執行腳本
#python zabbixhostdelete.py
{'jsonrpc': '2.0', 'params': ['10290'], 'method': 'host.delete', 'auth': u'f844af3cbbd2546410ab8ae8c441cfe1', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'hostids': [u'10290']}, u'id': 1}
Number Of Hosts:  1
{'jsonrpc': '2.0', 'params': ['10292'], 'method': 'host.delete', 'auth': u'f844af3cbbd2546410ab8ae8c441cfe1', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'hostids': [u'10292']}, u'id': 1}
Number Of Hosts:  1
刪除2個host!到zabbix的web界面查看,是刪除成功的!

也可以改成如下:

#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""
 
#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={ 
        "method":"host.delete", 
        "params":[]      #改成這樣
    }
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
with open("deletelist.txt") as f:                #改成這樣
    data=f.readlines()  
f.close()
for line in data:
    json_data['params'].append(line)
print json_data                    #結束
if len(auth_code) == 0:
    sys.exit(1)
if len(auth_code) != 0:
    get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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'])

三、zabbix API 創建維護模式

在某些時候,監控的主機進行代碼迭代,重啓端口,就會經常報警,這個時候報警就成了負擔,如果一次做很多臺server的升級,一直髮郵件很煩人,所以沒必要再發郵件了,如果將這些主機自動進入維護模式,那就不用收到那麼多報警郵件了。

1、以組爲單位進入維護模式

簡單來說就是假如有10臺server需要發佈升級代碼,這10臺server屬於一個組server1,那麼就可以將server1組添加到維護狀態,就不會收到報警郵件了,腳本代碼如下:

#cat zabbixaddmaintenance.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""
 
#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={
    "method": "maintenance.create",    #調用的方法
    "params": {
        "name": "test maintenance",    #自定義維護模式的名稱
         "active_since": 1477584000,   #維護開始時間
         "active_till": 1509120000,    #維護結束時間
        "groupids": ["13"],            #維護的server1的組id
        "timeperiods": [
            {
                "timeperiod_type": 2,  #type類型,2是Daily,3是Weekly
                "every": 1,            #一天一次
                "dayofweek": 64,       
                "start_time": 32400 ,  #維護開始的時間,這裏是9h,換算成秒
                "period": 75600      #維護時長,這裏21個小時,換算成秒
            }
        ],
    }
}
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
print json_data
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
if len(auth_code) == 0:
    sys.exit(1)
if len(auth_code) != 0:
    get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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 "The Number Of Maintenance: ", len(response['result']) 
生成時間的命令:
假如維護時間是從2016-10-28 00:00 - 2017-10-28 00:00 轉換成zabbix時間如下:
#timer1=`date -d "2016-10-28 00:00" +%s`
#echo $timer1
1477584000
#timer2=`date -d "2017-10-28 00:00" +%s`
#echo $timer2
1509120000
執行腳本
#python zabbixaddmaintenance.py
{'jsonrpc': '2.0', 'params': {'timeperiods': [{'timeperiod_type': 2, 'dayofweek': 64, 'start_time': 32400, 'every': 1, 'period': 75600}], 'active_since': 1477584000, 'active_till': 1509120000, 'name': 'test maintenance', 'groupids': ['13']}, 'method': 'maintenance.create', 'auth': u'02dd31060aa2bae5dc90dae489a7a887', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'maintenanceids': [u'8']}, u'id': 1}
The Number Of Maintenance:  1
可以看到創建OK!
PS:查看組id,是在zabbix庫中的groups表,如下:
mysql>select * from groups;

到web界面查看:http://10.0.18.12/zabbix

wKiom1gTLoDwrnIPAACotvwuklc220.png

進入查看:

wKioL1gTLvKTDpu9AAA8i2t1Y6s357.png

點擊“Periods”:

wKioL1gTLzLyQixBAABywE4OZS4627.png

可以看到維護的時間!

點擊“Hosts & Groups”:

wKioL1gTL-qjyrWiAABYuiy4CeY133.png然後將point_soa組中的2臺server:point_soa1和point_soa2的zabbix agentd停掉,查看狀態是處於unreachable的維護狀態,但是沒有發送報警郵件!

wKioL1gTMI_gbgUvAAAtxvYdsnU457.png

2、將多個組添加進入維護模式

在某些環境,有時候發佈代碼升級的server分屬不同的組,比如分屬point_soa和agent_soa,如果想將這兩個組都加入到維護模式,上面的腳本,就需要修改,並且執行2次,這個效率較低,將上面的腳本稍微修改了一下,然後可以同時將2個組加入到維護模式,腳本如下:

#cat zabbixaddmaintenance.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""
 
#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={
    "method": "maintenance.create",
    "params": {
         "name": "test maintenance",
         "active_since": 1477584000,
         "active_till": 1509120000,
         "groupids": [],      ##是一個列表,內容從txt文件中獲取
         "timeperiods": [
            {
                "timeperiod_type": 2,
                "every": 1,
                "dayofweek": 64,
                "start_time": 32400 ,
                "period": 75600
            }
        ],
    }
}
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
print json_data
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
with open("addmainten.txt") as f:                #添加的代碼,開始
    data=f.readlines()
f.close()
for line in data:
    json_data['params']['groupids'].append(line.strip("\n")) #處理換行符,不然會報錯。
print json_data                                  ##結束                                 
if len(auth_code) == 0:
    sys.exit(1)
if len(auth_code) != 0:
    get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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 "The Number Of Maintenance: ", len(response['result']) 
先到zabbix數據庫查看組id:
mysql> select * from groups where name like '%soa';
+---------+-----------+----------+-------+
| groupid | name      | internal | flags |
+---------+-----------+----------+-------+
|      13 | point_soa |        0 |     0 |
|      14 | agent_soa |        0 |     0 |
+---------+-----------+----------+-------+
2 rows in set (0.00 sec)
將需要加入維護模式的組,添加到addmainten.txt中,如下:
#cat addmainten.txt 
13
14
執行腳本
#python zabbixaddmaintenance.py
{'jsonrpc': '2.0', 'params': {'timeperiods': [{'timeperiod_type': 2, 'dayofweek': 64, 'start_time': 32400, 'every': 1, 'period': 75600}], 'active_since': 1477584000, 'active_till': 1509120000, 'name': 'test maintenance', 'groupids': []}, 'method': 'maintenance.create', 'auth': u'4677074d13da0baf955f78ea2c2e2164', 'id': 1}
{'jsonrpc': '2.0', 'params': {'timeperiods': [{'timeperiod_type': 2, 'dayofweek': 64, 'start_time': 32400, 'every': 1, 'period': 75600}], 'active_since': 1477584000, 'active_till': 1509120000, 'name': 'test maintenance', 'groupids': ['13', '14']}, 'method': 'maintenance.create', 'auth': u'4677074d13da0baf955f78ea2c2e2164', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'maintenanceids': [u'19']}, u'id': 1}
The Number Of Maintenance:  1
可以看到添加成功了,然後到web界面查看,如下:

wKiom1gW6rjA8GYFAABKRUcxGWc729.png

wKioL1gW6wGB7BO5AABg03tNQqc713.pngwKioL1gW60rAzNCuAABm8sI9DE8908.png可以看到agent_soa和point_soa兩個組添加到維護模式了!將其中的幾臺服務器的agent客戶端停掉,會報警,但是不會觸發郵件。如下:

wKiom1gW7WiA8P_6AABhXMFNrEU101.png

3、刪除維護模式

zabbix的維護模式是在特定時間有效,當不再需要維護的時候,就需要刪除維護模式,以免真的出現問題的時候,無法及時發送報警,進而影響業務!以下腳本,可以實現刪除創建的維護模式:

先在zabbix數據庫查看已經創建的維護模式id:
mysql> select * from maintenances;
+---------------+------------------+------------------+-------------+--------------+-------------+
| maintenanceid | name             | maintenance_type | description | active_since | active_till |
+---------------+------------------+------------------+-------------+--------------+-------------+
|            19 | test maintenance |                0 |             |   1477584000 |  1509120000 |
|            20 | update           |                0 |             |   1477929600 |  1509552000 |
+---------------+------------------+------------------+-------------+--------------+-------------+
2 rows in set (0.00 sec)
可以看到有2個維護狀態。
將在數據庫查到的id加入文本文件中,實現批量刪除
#cat deletemain.txt
19
20
查看腳本:
#cat deletemaintenance.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""
 
#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={
    "method": "maintenance.delete",
    "params": [],           #定義一個列表
}
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
print json_data
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
with open("deletemain.txt") as f:             #將需要刪除的維護id放在deletemain.txt中
    data=f.readlines()
f.close()
for line in data:                                #循環獲取id
    json_data['params'].append(line.strip("\n")) #去除換行符這個特殊符號
print json_data                 
if len(auth_code) == 0:
    sys.exit(1)
if len(auth_code) != 0:
    get_host_data = json.dumps(json_data) 
  
    # create request object 
    request = urllib2.Request(zabbix_url,get_host_data) 
    for key in zabbix_header: 
        request.add_header(key,zabbix_header[key]) 
  
    # get host list 
    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 "Delete Number Of Maintenance: ", len(response['result']) 
#python deletemaintenance.py
{'jsonrpc': '2.0', 'params': [], 'method': 'maintenance.delete', 'auth': u'ea11a835164c73a8da6673ef4522c3cb', 'id': 1}
{'jsonrpc': '2.0', 'params': ['19', '20'], 'method': 'maintenance.delete', 'auth': u'ea11a835164c73a8da6673ef4522c3cb', 'id': 1}
{u'jsonrpc': u'2.0', u'result': {u'maintenanceids': [u'19', u'20']}, u'id': 1}
Delete Number Of Maintenance:  1
PS:提示信息Delete Number Of Maintenance:  1 雖然是數字1,這個打印結果是腳本本身的一個小問
可以忽略,實際上列在deletemain.txt中的maintenanceid都刪除OK了!

4、更新維護模式

遇到一種情況:不想重新創建維護模式,想將這個維護模式中的server更換成另外一個或者多個server,這個時候需要使用zabbix API的maintenance.update方法了!

假如之前創建了一個維護模式:test maintenance,如下圖:

wKiom1ga8OHTN5UhAAA8HTY-5MA449.png 

wKioL1ga8SWgmgSiAABrOwnktpo272.png

wKiom1ga8TuwwhHhAABFffiTJ7I510.png

現在通過腳本將cmk_bs1和cmk_bs2兩臺服務器覆蓋掉,加入新的2臺服務器,腳本如下:

首先查看維護模式的id,如下:
mysql> select * from maintenances;
+---------------+------------------+------------------+-------------+--------------+-------------+
| maintenanceid | name             | maintenance_type | description | active_since | active_till |
+---------------+------------------+------------------+-------------+--------------+-------------+
|            22 | test maintenance |                0 |             |   1477584000 |  1509120000 |
+---------------+------------------+------------------+-------------+--------------+-------------+
1 row in set (0.00 sec)
可以看到id爲22!!!
#cat zabbixupdatemain.py
#!/usr/bin/env python 
#coding=utf-8 
 
#導入模塊,urllib2是一個模擬瀏覽器HTTP方法的模塊
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,用戶名,密碼,這裏修改爲自己實際的參數
zabbix_url="http://10.0.18.12/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "xxxx" 
auth_code     = ""
 
#auth user and password 
#用戶認證信息的部分,最終的目的是得到一個SESSIONID
#這裏是生成一個json格式的數據,用戶名和密碼
auth_data = json.dumps(
        {
            "jsonrpc":"2.0",
            "method":"user.login",
            "params":
                    {
                        "user":zabbix_user,
                        "password":zabbix_pass
                    },
            "id":0
        }) 
 
# create request object 
request = urllib2.Request(zabbix_url,auth_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
 
#auth and get authid 
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() 
    #判斷SESSIONID是否在返回的數據中
    if  'result'  in  response:
        auth_code=response['result']
    else:
        print  response['error']['data']
  
# request json 
json_data={
    "method": "maintenance.update",
    "params": {
         "maintenanceid": "22",          ##維護模式id
         "active_since": 1477584000,
         "active_till": 1509120000,
         "hostids": [],               ##留空,從txt中獲取hostid
         "timeperiods": [                          #timeperiods根據情況自行修改
            {
                "timeperiod_type": 2,
                "every": 1,
                "dayofweek": 64,
                "start_time": 32400 ,
                "period": 75600            #將維護時間由原來的2小時改爲21小時
            }
        ],
    }
}
json_base={
    "jsonrpc":"2.0",
    "auth":auth_code,
    "id":1
}
json_data.update(json_base)
print json_data
#用得到的SESSIONID去通過驗證,獲取主機的信息(用http.get方法)
with open("addmainten.txt") as f:        #讀取txt文件中的hostsid   #開始行
    data=f.readlines()
f.close()
for line in data:
    json_data['params']['hostids'].append(line.strip("\n"))
print json_data                            #結束行          
if len(auth_code) == 0:
    sys.exit(1)
if len(auth_code) != 0:
    get_host_data = json.dumps(json_data) 
    
# create request object 
request = urllib2.Request(zabbix_url,get_host_data) 
for key in zabbix_header: 
    request.add_header(key,zabbix_header[key]) 
# get host list 
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 "///////"
    print response
    #顯示主機的個數
    print "The Number Of Maintenance: ", len(response['result'])

到zabbix數據庫查出更新host的hostid,如下

mysql> select hostid,name  from hosts where name like 'agent_soa%';
+--------+------------+
| hostid | name       |
+--------+------------+
|  10154 | agent_soa1 |
|  10155 | agent_soa2 |
+--------+------------+
2 rows in set (0.00 sec)
將查到的id寫入到txt文件中:
#cat addmainten.txt
10154
10155
執行腳本
#python zabbixupdatemain.py
{'jsonrpc': '2.0', 'params': {'hostids': [], 'active_since': 1477584000, 'active_till': 1509120000, 'maintenanceid': '22', 'timeperiods': [{'timeperiod_type': 2, 'dayofweek': 64, 'start_time': 32400, 'every': 1, 'period': 75600}]}, 'method': 'maintenance.update', 'auth': u'bd0f78f684f03546345001197eae8839', 'id': 1}
{'jsonrpc': '2.0', 'params': {'hostids': ['10154', '10155'], 'active_since': 1477584000, 'active_till': 1509120000, 'maintenanceid': '22', 'timeperiods': [{'timeperiod_type': 2, 'dayofweek': 64, 'start_time': 32400, 'every': 1, 'period': 75600}]}, 'method': 'maintenance.update', 'auth': u'bd0f78f684f03546345001197eae8839', 'id': 1}
///////
{u'jsonrpc': u'2.0', u'result': {u'maintenanceids': [u'22']}, u'id': 1}
The Number Of Maintenance:  1
可以看到執行成功,沒有報錯,到web界面查看update之後的維護模式

wKiom1ga8-DjNQKSAABWqCDINPg793.png維護時間由原來的2個小時update到了21個小時!

wKioL1ga8__AN2tvAABEeLucwZM497.png維護的主機由原來的兩臺cmk機器update成爲了agent兩臺機器!

PS:維護模式的update方法在CentOS 6.6+zabbix 2.4.4 +Python 2.7.12 版本執行成功,但是在CentOS 6.5+zabbix 2.2.4+Python 2.6.6執行報錯如下:

{u'jsonrpc': u'2.0', u'id': 1, u'error': {u'message': u'Invalid params.', u'code': -32602, u'data': u'Maintenance "" already exists.'}}

百思不得其解,google了好多資料,也沒有解決,如果有朋友碰巧遇到了相似情況,還請多多指導,謝謝!

補充:

命令行調用方法:

curl -i -X POST -H 'Content-Type:application/json-rpc' -d '{ "jsonrpc": "2.0","method": "host.create","params": {"user":"admin","password":"123456","host": "salesagent","interfaces": [{"type": 1,"main": 1,"useip": 1,"ip": "10.11.20.100","dns": "","port": "10050"}],"groups": [{"groupid": "67"}],"templates": [{"templateid": "10001"}],"inventory_mode": 0,"inventory": {"macaddress_a": "01234","macaddress_b": "56768"}},"auth": "432075611467a50738c5cd76c173b36c", "id": 1}'  http://ip/api_jsonrpc.php

參考腳本鏈接:https://github.com/itnihao/zabbix-book/tree/master/13-chapter/zabbix-api-example

不足之處,請多多指出!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章