Zabbix API 使用详解 (Python)

1.Zabbix API是基于前端HTTP协议实现的,数据格式采用JSONRPC协议,格式如下:

{"method": "host.get", "params": { xxx: xxx }, "id": 1}

参数说明:

  • method:调用的方法名。
  • params:方法传入的参数,若无参数,则传入[]。
  • id:调用标识符,用于标识一次远程调用过程。
    服务器接收到JSON-RPC的调用请求后,处理该请求的方法调用,然后将结果返回调用方。

2.返回的数据格式如下:

{   
    "result": "xxxxxx", 
    "error": null, 
    "id": 1
} 

参数说明如下:

  • result:方法返回值,无返回值或调用出错返回null。
  • error:调用时发生错误,无错误返回null。·
  • id:调用标识符,与调用方传入的标识符一致。

3.Zabbix API支持的数据类型

基本类型
Type Description
bool 布尔值为true或者false
flag 当该值不等于空或者false时,被认为是true
integer 整数
float 浮点数
string 文本字符串
timestamp UNIX 时间戳
array 数组
object 关联数组
query 可以是一个数值,也可以是部分参数· extend:返回所有的对象值· count:返回值的数量

使用查询操作(get方法)时,可以使用更多的参数

Parameter Type Description
countOutput flag 返回结果的个数,而非实际的数据
editable boolean 如果设置为true,用户可对返回的对象进行写操作。默认值为false
excludeSearch flag 返回不匹配给定参数的结果
filter object 返回过滤后的结果,参数的值可以为一个数组或者单个值,text字段不能使用此参数
limit integer 限制返回结果的数量
nodeids string/array 返回给定节点的对象信息
output query 返回对象的属性。默认值为extend
preservekeys flag 返回以ID为键的数组
search object 搜索匹配的字符串,仅用于字符和文本字段
searchByAny boolean 如果设置为true,则返回 filter 或search字段中所有的值。默认值为false
searchWildcardsEnabled boolean 如果设置为true,允许使用“*”作为搜索参数的通配符。默认值为false
sortfield string/array 对给定的参数属性进行排序
sortorder string/array 排序。ASC为升序排列;DESC为降序排列
startSearch flag 搜索以某个参数开始的结果

实例:

1. python脚本调用zabbix api的一些操作

# -*- coding: utf-8 -*-
import json
import urllib.request, urllib.error, urllib.parse

class ZabbixAPI:
    def __init__(self):
        self.__url = 'http://192.10.10.91/api_jsonrpc.php'
        self.__user = 'Admin'
        self.__password = 'zabbix'
        self.__header = {"Content-Type": "application/json-rpc"}
        self.__token_id = self.UserLogin()

#登陆获取token
    def UserLogin(self):
        data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
            "user": self.__user,
            "password": self.__password
            },
            "id": 0,
        }
        return self.PostRequest(data)

#推送请求
    def PostRequest(self, data):
        request = urllib.request.Request(self.__url,json.dumps(data).encode('utf-8'),self.__header)
        result = urllib.request.urlopen(request)
        response = json.loads(result.read().decode('utf-8'))
        try:
            #print response['result']
            return response['result']
        except KeyError:
            raise KeyError

 #主机列表
    def HostGet(self,hostid=None,hostip=None):
        data = {
            "jsonrpc":"2.0",
            "method":"host.get",
            "params":{
                "output":"extend",
                "selectGroups": "extend",
                "selectParentTemplates": ["templateid","name"],
                "selectInterfaces": ["interfaceid","ip"],
                "selectInventory": ["os"],
                "selectItems":["itemid","name"],
                "selectGraphs":["graphid","name"],
                "selectApplications":["applicationid","name"],
                "selectTriggers":["triggerid","name"],
                "selectScreens":["screenid","name"]
            },
            "auth": self.__token_id,
            "id":1,
        }
        if hostid:
            data["params"]={
                "output": "extend",
                "hostids": hostid,
                "sortfield": "name"
            }
        return self.PostRequest(data)

 #主机列表
    def HostCreate(self,hostname,hostip,groupid=None,templateid=None):
        data = {
            "jsonrpc":"2.0",
            "method":"host.create",
            "params": {
                "host": hostname,
                "interfaces": [
                    {
                    "type": 1,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": "10050"
                    }
                ],
                "groups": [
                    {
                    "groupid": groupid
                    }
                ],
                "templates": [
                    {
                    "templateid": templateid
                    }
                ]
            },
            "auth": self.__token_id,
            "id":1,
        }
        return self.PostRequest(data)

 #主机组列表
    def HostGroupGet(self,hostid=None,itemid=None):
        data = {
            "jsonrpc":"2.0",
            "method":"hostgroup.get",
            "params":{
                "output": "extend",
                "hostids": hostid,
                "itemids": itemid,
                "sortfield": "name"
            },
            "auth": self.__token_id,
            "id":1,
        }
        return self.PostRequest(data)

 #监控项列表
    def ItemGet(self,hostid=None,itemid=None):
        data = {
            "jsonrpc":"2.0",
            "method": "item.get",
            "params": {
                "output": "extend",
                "hostids": hostid,
                "itemids": itemid,
                "sortfield": "name"
            },
            "auth": self.__token_id,
            "id":1,
        }
        return self.PostRequest(data)


 #模板列表
    def TemplateGet(self, hostid=None,templateid=None):
        data = {
            "jsonrpc":"2.0",
            "method": "template.get",
            "params": {
                "output": "extend",
                "hostids": hostid,
                "templateids": templateid,
                "sortfield": "name"
            },
            "auth": self.__token_id,
            "id":1,
        }
        return self.PostRequest(data)

 #图像列表
    def GraphGet(self,hostid=None,graphid=None):
        data = {
            "jsonrpc":"2.0",
            "method": "graph.get",
            "params": {
                "output": "extend",
                "hostids": hostid,
                "graphids": graphid,
                "sortfield": "name"
            },
            "auth": self.__token_id,
            "id":1,
        }
        return self.PostRequest(data)


 #历史数据
    def History(self,itemid,data_type):
        data = {
            "jsonrpc": "2.0",
            "method": "history.get",
            "params": {
                "output": "extend",
                "history": data_type,
                "itemids": itemid,
                "sortfield": "clock",
                "sortorder": "DESC",
                "limit": 30
            },
            "auth": self.__token_id,
            "id": 2
        }
        return self.PostRequest(data)

#测试:python manager.py shell ; from ZABBIX.ZabbixAPI import * ; main(),代码修改了要ctrl+Z退出重进
def main():
    zapi=ZabbixAPI()
    token=zapi.UserLogin()
    print('token is',token)
    hosts=zapi.HostGet()
    print('hosts info is',hosts)
    #[{u'host': u'Zabbix server', u'hostid': u'10084', u'interfaces': [{u'interfaceid': u'1', u'ip': u'127.0.0.1'}]}]
    hostgroups=zapi.HostGroupGet(hostid=10084)
    print('hostgroups is',hostgroups)
    #zapi.xxx() ......
if __name__ == '__main__':
    main()

2.,Zabbix可以根据CMDB里面信息自动Link相关的模块,添加|删除监控。很多小的公司没有资产管理系统,可以通过扫描网段ip和zabbix api取到的主机ip做对比来判断添加删除监控

1)通过Nmap工具扫描网段,扫描出已经使用的IP地址。
2)通过Nmap检测已经扫描IP的3389或者22端口是否开放,可以判断那些事windows机器,那些是Linux机器。
3)Linux下面通过ssh + hostname命令找出Linux主机名。
4)Windows下面通过nmblookup -A 命令找出Windows主机名。
5)用Python脚本读扫描结果文件,把主机名写到列表里面。
6)用Zabbix python API 调用已经监控的主机名,写到列表里面。
7)两个列表取交集,用for循环判断哪些主机名没有监控。
8)发邮件通知监控负责人。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys
import json
import urllib2
import datetime,time
from urllib2 import URLError

#scan_machine.sh是调用的Shell写的关于Nmap扫描的脚本,scan_hostname.log是Nmap扫描的结果,里面内容是IP 主机名。
nmap_cmd = "/shell/machine/scan_machine.sh"


def runCmd(command):
    global mail_cmd
    mail_cmd = '''mail -s "Report on not monitor Hosts of Zabbix" [email protected] < /shell/machine/result/result.txt'''
    return os.system(command)

runCmd(nmap_cmd)


def nmap_host():
    hostiplst = []
    hostnamelst = []
    f = file('/shell/machine/result/scan_hostname.log','r')
    for line in f.readlines():
        hostip = line.split()[0]
        hostname = line.split()[1]
        hostiplst.append(hostip)
        hostnamelst.append(hostname)
    hostnamelst.sort()
    #print hostiplst
    return hostnamelst
    f.close()


def zabbix_host():
    zabbixhostlst= []
    #based url and required header
    url = "http://192.168.161.128/api_jsonrpc.php"
    header = {"Content-Type": "application/json"}
    #request json
    data = json.dumps(
    {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params":{
            "output":["hostid","name"],
            "filter":{"host":""}
        },
        #auth id
        "auth":"Zabbix Auth ID",
        "id": 1,
    })

    #create request object
    request = urllib2.Request(url,data)
    for key in header:
        request.add_header(key,header[key])
    #get host list
    try:
        result = urllib2.urlopen(request)
    except URLError as e:
        print "The server could not fulfill the request.",e.reason
    else:
        reponse = json.loads(result.read())
        result.close()

    #print "Number of Hosts:",len(reponse['result'])
    for host in reponse['result']:
    #print "Host ID:",host['hostid'],"Host Name:",host['name']
        zbxhosts=host['name']
        zabbixhostlst.append(zbxhosts)
    zabbixhostlst.sort()
    return zabbixhostlst


def main():
    nmaphostlst = nmap_host()
    zbxhostlst = zabbix_host()
    # diff取两个列表不重复的部分,即未监控的host
    diff = list(set(nmaphostlst) ^ set(zbxhostlst))
    content = "\n"
    nomonitorlst = []
    if len(diff) != 0:
        for host in diff:
            if host in nmaphostlst:
                nomonitorlst.append(host)
            else:
                sys.exit()

    #print zbxhostlst
    string = '\n'.join(nomonitorlst)
    f = file('/shell/machine/result/result.txt','w')
    f.write(string)
    f.flush()
    f.close()
    runCmd(mail_cmd)

if __name__ == "__main__":
    main()

你可能感兴趣的:(Zabbix监控,Python,模块,脚本,json,zabbix,api)