添加一台主机上去

import json
import requests
import sys

zabbix_url = "http://zabbix.example.com/api_jsonrpc.php"
zabbix_user = "Admin"
zabbix_password = "Password"
header = {'Content-Type': 'application/json'}

#发送post请求,返回字典形式
def SendPost(data):
    try:
        result = requests.post(url=zabbix_url,data=json.dumps(data),headers=header)
    except Exception as e:
        print("发送post请求失败!错误:{}".format(e))
        sys.exit()
    return json.loads(result.text)


#获取用户令牌
def GetUserToken():
    data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": zabbix_user,
                "password": zabbix_password,
            },
            "id": 1,
        }
    result = SendPost(data=data)
    return result.get("result")

#获取主机组Linux servers的id
def GetGostGroupID():
    user_token = GetUserToken()
    data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
            "filter": {
                "name": [
                    "Linux servers"
                ]
            }
        },
        "auth": user_token,
        "id": 1
    }
    result = SendPost(data=data)
    return result.get("result")[0].get("groupid")

#获取模板template OS Linux的id
def GetTemplateID():
    user_token = GetUserToken()
    data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": "extend",
            "filter": {
                "host": [
                    "Template OS Linux"
                ]
            }
        },
        "auth": user_token,
        "id": 1
    }
    result = SendPost(data=data)
    return result.get("result")[0].get("templateid")

#创建监控主机
def AddHost(hostname,hostip):
    user_token = GetUserToken()
    host_group_id = GetGostGroupID()
    template_id = GetTemplateID()
    data = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostname,
            "interfaces": [
                {
                    "type": 1,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": "10050"
                }
            ],
            "groups": [
                {
                    "groupid": host_group_id
                }
            ],
            "templates": [
                {
                    "templateid": template_id
                }
            ],
        },
        "auth": user_token,
        "id": 1
    }
    result = SendPost(data=data)
    if "error" not in result:
        print("服务器{}添加成功".format(hostip))
    else:
        print("服务器{}添加失败".format(hostip))

if __name__ == "__main__":
    hostname = input("服务器名称(避免中文字符): ")
    hostip = input("服务器ip地址: ")
    AddHost(hostname=hostname,hostip=hostip)

总结:后续可以结合Django或者Flask,结合数据库,可以在web端添加机器,目前还可以继续扩展

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://kkxl95.cn/article/1597824332/