在Python3.8环境中调用zabbix API批量添加主机和用户群组

一、基础环境

        运行环境:python3.8

        Zabbix版本:5.0

        默认读者对python和zabbix API 有一定了解。因为项目需求,将功能进行了拆分,添加主机与添加用户群组分开为两个脚本。可根据需要自行整合或添加功能。

二、实现功能

        读取Excel表格,批量添加主机,链接的模版必须存在,会将添加失败的用户群组名输出到日志文件./fail_addHost.txt中。

proxyName可见主机名服务器IP(主机名)用途(描述)主机群租完整名(换行符分隔)模版完整名(换行符分隔)
127.0.0.1AAAA172.16.40.79著丛1test
test1
Template DB PostgreSQL
Template Module Generic SNMP
127.0.0.1BBBBB172.16.41.88著丛2testTemplate App Apache by HTTP
127.0.0.1CCCCC172.16.42.79NullwindowsTemplate App FTP Service
127.0.0.1DDDD172.16.43.88九歌centos6Template App FTP Service
127.0.0.1CDA192.168.100.12天行ubuntuTemplate App FTP Service
Template OS Solaris
      

        上代码:

# !/usr/bin/env python3
# coding:utf-8
# Author: Nieen
import json
from urllib.request import Request
from urllib.request import urlopen
from urllib.error import HTTPError
import pandas as pd
import time


class zabbixtools:
    def __init__(self):
        # zabbix前端访问UERL
        self.url = "http://192.168.100.134/api_jsonrpc.php"
        self.header = {"Content-Type": "application/json"}
        # zabbix具有读写权限的可登陆账号密码
        # 527d6424e802a2b22bbcffcc0da481c5
        self.authID = self.user_login("Admin", "zabbix")

    def user_login(self, user, password):
        data = bytes(json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "user.login",
                "params": {
                    "user": user,
                    "password": password
                },
                "id": 0
            }), "utf-8")
        request = Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
        try:
            result = urlopen(request)
        except HTTPError as e:
            print("Auth Failed, Please Check Your Name And Password:", e.code)
        else:
            response = json.loads(result.read().decode('utf8'))
            result.close()
            authID = response['result']
            return authID

    def get_data(self, data):
        formData = bytes(data, 'utf-8')
        request = Request(self.url, formData)
        for key in self.header:
            request.add_header(key, self.header[key])
        try:
            result = urlopen(request)
        except HTTPError as e:
            if hasattr(e, 'reason'):
                print('We failed to reach a server.')
                print('Reason: ', e.reason)
            elif hasattr(e, 'code'):
                print('The server could not fulfill the request.')
                print('Error code: ', e.code)
            return 0
        else:
            response = json.loads(result.read().decode('utf-8'))
            result.close()
            return response

    def host_get(self, hostip):
        # hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
        data = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": {
                    "output": ["hostid", "name", "status", "host"],
                    "filter": {
                        "host": [hostip]}
                },
                "auth": self.authID,
                "id": 1
            })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # print(type(res))

            # for host in res:
            host = res[0]
            # if hostip == host['hostip']:
            return host['hostid']
        else:
            return ""

    def hostgroup_get(self, hostgroupName):
        data = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "hostgroup.get",
                "params": {
                    "output": "extend",
                    "filter": {
                        "name": [  # 列表格式,可多个
                            hostgroupName
                        ]
                    }
                },
                "auth": self.authID,
                "id": 1
            })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # print(type(res))
            # for host in res:
            host = res[0]
            return host['groupid']
        else:
            return ""

    def hostgroup_create(self, hostgroupName):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "hostgroup.create",
            "params": {
                "name": hostgroupName
            },
            "auth": self.authID,
            "id": 1
        })
        res = self.get_data(data)['result']

        if (res != 0) and (len(res) != 0):
            # for host in res:
            # print(type(res))
            # print res['hostids'][0]
            return res['groupids'][0]
        else:
            return ""

    def template_get(self, templateName):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "template.get",
            "params": {
                "output": "extend",
                "filter": {
                    "host": [
                        templateName
                    ]
                }
            },
            "auth": self.authID,
            "id": 1,
        })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # for host in res:
            # print(type(res))
            host = res[0]
            return host['templateid']
        else:
            return ""

    def proxy_get(self, proxyName):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "proxy.get",
            "params": {
                "output": "extend",
                "selectInterface": "extend"
            },
            "auth": self.authID,
            "id": 1,
        })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # print(type(res))

            for proxyHost in res:
                # proxyHost = res[0]
                if proxyName == proxyHost['host']:
                    return proxyHost['proxyid']
        else:
            return ""

    def user_get(self, userName):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "user.get",
            "params": {
                "output": "extend",
            },
            "auth": self.authID,
            "id": 1,
        })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # print(type(res))

            for proxyHost in res:
                # proxyHost = res[0]
                if userName == proxyHost['name']:
                    return proxyHost['userid']
        else:
            return ""

    def usergroup_get(self, usergroupName):
        pass

    def user_create(self, userName):
        pass

    def host_create(self, proxyID, visibleName, hostIP, hostgroupsidList, description, templateList):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.create",
            "params": {
                "host": hostIP,
                "name": visibleName,
                "proxy_hostid": proxyID,
                "description": description,
                "interfaces": [
                    {
                        "type": 1,
                        "main": 1,
                        "useip": 1,
                        "ip": hostIP,
                        "dns": '',
                        "port": "10050"
                    }
                ],
                "groups": hostgroupsidList,
                "templates": templateList,
            },
            "auth": self.authID,
            "id": 1
        })
        print("============")
        # ss = self.host_get(hostIP)
        # print(self.get_data(data))
        # print(self.get_data(data))

        # print(type(res))
        res = self.get_data(data)
        if "result" in res:
            print(res['result'])
            return res['result']['hostids'][0]
        elif "error" in res:
            # 打开一个文件
            f = open("./fail_addHost.txt", "a+")
            localtime = time.asctime(time.localtime(time.time()))
            log = localtime + "[主机] " + hostIP + ": " + res['error']['data'] + "\n"
            f.write(log)
            # 关闭打开的文件
            f.close()


if __name__ == "__main__":
    test = zabbixtools()
    excelPath = r'./files/addHost.xlsx'
    df = pd.read_excel(excelPath, sheet_name=0, header=0).fillna(method='pad')
    for row in range(df.__len__()):
        proxyName = df.iloc[row][0]
        visiblename = df.iloc[row][1]
        hostip = df.iloc[row][2]  # =hostname
        description = df.iloc[row][3]
        # print(description)
        if description == "Null":
            description = ""
        hostgroupName = df.iloc[row][4]
        # print(hostgroupName)
        templateName = df.iloc[row][5]
        # print(templateName)
        proxyid = test.proxy_get(proxyName)
        # print(proxyid)
        groupsidlist = []
        for indexGroup in hostgroupName.split('\n', -1):
            groupsid = test.hostgroup_get(indexGroup)
            # print(groupsid)
            if groupsid == "":
                # print(indexGroup, "00000000")
                groupsid = test.hostgroup_create(indexGroup)
                # print(groupsid)

            groupsidlist.append({"groupid": groupsid})

        print(groupsidlist)
        hosttempidlist = []
        for indexTempate in templateName.split('\n', -1):
            hosttempidid = test.template_get(indexTempate)
            # print(hosttempidid)
            hosttempidlist.append({"templateid": hosttempidid})

        print(hosttempidlist)
        test.host_create(proxyid, visiblename, hostip, groupsidlist, description, hosttempidlist)

        读取Excel表格,批量添加用户群组,会将添加失败的用户群组名输出到日志文件./fail_addHost.txt中,添加用户群组的同时会链接一个同名的主机群组(项目需要),表格比较简单,只有一列,就是要添加的用户群组名称,在此不再示例。

       上代码:

# !/usr/bin/env python3
# coding:utf-8
# Author: Nieen
import json
from urllib.request import Request
from urllib.request import urlopen
from urllib.error import HTTPError
import time
import pandas as pd


class zabbixtools:
    def __init__(self):
        # zabbix前端访问UERL
        self.url = "http://192.168.100.134/api_jsonrpc.php"
        self.header = {"Content-Type": "application/json"}
        # zabbix具有读写权限的可登陆账号密码
        # 527d6424e802a2b22bbcffcc0da481c5
        self.authID = self.user_login("Admin", "zabbix")

    def user_login(self, user, password):
        data = bytes(json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "user.login",
                "params": {
                    "user": user,
                    "password": password
                },
                "id": 0
            }), "utf-8")
        request = Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
        try:
            result = urlopen(request)
        except HTTPError as e:
            print("Auth Failed, Please Check Your Name And Password:", e.code)
        else:
            response = json.loads(result.read().decode('utf8'))
            result.close()
            authID = response['result']
            return authID

    def get_data(self, data):
        formData = bytes(data, 'utf-8')
        request = Request(self.url, formData)
        for key in self.header:
            request.add_header(key, self.header[key])
        try:
            result = urlopen(request)
        except HTTPError as e:
            if hasattr(e, 'reason'):
                print('We failed to reach a server.')
                print('Reason: ', e.reason)
            elif hasattr(e, 'code'):
                print('The server could not fulfill the request.')
                print('Error code: ', e.code)
            return 0
        else:
            response = json.loads(result.read().decode('utf-8'))
            result.close()
            return response

    def hostgroup_get(self, hostgroupName):
        data = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "hostgroup.get",
                "params": {
                    "output": "extend",
                    "filter": {
                        "name": [  # 列表格式,可多个
                            hostgroupName
                        ]
                    }
                },
                "auth": self.authID,
                "id": 1
            })
        res = self.get_data(data)['result']
        if (res != 0) and (len(res) != 0):
            # print(type(res))
            # for host in res:
            host = res[0]
            return host['groupid']
        else:
            return ""

    def hostgroup_create(self, hostgroupName):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "hostgroup.create",
            "params": {
                "name": hostgroupName
            },
            "auth": self.authID,
            "id": 1
        })
        res = self.get_data(data)['result']

        if (res != 0) and (len(res) != 0):
            # for host in res:
            # print(type(res))
            # print res['hostids'][0]
            return res['groupids'][0]
        else:
            return ""

    def usergroup_get(self, usergroupName):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "usergroup.get",
            "params": {
                "output": "extend",
                "status": 0
            },
            "auth": self.authID,
            "id": 1
        })
        resList = self.get_data(data)['result']
        for usergroup in resList:
            if usergroupName == usergroup['name']:
                # for host in res:
                # print(type(res))
                return usergroup['name']
                # return res['usrgrpid'][0]
            else:
                continue
        return ""

    def usergroup_create(self, usergroupName, hostgroupID):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "usergroup.create",
            "params": {
                "name": usergroupName,
                "rights": {
                    "permission": 3,
                    "id": hostgroupID
                }
            },
            "auth": self.authID,
            "id": 1
        })
        print("============")
        # ss = self.host_get(hostIP)
        # print(self.get_data(data))
        # print(self.get_data(data))

        # res = self.get_data(data)  # ['result']
        # print(type(res))
        res = self.get_data(data)
        print(res, '---------')

        if "result" in res:
            return res['result']['usrgrpids'][0]
        elif "error" in res:
            # 打开一个文件
            f = open("./fail_addHost.txt", "a+")
            localtime = time.asctime(time.localtime(time.time()))
            log = localtime + "[用户群组] " + usergroupName + ": " + res['error']['data'] + "\n"
            f.write(log)
            # 关闭打开的文件
            f.close()


if __name__ == "__main__":
    test = zabbixtools()
    excelPath = r'./files/addHost.xlsx'
    df = pd.read_excel(excelPath, sheet_name=0, header=0).fillna(method='pad')
    for row in range(df.__len__()):
        usergroupName = df.iloc[row][6]
        hostgroupName = usergroupName# 同名
        print(hostgroupName)
        # templateName = df.iloc[row][5]
        # print(templateName)
        hostgroupid = test.hostgroup_get(hostgroupName)
        if hostgroupid == "":
            # print(indexGroup, "00000000")
            hostgroupid = test.hostgroup_create(hostgroupName)
            # print(groupsid)

        usergroupStatus = test.usergroup_get(usergroupName)
        print(usergroupStatus, "++++++++")
        if usergroupStatus == "":
            test.usergroup_create(usergroupName, hostgroupid)
        else:
            f = open("./fail_addHost.txt", "a+")
            localtime = time.asctime(time.localtime(time.time()))
            log = localtime + " [用户群组] " + usergroupName + ": 已创建\n"
            f.write(log)
            # 关闭打开的文件
            f.close()
            continue

        以上。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值