zabbix api调用

zabbix api调用

api能干什么

Zabbix API allows you to programmatically retrieve and modify the configuration of Zabbix and provides access to historical data.
It is widely used to:

  • Create new applications to work with Zabbix;
  • Integrate Zabbix with third party software;
  • Automate routine tasks.

我自己的理解就是可以通过编程的方法操作zabbix,比如说创建主机啊,创建图形等,当然不只是创建,增删改查基本都支持。

api的协议

用php创建的基于了JSON-RPC 2.0
意味着api的请求和回复格式都是用json编码

python编写程序调用api

需要调用的模块

  1. urllib2
  2. json

步骤大致分为两步,

认证,取得ac (authentication token)

{
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
        "user": "Admin",
        "password": "zabbix"
    },
    "id": 1,
    "auth": null
}

返回是

{
    "jsonrpc": "2.0",
    "result": "0424bd59b807674191e7d77572075f33",
    "id": 1
}

发送api 请求主体。

{
    "jsonrpc": "2.0",
    "method": "host.get",
    "params": {
        "output": [
            "hostid",
            "host"
        ],
        "selectInterfaces": [
            "interfaceid",
            "ip"
        ]
    },
    "id": 2,
    "auth": "0424bd59b807674191e7d77572075f33"
}

返回:

{
    "jsonrpc": "2.0",
    "result": [
        {
            "hostid": "10084",
            "host": "Zabbix server",
            "interfaces": [
                {
                    "interfaceid": "1",
                    "ip": "127.0.0.1"
                }
            ]
        }
    ],
    "id": 2
}

用程序写就是

python示例

import urllib2
import json
zabbix_url="http://zabbix.xxx.com/api_jsonrpc.php"
api_pass='xxxx'
auth_data={ 'jsonrpc':'2.0','method':'user.login','params':{'user':'api','password':api_pass},'id':1}
#auth function
def get_auth():
        request=urllib2.Request(zabbix_url,json.dumps(auth_data))
        request.add_header('Content-Type','application/json')
        response=urllib2.urlopen(request)
        var1=json.loads(response.read())
        return var1['result']

#get auth session
session=get_auth()

json请求照着api的文档https://www.zabbix.com/documentation/2.2/manual/api里面抄就行了。注意一下zabbix版本,2.0,2.2和2.4的api请求内容都是不一样的。

id 顺序递增,下一次api请求的id就是2了。用urllib2.urlopen 就 可以了。关于urllib2的用法,可以参看我之前的文章。python urllib2模块

你可能感兴趣的:(python,zabbix)