zabbix常用api

本文介绍了Zabbix监控系统中常用的API操作,包括如何使用内置API以及集成第三方插件进行监控和管理。通过这些API,可以实现自动化配置、数据获取和报警等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

zabbix自带api

#!/usr/bin/python
#coding:utf-8

import requests
import json

url = "http://192.168.99.14/zabbix/api_jsonrpc.php"
headers = {"Content-Type": "application/json-rpc"}

def login_zabbix():
    data = {
        "jsonrpc":"2.0",
        "method":"user.login",
        "id":1,
        "auth":None,
        "params": {
                "user": "Admin",
                "password": "zabbix"
        }
    }

    r = requests.post(url, data = json.dumps(data), headers = headers)

    _content = json.loads(r.content)
    return _content['result']

def create_hostgoup():
    _auth = login_zabbix()
    data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.create",
        "params": {
            "name": "reboot"
        },
        "auth": _auth,
        "id": 1
    }

    r = requests.post(url, data=json.dumps(data), headers=headers)
    _content = json.loads(r.content)
    print _content

def get_goupid():
    _auth = login_zabbix()
    data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
            "filter": {
                "name": [
                    "reboot"
                ]
            }
        },
        "auth": _auth,
        "id": 1
    }
    r = requests.post(url, data=json.dumps(data), headers=headers)
    _content = json.loads(r.content)
    return _content['result'][0]['groupid']


def get_templateid():
    _auth = login_zabbix()
    data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": "extend",
            "filter": {
                "host": [
                    "Template OS Linux",
                ]
            }
        },
        "auth": _auth,
        "id": 1
    }
    r = requests.post(url, data=json.dumps(data), headers=headers)
    _content = json.loads(r.content)
    return _content['result'][0]['templateid']

def create_host(_host_list):
    _auth = login_zabbix()
    _groupid = get_goupid()
    _templdateid = get_templateid()


    for _host in _host_list:
        data = {
            "jsonrpc": "2.0",
            "method": "host.create",
            "params": {
                "host": _host['host'],
                "interfaces": [
                    {
                        "type": 1,
                        "main": 1,
                        "useip": 1,
                        "ip": _host['ip'],
                        "dns": "",
                        "port": "10050"
                    }
                ],
                "groups": [
                    {
                        "groupid": _groupid
                    }
                ],
                "templates": [
                    {
                        "templateid": _templdateid
                    }
                ],
                "inventory_mode": 0,
                "inventory": {
                    "macaddress_a": "01234",
                    "macaddress_b": "56768"
                }
            },
            "auth": _auth,
            "id": 1
        }
        r = requests.post(url, data=json.dumps(data), headers=headers)
        _content = json.loads(r.content)
        print _content['result']['hostids']


if __name__ == "__main__":
    _host_list = [
        {"ip": "192.168.99.10", "host": "reboot-devops-02"},
        {"ip": "192.168.99.11", "host": "reboot-ms-web-01"},
        {"ip": "192.168.99.12", "host": "reboot-ms-web-02"},
        {"ip": "192.168.99.13", "host": "reboot-ms-web-03"}
    ]
    create_host(_host_list)

第三方插件

#!/usr/bin/python
# coding:utf-8
from flask import current_app
from zabbix_client import ZabbixServerProxy
from app.models import Zbhost, Server
from app import db

class Zabbix(object):
    def __init__(self):
        self.url = current_app.config.get('ZABBIX_API_URL')
        self.username = current_app.config.get('ZABBIX_API_USER')
        self.password = current_app.config.get('ZABBIX_API_PASS')
        self._login()

    def _login(self):
        self.zb = ZabbixServerProxy(self.url)
        self.zb.user.login(user=self.username, password=self.password)

    def __del__(self):
        self.zb.user.logout()

    def get_hostgroup(self):
        return self.zb.hostgroup.get(output=['groupid', 'name'])

    def _create_host(self, params):
        try:
            return self.zb.host.create(**params)
        except Exception,e:
            return e.args

    def create_zb_host(self, hostname, ip, groupid = 2):
        """
        创建zabbix监控主机
        :param hostname:
        :param ip:
        :param groupid:
        :return:
        """
        data = {"host": hostname,
            "interfaces": [
                              {
                                  "type": 1,
                                  "main": 1,
                                  "useip": 1,
                                  "ip": ip,
                                  "dns": "",
                                  "port": "10050"
                              }
                          ],
            "groups": [
                {
                    "groupid": groupid
                }
            ]
        }
        return self._create_host(data)

    def get_hosts(self):
        return self.zb.host.get(output=["hostid", "host"])

    def get_interfaces(self, ids):
        """
        获取host的ip
        :param ids:
        :return:
        """
        interface = self.zb.hostinterface.get(hostids = ids, output = ["hostid", "ip"])
        ret = {}
        for _it in interface:
            ret[_it['hostid']] = _it['ip']
        return ret

    def get_templates(self, ids):
        return self.zb.template.get(hostids = ids, output = ["templateid", "name"])

    # 接触模板绑定
    def unlink_template(self, hostid, templateid):
        templates = [{"templateid" : templateid}]
        return self.zb.host.update(hostid = hostid, templates_clear = templates)

    # 新增模板,就是查出原来有的模板,然后拼接最新的模板,一起更新为当前的模板
    def replace_template(self, hostid, templateids):
        templates = []
        for id in templateids:
            templates.append({"templateid":id})
        try:
            ret = self.zb.host.update(hostid=hostid,templates = templates)
            return ret
        except Exception as e:
            return e.args

def rsync_zabbix_to_zbhost():
    """
    将zabbix里的host信息同步到zbhost里
    :return:
    """
    zb = Zabbix()
    # 1 从zabbix里取出所有的host信息
    zabbix_hosts = zb.get_hosts()
    zabbix_hosts_interface = zb.get_interfaces([z['hostid'] for z in zabbix_hosts])
    commit = False
    for host in zabbix_hosts:
        h = db.session.query(Zbhost).filter_by(hostid = host['hostid']).all()
        if h:
            continue
        host['ip'] = zabbix_hosts_interface[host['hostid']]
        db.session.add(Zbhost(**host))
        commit = True
    if commit:
        db.session.commit()

def rsync_server_to_zbhost():
    """
        同步cmdb server的数据到缓存表zbhost
    """
    hosts = db.session.query(Zbhost).all()
    servers = db.session.query(Server).filter(Server.inner_ip.in_([h.ip for h in hosts])).all()

    server_info = {}
    for s in servers:
        server_info[s.inner_ip] = s.id

    for h in hosts:
        if not h.cmdb_hostid:
            db.session.query(Zbhost).filter(Zbhost.id == h.id).update({"cmdb_hostid":server_info[h.ip]})
            db.session.commit()

"""
    取出zabbix中主机和模板信息
"""
def get_zabbix_data(hosts):
    zabbix_data = db.session.query(Zbhost).filter(Zbhost.cmdb_hostid.in_([h['id'] for h in hosts])).all()
    zb = Zabbix()
    ret = []
    for zb_host in zabbix_data:
        tmp = {}
        tmp["hostname"] = zb_host.host
        tmp["templates"] = zb.get_templates(zb_host.hostid)
        tmp["hostid"] = zb_host.hostid
        ret.append(tmp)

    return ret

# 连接模板
def zabbix_link_template(hostids, templateids):
    ret = []
    zb = Zabbix()
    for hostid in hostids:
        linked_template_ids = [t['templateid'] for t in zb.get_templates(hostid)]
        linked_template_ids.extend(templateids)
        ret.append(zb.replace_template(hostid, linked_template_ids))

    return ret

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值