侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

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

zze
zze
2020-08-19 / 0 评论 / 0 点赞 / 744 阅读 / 5079 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

#!/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)

0

评论区