@zabbix监控主机批量接入web

1.py基础环境要求

编写Python脚本实现excel数据接入zabbix-server的Web页面

# 使用python3执行脚本
# 注意:由于xlrd新的模块(2.0.1版本)已不支持.xlsx文件,因此需要卸载当前版本的xlrd库,安装1.2.0版本即可。
pip uninstall xlrd  	    # 卸载当前版本
pip install xlrd==1.2.0 	# 安装1.2.0版本

2.脚本接口脚本

shell> vim zabbix_import_agent.py
import json
import requests
import xlrd
import urllib3

urllib3.disable_warnings()

url = "https://192.168.1.150/zabbix/api_jsonrpc.php"
username = "Admin"
passwd = "zabbix"
excel = "excel_agent.xlsx"

# Login API
login_headers = {'Content-Type': 'application/json-rpc'}
login = {
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
        "user": username,
        "password": passwd
    },
    "id": 1
}

token = requests.post(url, data=json.dumps(
    login), headers=login_headers, verify=False).json()
auth = token['result']


# Get Template ID
def template(auth, group_name_list):
    template_post = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": "extend",
            "filter": {
                "host": group_name_list
            }
        },
        "auth": auth,
        "id": 1
    }
    template_get, templateid = requests.post(url, data=json.dumps(
        template_post), headers=login_headers, verify=False).json(), []
    for id in template_get['result']:
        templateid.append({"templateid": id['templateid']})
    return templateid


# Get GROUP ID
def group(auth, group_name_list):
    group_post = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
            "filter": {
                "name": group_name_list
            }
        },
        "auth": auth,
        "id": 1
    }
    group_get, groupid = requests.post(url, data=json.dumps(
        group_post), headers=login_headers, verify=False).json(), []
    for id in group_get['result']:
        groupid.append({"groupid": id['groupid']})
    return groupid


# GET PROXY ID
def proxy(auth, proxy):
    proxy_post = {
        "jsonrpc": "2.0",
        "method": "proxy.get",
        "params": {
            "output": "extend",
            "selectInterface": "extend",
            "filter": {
                "host": proxy
            }
        },
        "auth": auth,
        "id": 1
    }
    proxy_get = requests.post(url, data=json.dumps(
        proxy_post), headers=login_headers, verify=False).json()
    return proxy_get['result'][0]['proxyid']


# Create Hosts
def create_host(hostname, display_name, proxy, method, ip, port, group, template, description, macros, inventory, tags,
                auth):
    create_host = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostname,
            "name": display_name,
            "proxy_hostid": proxy,
            "description": description,
            "interfaces": [
                {
                    "type": method,
                    "main": 1,
                    "useip": 1,
                    "ip": ip,
                    "dns": "",
                    "port": port
                }
            ],
            "groups": group,
            "templates": template,
            "macros": macros,
            "inventory_mode": 0,
            "inventory": inventory,
            "tags": tag
        },
        "auth": auth,
        "id": 1
    }
    print(create_host)
    create = requests.post(url, data=json.dumps(
        create_host), headers=login_headers, verify=False).json()
    return create


# Method_id Change To Number
def method(method_name):
    if method_name == "SNMP":
        method = [2, 161]
    elif method_name == "agent":
        method = [1, 10050]
    elif method_name == "IPMI":
        method = [3, 623]
    else:
        method = [4, 12345]
    return method


# Excel
excel_data = xlrd.open_workbook(excel)
excel_table = excel_data.sheets()[0]
excel_lines = excel_table.nrows        # 输出表格行数


# print(excel_table.ncols)            #输出表格列数
# print(excel_table.row_values(0))    #输出第一行
# print(excel_table.col_values(0))    #输出第一列


def macros(num):
    macros = []
    macro1, macro2, macro3, macro4, macro5, macro6 = [
        excel_table.cell(num, u).value for u in range(7, 13, 1)]
    for i in [macro1, macro2, macro3, macro4, macro5, macro6]:
        if i:
            macros.append(
                {"macro": "{$" + i.split(":")[0] + "}", "value": i.split(":")[1]})
    return macros


def tags(num):
    tag_fn = []
    tag = excel_table.cell(num, 27).value
    for x in tag.split(','):
        tag_fn.append({"tag": x.split(":")[0], "value": x.split(":")[1]})
    return tag_fn


def inventory(num):
    l1 = ["type", "contact", "site_rack", "site_city", "site_address_a", "date_hw_install", "date_hw_purchase", "os",
          "serialno_a", "asset_tag", "deployment_status", "date_hw_expiry", "software", "notes"]
    l2 = [excel_table.cell(num, i).value for i in range(13, 27)]
    inventory = {}
    for k in zip(l1, l2):
        inventory[k[0]] = k[1]
    return inventory


for i in range(2, excel_lines):
    hostname = excel_table.cell(i, 0).value  # 主机名
    ip = excel_table.cell(i, 1).value  # IP地址
    display_name = hostname + "_" + ip  # 可见名称
    proxy_id = proxy(auth, excel_table.cell(i, 3).value)  # ProxyID
    method_id = method(excel_table.cell(i, 2).value)  # 采集方法,0为方法,1为端口
    group_id = group(auth, excel_table.cell(i, 4).value.split(","))  # 组ID
    template_id = template(auth, excel_table.cell(
        i, 5).value.split(","))  # 模板ID
    description = excel_table.cell(i, 6).value  # 描述信息
    macros_list = macros(i)  # 宏
    inventory_list = inventory(i)
    tag = tags(i)
    create_step = create_host(hostname, display_name, proxy_id,
                              method_id[0], ip, method_id[1], group_id, template_id, description, macros_list,
                              inventory_list, tags, auth)
    if "error" in create_step:
        print("主机   " + hostname + "_" + ip +
              "\t\033[0;31;40m创建失败\033[0m\t错误消息:" + create_step["error"]["data"])
    else:
        print("主机   " + hostname + "_" + ip + "\t\033[1;32;40m创建成功\033[0m")

4.linux服务器执行

需要配置python3环境

host主机清单excel模板,文件名为excel_agent.xlsx:
【excel_agent.xlsx】

表格如下所示:

在这里插入图片描述

#py脚本执行
python3 zabbix_import_agent.py

3.使用pycharm执行

使用pycharm导入,环境如上使用Python3执行:

在这里插入图片描述

在这里插入图片描述

结果如下所示:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值