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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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)
# 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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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']['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)
# 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
执行:
#pythonzabbixhostcreate.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'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'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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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']['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)
# 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'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'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'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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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)
# 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'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'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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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)
# 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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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)
# 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'id': 1}
The Number Of Maintenance:1
可以看到创建OK!
PS:查看组id,是在zabbix库中的groups表,如下:
mysql>select * from groups; 到web界面查看:http://10.0.18.12/zabbix
http://s4.运维网.com/wyfs02/M00/89/73/wKiom1gTLoDwrnIPAACotvwuklc220.png
进入查看:
http://s1.运维网.com/wyfs02/M00/89/71/wKioL1gTLvKTDpu9AAA8i2t1Y6s357.png
点击“Periods”:
http://s2.运维网.com/wyfs02/M00/89/71/wKioL1gTLzLyQixBAABywE4OZS4627.png
可以看到维护的时间!
点击“Hosts & Groups”:
http://s1.运维网.com/wyfs02/M01/89/71/wKioL1gTL-qjyrWiAABYuiy4CeY133.png然后将point_soa组中的2台server:point_soa1和point_soa2的zabbix agentd停掉,查看状态是处于unreachable的维护状态,但是没有发送报警邮件!
http://s5.运维网.com/wyfs02/M01/89/71/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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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)
# 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'id': 1}
The Number Of Maintenance:1
可以看到添加成功了,然后到web界面查看,如下:http://s5.运维网.com/wyfs02/M01/89/88/wKiom1gW6rjA8GYFAABKRUcxGWc729.png
http://s4.运维网.com/wyfs02/M01/89/86/wKioL1gW6wGB7BO5AABg03tNQqc713.pnghttp://s5.运维网.com/wyfs02/M02/89/86/wKioL1gW60rAzNCuAABm8sI9DE8908.png可以看到agent_soa和point_soa两个组添加到维护模式了!将其中的几台服务器的agent客户端停掉,会报警,但是不会触发邮件。如下:
http://s4.运维网.com/wyfs02/M02/89/89/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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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)
# 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'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,如下图:
http://s3.运维网.com/wyfs02/M01/89/BC/wKiom1ga8OHTN5UhAAA8HTY-5MA449.png
http://s1.运维网.com/wyfs02/M02/89/B9/wKioL1ga8SWgmgSiAABrOwnktpo272.png
http://s2.运维网.com/wyfs02/M00/89/BC/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)
#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'inresponse:
auth_code=response['result']
else:
printresponse['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)
# 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,namefrom 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'id': 1}
The Number Of Maintenance:1
可以看到执行成功,没有报错,到web界面查看update之后的维护模式http://s4.运维网.com/wyfs02/M01/89/BC/wKiom1ga8-DjNQKSAABWqCDINPg793.png维护时间由原来的2个小时update到了21个小时!
http://s2.运维网.com/wyfs02/M02/89/B9/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
不足之处,请多多指出!
页:
[1]