python3 批量创建zabbix主机

一、简介

此程序是python调用zabbix API 批量创建监控主机的脚本。所有格式参考zabbix 官网API。地址如下:

https://www.zabbix.com/documentation/6.0/zh/manual/api/reference

二、创建zabbixAPI包

1.config.py

其中Get_token函数是为了获取访问zabbix API所需要的token.

import json,requests


zabbix_api = "http://xx.xx.xx.xx/zabbix/api_jsonrpc.php"
zabbix_user = "用户名"
zabbix_pass =  "密码"


header = {
    "Content-Type": "application/json"
}

requests_token_data = json.dumps({
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
        "user": zabbix_user,
        "password": zabbix_pass
    },
    "id": 1,
})

def Get_token():
    try:
        res = requests.post(zabbix_api,headers=header,data=requests_token_data)
        token = json.loads(res.text)["result"]
        return token

    except Exception:
        return "get token error"

2.get_template_info.py

函数的作用是根据模板名称,获取模板对应的模板id

import  requests,json
from . import config

token = config.Get_token()

def Get_template_info2(template_name):
    data = json.dumps({
            "jsonrpc": "2.0",
            "method": "template.get",
            "params": {
                "output": ["host","name","templateid"],
                "filter": {
                    "host": [
                        template_name
                    ]
                },
            },
            "auth": token,
            "id": 1

    })

    try:
        res = requests.post(config.zabbix_api,headers=config.header,data=data)
        return  json.loads(res.text)["result"]
    except Exception:
        return "get template info error !"

if __name__ == '__main__':
    mes = Get_template_info2("")
    print(mes)

3.get_groupid.py

此函数是根据主机组的名称,获取主机组的组ID

import json,requests
from . import config

token = config.Get_token()


def Get_groupid(group_name):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extent",
            "filter": {
                "name": [
                    group_name
                ]
            }
        },
        "auth": token,
        "id": 1
    })

    try:
        res = requests.post(config.zabbix_api,headers=config.header,data=data)
        groupid = json.loads(res.text)["result"][0]["groupid"]
        return groupid
    except Exception:
        return "get groupid error !"

4.create_host.py

此函数是在前两个函数的基础上 创建zabbix监控主机

import requests,json
from . import config

token = config.Get_token()


def Create_host(*args):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": args[0],
            "name": args[1],
            "interfaces": [
                {
                    "type": 1,
                    "main": 1,
                    "useip": 1,
                    "ip": args[4],
                    "dns": "",
                    "port": "10050"
                }
            ],
            "groups": [
                {
                    "groupid": args[2],
                }
            ],
            "templates": args[3],
        },
        "auth": token,
        "id": 1
    })

    try:
        res =  requests.post(config.zabbix_api,headers=config.header,data=data)
        return  json.loads(res.text)["result"]
    except Exception as err:
        return  err


5.create_macro.py

此函数是创建主机宏变量

import requests,json
from . import config

token = config.Get_token()

def Create_macro(hostid,key,value):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "usermacro.create",
        "params": {
            "hostid": hostid,
            "macro": key,
            "value": value,
        },
        "auth": token,
        "id": 1
    })

    try:
        res = requests.post(config.zabbix_api,headers=config.header,data=data)
        return  json.loads(res.text)["result"]
    except Exception:
        return "create usermacro error !"

三、main.py

import requests,json,csv
from zabbixApi import get_groupid,get_template_info,create_host,config,create_macro



#存放zabbix主机信息的csv文件名称
csvFile_name = "hostList.csv"


#存放所有主机信息的列表
host_list = []


with open("hostList.csv",'r') as f:
    dw = csv.reader(f)
    for i in dw:
        if i[0] != "主机名":
            host_list.append(i)

#检测每行内容是否存在空值
for k in host_list:
    for j in k:
        if len(j) == 0:
            print("{}存在空值,无法创建zabbix监控项".format(k))
            host_list.pop(host_list.index(k))

hostId_list = []

for item in host_list:
    if item[3].lower() == "windows":
        item[2] = get_groupid.Get_groupid(item[2])
        template = get_template_info.Get_template_info2("Windows by Zabbix agent simple")[0]["templateid"]
        item[3] = [{"templateid": template}]

        c_res = create_host.Create_host(*item)
        try:
            hostId_list.append(c_res["hostids"][0])
        except Exception as err:
            print(err)
            exit(111)

	#linux 主机需要两个模板,所以这里获取了两次不通linux主机的模板
    elif item[3].lower() == "linux":
        item[2] = get_groupid.Get_groupid(item[2])
        template1 = get_template_info.Get_template_info2("Linux by Zabbix agent_active_ custom")[0]["templateid"]
        template2 = get_template_info.Get_template_info2("tcp port discover")[0]["templateid"]
        item[3] = [{"templateid": template1},{"templateid": template2}]

        c_res = create_host.Create_host(*item)
        try:
            hostId_list.append(c_res["hostids"][0])
        except Exception as err:
            print(err)
            exit(111)
            
#这里是为主机添加主机宏
macro_key = "{$PROJECT}"
macro_key1 = "{$BPUSER}"
value = "测试医院"
value1 = "zhangsan"

#根据主机ID 为对应主机添加主机宏变量
for i in hostId_list:
    macor_res = create_macro.Create_macro(i,macro_key,value)
    print(macor_res)
    macor_res1 = create_macro.Create_macro(i,macro_key1,value1)
    print(macor_res1)

四、创建hostList.csv文件

文件格式如下:

主机名主机显示名称主机组操作系统IP地址
test1门诊服务APP测试医院应用服务器组linux192.168.1.1
test2门诊服务AP2测试医院应用服务器组linux192.168.1.2
test4测试服务器测试医院应用服务器组windows192.168.1.10
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Python调用Zabbix API批量查询主机的信息,您需要进行以下步骤: 1. 安装 `zabbix-api` 模块:您可以使用 `pip` 命令安装该模块,例如:`pip install zabbix-api` 2. 导入必要的库和模块: ```python from pyzabbix import ZabbixAPI import json ``` 3. 创建 `ZabbixAPI` 对象并登录: ```python zabbix_server = "http://zabbix.example.com" zabbix_user = "username" zabbix_password = "password" zapi = ZabbixAPI(url=zabbix_server, user=zabbix_user, password=zabbix_password) zapi.login() ``` 4. 使用 `host.get` 方法批量查询主机信息: ```python hosts = zapi.host.get(output=['hostid', 'host', 'name', 'status', 'ip']) ``` 此时,变量 `hosts` 将包含所有主机的信息。在这个示例中,我们查询了每个主机的 `hostid`、`host`、`name`、`status` 和 `ip` 信息。 5. 处理查询结果: ```python for host in hosts: print("Host ID:", host['hostid']) print("Host Name:", host['name']) print("Host Status:", host['status']) print("Host IP:", host['ip']) print("------------------------") ``` 以上代码将遍历每个主机,并打印出其 ID、名称、状态和 IP 地址。 完整代码示例: ```python from pyzabbix import ZabbixAPI import json zabbix_server = "http://zabbix.example.com" zabbix_user = "username" zabbix_password = "password" zapi = ZabbixAPI(url=zabbix_server, user=zabbix_user, password=zabbix_password) zapi.login() hosts = zapi.host.get(output=['hostid', 'host', 'name', 'status', 'ip']) for host in hosts: print("Host ID:", host['hostid']) print("Host Name:", host['name']) print("Host Status:", host['status']) print("Host IP:", host['ip']) print("------------------------") ``` 注意:在实际使用中,您可能需要根据具体情况修改查询的参数和返回结果的处理方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值