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 测试医院应用服务器组 linux 192.168.1.1
test2 门诊服务AP2 测试医院应用服务器组 linux 192.168.1.2
test4 测试服务器 测试医院应用服务器组 windows 192.168.1.10

你可能感兴趣的:(python,zabbix,linux,运维)