Zabbix学习笔记(五)---调用API接口实例

简介:

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()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值