本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

调用API批量添加主机到Zabbix中

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:


#!/usr/bin/env python3
# encoding:utf-8

import json
import os
import socket
import struct
import sys

import requests


def get_ip_addr(ifeth):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        import fcntl
    except Exception as e:
        os.system("pip install fcntl")
        import fcntl
    return socket.inet_ntoa(
        fcntl.ioctl(
            s.fileno(), 0x8915, struct.pack("256s", bytes(ifeth[:15], "utf-8"))
        )[20:24]
    )


class zabbix_api(object):
    def __init__(self):
        self.url = "http://10.0.1.201/zabbix/api_jsonrpc.php"
        self.user = "Admin"
        self.passwd = "zabbix123"
        self.auth = self.login()

    def login(self):
        params = {
            "method": "user.login",
            "params": {"user": self.user, "password": self.passwd},
        }
        output = self.get_result_from_api(params)
        try:
            self.auth = output["result"]
            print("login Zabbix Server Sucesses!!")
            return self.auth
        except Exception as e:
            print("Login Zabbix Server Failed")

    def get_result_from_api(self, params):
        req_params = {"jsonrpc": "2.0", "id": 1}
        req_params.update(params)
        data = json.dumps(req_params).encode("utf-8")
        head = {"Content-Type": "application/json-rpc"}
        response = requests.post(self.url, data=data, headers=head)
        return response.json()

    def get_hostgroup_id(self, hostgroup):
        params = {
            "method": "hostgroup.get",
            "params": {"output": "extend", "filter": {"name": [hostgroup]}},
            "auth": self.auth,
            "id": 1,
        }
        output = self.get_result_from_api(params)
        try:
            groupid = output["result"][0]["groupid"]
            return groupid
        except Exception as e:
            print("get hostgroup is Null")

    def get_templates_id(self, template_name=["gm-Base"]):
        params = {
            "method": "template.get",
            "params": {"output": "extend", "filter": {"host": template_name}},
            "id": 1,
            "auth": self.auth,
        }
        output = self.get_result_from_api(params)
        templateid_list = list()
        try:
            for i in output["result"]:
                templateid_list.append(i["templateid"])
            return templateid_list
        except Exception as e:
            print("get templateid is Null")

    def auto_join_zabbix(self, hostname, ipaddr, hostgroup, templeate_list):
        '''
        :param hostname: 主机名
        :param ipaddr: IP
        :param hostgroup: 主机组
        :param templeate_list: 使用的模板
        :return:
        '''
        hostgroup_id = self.get_hostgroup_id(hostgroup)
        template_id_list = self.get_templates_id(templeate_list)
        format_template_id_list = list()
        for i in template_id_list:
            format_template_id_list.append({"templateid": i})
        params = {
            "method": "host.create",
            "params": {
                "host": hostname,
                "interfaces": [
                    {
                        "type": 1,
                        "main": 1,
                        "useip": 1,
                        "ip": ipaddr,
                        "dns": "",
                        "port": "10050",
                    }
                ],
                "groups": [{"groupid": hostgroup_id}],
                "templates": format_template_id_list,
                "inventory_mode": 0,
            },
            "auth": self.auth,
            "id": 1,
        }
        output = self.get_result_from_api(params)
        try:
            print("Host ID:", output["result"]["hostids"])
        except Exception as e:
            print("create host is failed")


if __name__ == "__main__":
    default_template = [
        "Template OS Linux Active",
    ]

    zbx = zabbix_api()
    # ipaddr = get_ip_addr("ens3")
    # hostname = socket.gethostname()

    host_prefix = sys.argv[1]
    hostname = sys.argv[2]
    ipaddr = sys.argv[3]

    if host_prefix == '':
        host_group = 'virtual'
    else:
        host_group = host_prefix
        hostname = '{}_{}'.format(host_prefix, hostname)
    
    zbx.auto_join_zabbix(hostname, ipaddr, host_group, default_template)


如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×