python创建zabbix主机

37 篇文章 1 订阅
15 篇文章 0 订阅
#!/usr/bin/python
# encoding: utf-8
#filename: host_create.py
#author: gaohaixiang
#writetime:20190713

import zabbix_base_api  # zabbix-API-自定义库
import time

z_api_con = zabbix_base_api.zabbix_base_api(url='http://192.168.73.9/api_jsonrpc.php')

def getHostid(method,ip,authid):
    data = {
        "output": ["hostid", "host"],
        "filter": {
            "ip": ip
        },
        "selectInterfaces": ["ip"],
        "selectParentTemplates": ["name"]

    }
    responses = z_api_con.json_data(method, data, authid)
    return responses

def hostCreate(method,ip,authid):
    data = {
        "host": ip,
        "proxy_hostid": 16980,  #主机所走的代理
        "interfaces": [
            {
                "type": 1,
                "main": 1,
                "useip": 1,
                "ip": ip,
                "dns": "",
                "port": "10050"
            },
            # {                     #网络设备,SNMP
            #     "type": 2,
            #     "main": 1,
            #     "useip": 1,
            #     "ip": ip,
            #     "dns": "",
            #     "port": "161"
            # }
        ],
        "groups": [
            {
                "groupid": 2    #主机所在的组
            }
        ],
        "templates": [
            {
                "templateid": 15918 #主机需要添加的模板
            }
        ]
    }

    responses = z_api_con.json_data(method, data, authid)
    return responses

def main_all(authid):
    file = open("iplist.txt", "r")
    add_file = open("host-create.txt","a+")
    lists = file.readlines()
    print (lists)
    iplist = []
    for list in lists:
        ip = list.strip("\n")

#判断主机是否存在,存在将hostid和ip写入文件,不存在则创建,将IP写入文件
        hostget = getHostid("host.get",ip,authid)["result"]
        #print(hostget)
        if hostget:
            hostid = hostget[0]["hostid"]
            host = hostget[0]["host"]
            add_file.writelines(hostid+"\t"+host+"\n")
        else:
            hostcreate = hostCreate("host.create",ip,authid)
            print(hostcreate)
            add_file.writelines(ip+"\n")

    add_file.close()
    file.close()

if __name__ == "__main__":
    starttime = time.time()
    print ("Process is running...")
    authid = z_api_con.authid('gaohaixiang', 'gaohaixiang')
    main_all(authid)
    z_api_con.login_out(authid)
    endtime = time.time()
    print (endtime-starttime)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值