简介:
Zabbix除了异常强大的监控功能外,还提供了丰富的api接口,非常适合二次开发。Zabbix API是基于JSON-RPC 2.0规格调用API,本文主要是用于Python脚本。具体的API文档可以根据Zabbix版本选择API接口。官方API接口文档地址:https://www.zabbix.com/documentation/2.4/manual/api
调用API分为2个步骤:
1.获取认证,取得ac (authentication token)
curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"user.login","params":{"user":"登陆zabbix的用户名","password":"登陆zabbix的密码"},"id": 对应生成的acID号}' http://zabbix服务器IP地址/zabbix/api_jsonrpc.ph
实例:
curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"user.login","params":{"user":"Admin","password":"zabbix"},"id": 1}' http://192.168.1.1/zabbix/api_jsonrpc.ph
执行上面的命令后,返回值是:
HTTP/1.1 200 OK
Server: nginx/1.0.15
Date: Mon, 25 Jul 2016 11:10:54 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
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
{"jsonrpc":"2.0","result":"91cb1b0baf3ba8cad25eff48c42ccfe9","id":1}
其中,91cb1b0baf3ba8cad25eff48c42ccfe9就是我们的登陆密钥,id,1就是匹配的账号
2.实际应用,关闭Zabbix服务器上ID为3的action
curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"action.update","params":{"actionid":"3","status":"1"},"auth":"91cb1b0baf3ba8cad25eff48c42ccfe9钥","id": 1}' http://192.168.1.1/zabbix/api_jsonrpc.php
当反馈值为:
HTTP/1.1 200 OK
Server: nginx/1.0.15
Date: Mon, 25 Jul 2016 11:19:51 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
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
{"jsonrpc":"2.0","result":{"actionids":[3]},"id":1}
说明命令已经执行成功,可以把此命令添加到运行脚本中去,可以实现更多的自动化运维。更多的应用请查看API官方文档。
给出一个python的具体脚本:
#!/usr/bin/env python
# Encoding: utf-8
# Author:zhouli@chuangyoutech.com
# Description:
from __future__ import division
import threading
import urllib2
import getopt
import time
import json
import sys
import os
import commands
reload(sys)
sys.setdefaultencoding('utf-8')
cmdcode7="curl -i -X POST -H 'Content-Type:application/json' -d '{\"jsonrpc\": \"2.0\",\"method\":\"action.update\",\"params\":{\"actionid\":\"3\",\"status\":\"1\"},\"auth\":\"密钥\",\"id\": 对应匹配的id号}' http://zabbix服务器的IP地址/zabbix/api_jsonrpc.php"
def guan():
print commands.getoutput(cmdcode7)
guan()