python3 批量添加 zabbix 主机,绑定主机群组

python3 批量添加 zabbix 主机,绑定主机群组

 

代码:

import requests
import json


# header
headers = {'Content-Type': 'application/json-rpc'}
# URL + /api_jsonrpc.php
zx_url = 'http://192.168.3.241/api_jsonrpc.php'
# 用户名
user = 'Admin'
# 密码
password = '******'
# 想要添加到什么组
host_groups = '测试'
# 端口
ports = '10050'
# 字典的形式传入 hostname 和 IP 地址
host_message = {'agent 01': '192.168.3.1',
                'agent 02': '192.168.3.2',
                'agent 03': '192.168.3.3',
                'agent 04': '192.168.3.4'
                }


# 登陆,获取用户身份验证令牌,每次登陆令牌都不一样。
def login_zabbix():
    data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": user,
            "password": password
        },
        "id": 1
    }

    r = requests.post(zx_url, headers=headers, data=json.dumps(data))
    result = r.json()
    auth = result['result']

    # 返回身份验证令牌
    return auth


# 获取需要的组的ID,后面添加主机通过组ID添加
def get_host_group():
    data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
            "filter": {
                "name": [
                    host_groups,  # 主机组的名字
                ]
            }
        },
        "auth": auth,  # 用户身份令牌
        "id": 1
    }

    r = requests.post(zx_url, headers=headers, data=json.dumps(data))
    result = r.json()
    group_id = result['result'][0]['groupid']

    # 返回组ID
    return group_id


# 添加主机
def add_agent(auth, group_id, host, ip):
    data = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": host,  # zabbix上显示的主机名字
            "interfaces": [
                {
                    "type": 1,
                    "main": 1,
                    "useip": 1,
                    "ip": ip,  # IP地址
                    "dns": "",
                    "port": ports  # 端口
                }
            ],
            "groups": [
                {
                    "groupid": group_id  # 组ID
                }
            ],
        },
        "auth": auth,  # 用户身份令牌
        "id": 1
    }

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

    # 成功输出host ID
    if 'result' in data:
        print('''\033[1;32m add %s success.
 hostid: %s \033[0m \n''' % (ip, data['result']['hostids'][0]))

    # 失败输出为什么
    if 'result' not in data:
        print('''\033[1;31m add %s is error!!!
 error code: %s
 error message: %s
 error data: %s \033[0m \n''' % (ip, data['error']['code'], data['error']['message'], data['error']['data']))


# 主程序
if __name__ == '__main__':
    # 获取令牌
    auth = login_zabbix()
    # 获取组ID
    group_id = get_host_group()

    # 添加主机
    for key in host_message:
        add_agent(auth, group_id, key, host_message[key])

  

使用说明(只需要更改这些地方的变量的值):

 

 

正确输出:

 

 错误输出:

 

 

 

posted @ 2021-11-29 16:15  江戸川のコナン  阅读(254)  评论(0编辑  收藏  举报
……