首页 > 其他分享 >zabbix通过api方式批量创建和删除主机

zabbix通过api方式批量创建和删除主机

时间:2023-05-06 16:01:01浏览次数:47  
标签:info return 批量 self zabbix api dict result msg

zabbix库连接信息,文件名为Conn.py

import pymysql

"""
获取后台数据库连接
"""


def CON():
    con = pymysql.connect(host='rm-xxx.xxxxx.rds.aliyuncs.com', user='xxx',
                          password='xxxx', db='zabbix')
    return con


多台机器信息获取通过向项目目录下一个hosts.list文件里填入,内容格式如下:

slsk_aliyun_bili_501_BT_2|ip地址|10050|slsk|linux
slsk_aliyun_bili_501_GW-LG_2|ip地址|10050|slsk|linux
....

以|分割,第一列是机器主机名,第二列是机器ip地址,第三列是zabbix_agent传输端口,第四列是zabbix机器组名字,第五列表示是什么系统,目前只支持linux

zabbix api class封装,文件名为utils.py,

import json
import requests
from . import Conn
from config import basedir
import os
from action.actlog import HaLog


class ZabbixApi:
    def __init__(self):  # 初始化信息
        self.url = 'http://zabbix访问地址/api_jsonrpc.php'
        self.user = 'zabbix账号'
        self.passwd = 'zabbix密码'
        self.header = {"Content-Type": "application/json-rpc"}
        self.HostIP = []  # ip存放列表
        self.HostName = []  # 主机名存放列表
        self.HostTemplate = []  # 模板名称存放列表
        self.HostGroup = []  # 主机组存放列表
        self.l = HaLog("zabbix.log", "info", log_path="/home/hero/log")

    def UserLogin(self):
        data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": self.user,
                "password": self.passwd
            },
            "id": "1"
        }
        return self.UrlRequest(data)

    def UrlRequest(self, data):
        request = requests.post(self.url, json.dumps(data), headers=self.header)
        response = json.loads(request.text)
        self.l.info(str(response))
        return response

    def HostInFo(self):  # 将文件主机信息分类加入每个列表中
        host_info_path = os.path.join(basedir, "hosts.list")
        with open(host_info_path, encoding='utf-8', mode='r') as f:
            qsq = f.readlines()
            for list in qsq:
                host_name = list.strip().split('|')[0]
                self.HostName.append(host_name)
                host_ip = list.strip().split('|')[1]
                self.HostIP.append(host_ip)
                # host_port = list.strip().split('|')[2]
                host_group_name = list.strip().split('|')[3]
                self.HostGroup.append(host_group_name)
                template_name = list.strip().split('|')[4]
                self.HostTemplate.append(template_name)
            print(self.HostName, self.HostIP, self.HostGroup, self.HostTemplate)
        f.close()
        return self.HostName, self.HostIP, self.HostGroup, self.HostTemplate

    def HostInFoFromlist(self, info_list):
        """
        将列表转换为zabbix参数
        例:
        ["slsk_aliyun_bili_501_BT_2|ip地址|10050|slsk|linux",
        "slsk_aliyun_bili_501_GW-LG_2|ip地址|10050|slsk|linux",
        ...]
        迭代循环列表中内容,将字符串按照| 分隔,重新分解为zabbix 主机信息。
        :param info_list:
        :return:
        """
        for info in info_list:
            host_name = info.strip().split('|')[0]
            self.HostName.append(host_name)
            host_ip = info.strip().split('|')[1]
            self.HostIP.append(host_ip)
            # host_port = list.strip().split('|')[2]
            host_group_name = info.strip().split('|')[3]
            self.HostGroup.append(host_group_name)
            template_name = info.strip().split('|')[4]
            self.HostTemplate.append(template_name)
        return self.HostName, self.HostIP, self.HostGroup, self.HostTemplate

    def CreateHost(self, HostName, HostIP, HostGroup, HostTemplate, new_auth):  # 创建主机
        for i in range(len(HostIP)):
            ip = HostIP[i]
            name = HostName[i]
            temp = HostTemplate[i]
            # 暂时只给支持linux机器的创建
            if temp == 'linux':
                tempid = 10001
            elif temp == 'windows':
                tempid = 0000
            else:
                tempid = 0000
            group = HostGroup[i]  # 根据group名获取到groupid
            # if group == 'qiuqiu_prod':
            #     groupid = 21
            if group:
                con = Conn.CON()
                sql = "SELECT groupid FROM hstgrp where name='%s';" % group
                CURSOR = con.cursor()
                CURSOR.execute(sql)
                try:
                    groupid = CURSOR.fetchone()[0]
                except:
                    groupid = None
                finally:
                    CURSOR.close()
                    con.close()

            else:
                self.l.write("group 为空")
                return {"success": False, "msg": "group 为空"}

            if groupid is None:
                self.l.write("未获取到groupid")
                return {"success": False, "msg": "未获取到groupid"}
            data = {
                "jsonrpc": "2.0",
                "method": "host.create",
                "params": {
                    "host": name,
                    "interfaces": [
                        {
                            "type": 1,
                            "main": 1,
                            "useip": 1,
                            "ip": ip,
                            "dns": "",
                            "port": "10050"
                        }
                    ],
                    "groups": [
                        {
                            "groupid": groupid
                        }
                    ],
                    "templates": [
                        {
                            "templateid": tempid
                        }
                    ],
                },
                "auth": new_auth,
                "id": 1
            }
            res = self.UrlRequest(data)
            try:
                if res['error']:
                    return {"success": False, "msg": res['error']['data']}
            except:
                pass
            if i == len(HostIP) - 1:
                return {"success": True, "msg": "所有主机已创建完成!"}

    def Host_Get(self, new_auth, hostName):
        data = {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": "extend",
                "filter": {
                    "host": hostName
                }
            },
            "auth": new_auth,
            "id": 1
        }

        response = self.UrlRequest(data)
        self.l.write(response)
        if not len(response['result']):
            self.l.write("\033[041m %s \033[0m is not exist" % hostName)
            return False

        self.l.write("主机数量: \033[31m%s\033[0m" % (len(response['result'])))
        for host in response['result']:
            # print host
            if len(hostName) == 0:
                return False
            else:
                return host['hostid']

    def DeleteHost(self, HostName, HostIP, HostGroup, HostTemplate, new_auth):  # 删除主机
        hostid_list = []
        for i in range(len(HostIP)):
            name = HostName[i]
            hostid = self.Host_Get(new_auth, name)
            if not hostid:
                return {"success": False, "msg": "主机  %s 删除失败 !" % name}
            hostid_list.append(hostid)

        data = {
            "jsonrpc": "2.0",
            "method": "host.delete",
            "params": hostid_list,
            "auth": new_auth,
            "id": 1
        }

        self.UrlRequest(data)
        return {"success": True, "msg": "'所有主机已删除完成!"}


router函数,这里通过flask编写

from . import zabbix
from flask import make_response
from router_zabbix.utils import ZabbixApi


@zabbix.route('/create_hosts')
def create_hosts():
    result_dict = {}
    try:
        res = ZabbixApi().UserLogin()
        auth = res['result']
    except Exception as E:
        result_dict["success"] = False
        result_dict["msg"] = E
        return make_response(result_dict, 222)

    try:
        HostName, HostIP, HostGroup, HostTemplate = ZabbixApi().HostInFo()
        info = ZabbixApi().CreateHost(HostName, HostIP, HostGroup, HostTemplate, auth)
        if not info["success"]:
            result_dict["success"] = False
            result_dict["msg"] = info["msg"]
            return make_response(result_dict, 222)
    except Exception as E:
        result_dict["success"] = False
        result_dict["msg"] = E
        return make_response(result_dict, 222)

    result_dict["success"] = True
    result_dict["msg"] = info["msg"]
    return make_response(result_dict, 200)


@zabbix.route('/delete_hosts')
def delete_hosts():
    result_dict = {}
    try:
        res = ZabbixApi().UserLogin()
        auth = res['result']
    except Exception as E:
        result_dict["success"] = False
        result_dict["msg"] = E
        return make_response(result_dict, 222)

    try:
        HostName, HostIP, HostGroup, HostTemplate = ZabbixApi().HostInFo()
        info = ZabbixApi().DeleteHost(HostName, HostIP, HostGroup, HostTemplate, auth)
        if not info["success"]:
            result_dict["success"] = False
            result_dict["msg"] = info["msg"]
            return make_response(result_dict, 222)
    except Exception as E:
        result_dict["success"] = False
        result_dict["msg"] = E
        return make_response(result_dict, 222)

    result_dict["success"] = True
    result_dict["msg"] = info["msg"]
    return make_response(result_dict, 200)


def delete_hosts_cmd(info_list):
    """
    命令行方式调用zabbix api 用于删除 主机信息
    :return:
    """
    result_dict = {}
    try:
        res = ZabbixApi().UserLogin()
        auth = res['result']
    except Exception as E:
        result_dict["success"] = False
        result_dict["msg"] = E
        print('Zabbix 认证失败:')
        print(result_dict)
        return {"success": False, "msg": 'Zabbix 认证失败:{}'.format(result_dict)}

    try:
        HostName, HostIP, HostGroup, HostTemplate = ZabbixApi().HostInFoFromlist(info_list)
        info = ZabbixApi().DeleteHost(HostName, HostIP, HostGroup, HostTemplate, auth)
        if not info["success"]:
            result_dict["success"] = False
            result_dict["msg"] = info["msg"]
            print("Zabbix 删除失败:")
            print(result_dict)
            return {"success": False, "msg": 'Zabbix 删除失败:{}'.format(result_dict)}

    except Exception as E:
        result_dict["success"] = False
        result_dict["msg"] = E
        print(result_dict)
        return {"success": False, "msg": 'Zabbix 操作失败:{}'.format(result_dict)}

    result_dict["success"] = True
    result_dict["msg"] = info["msg"]
    print(result_dict)
    return {"success": True, "msg": result_dict}


标签:info,return,批量,self,zabbix,api,dict,result,msg
From: https://blog.51cto.com/u_15703497/6250463

相关文章

  • 通话记录生成器安卓版下载,手机通话记录生成器app,一键批量生成通话记录
    铁牛通话记录生成器是可以批量自动生成通话记录的app软件。如何“铁牛通话记录生成器下载”?这段话的这几个网都可以,复制它们到手机浏览器打开就可以。通话记录生成器下载jp155.com,通话记录生成器安卓版下载jp1988.com,下载通话记录生成器app,体验通话记录生成器在线,了解通话记录生成......
  • Java获取pdd详情api接口、商品详情、商品描述、宝贝链接获取展示示例
    ​拼多多商品详情就是对拼多多商城中的宝贝的描述了,消费者们在进入到宝贝的详情页面后,可以通过这些描述去了解该款宝贝。其实这样也可以大大的增加商品的转化率。那么它的作用有什么呢?1.突出商品卖点:把商品的特色和突出点写表现出来,很更好的吸引到顾客,让顾客有点击和购买的欲......
  • Net Core Web Api 配置Swagger
    一、创建NETCoreAPI项目NETCore版本:NETCore2.21.创建coreweb应用程序2.选择API3.下图为生成后的项目二、安装Swagger1.打开NuGet包管理器2.搜索Swashbuckle.AspNetCore安装在项目上3.点击我接受三、配置Swagger对于ConfigureServices和Configure的配置点击可参考1.ConfigureS......
  • Springboot 系列 (30) - Springboot+HBase 大数据存储(八)| Springboot Client/Server
    Kerberos(SecureNetworkAuthenticationSystem,网络安全认证系统),是一种网络认证协议,其设计目标是通过密钥系统为Client/Server提供强大的认证服务。该认证过程的实现不依赖于主机操作系统的认证,无需基于的信任,不要求网络上所有主机的物理安全,并假定网络上传送的数据包可以被......
  • ABP CORE+EF 批量删除、修改
    //物理删除()//awaitthis.Repository.GetAll().Where(p=>input.Ids.Contains(p.Id)).BatchDeleteAsync();//逻辑删除,批量修改删除字段awaitthis.Repository.GetAll().Where(p=>input.Ids.Contains(p.Id)).BatchUpdateAsync(p=>newShop......
  • 【快应用】一个for循环,教你实现批量包名检测功能
     【关键词】包名检测,for循环 【问题背景】快应用中调用pkg.hasInstalled检测应用是否已安装时,填入一个包名时,是可以正确返回结果,当输入的包名参数是一个数组时就只返回第一个包名的检测结果,之后的就不再返回结果了。这种情形该如何处理?​​ 【问题分析】这是因为该接口......
  • CUDA 的随机数算法 API
    参考自NvidiacuRand官方API文档一、具体使用场景如下是是在dropout优化中手写的uniform_random的Kernel:#include<cuda_runtime.h>#include<curand_kernel.h>__device__inlinefloatcinn_nvgpu_uniform_random_fp32(intseed){curandStatePhilox4_32_10_t......
  • salt-api
    添加用户useradd-M-s/sbin/nologinsaltapipasswdsaltapi新增配置文件#cat/etc/salt/master.d/eauth.confexternal_auth:pam:saltapi:#用户-.*#该配置文件给予saltapi用户所有模块使用权限,出于安全考虑一般只给予特定模块使用权限......
  • go测试库之apitest
    前言使用go语言做开发差不多快一年了,主要用来写后端Web服务,从一开始吐槽他的结构体,比如创建个复杂的JSON格式数据,那是相当的痛苦。还有err处理写的巨麻烦。当然,go也有爽的地方,创建个线协程简直太简单了。到后来慢慢接受,觉得效率还行,因为是静态强类型语言,在修改完项目代码之......
  • 武装你的WEBAPI-OData Versioning
    本文属于OData系列目录武装你的WEBAPI-OData入门武装你的WEBAPI-OData便捷查询武装你的WEBAPI-OData分页查询武装你的WEBAPI-OData资源更新Delta武装你的WEBAPI-OData之EDM武装你的WEBAPI-OData常见问题武装你的WEBAPI-OData使用Endpoint武装你的WEBAPI-OData聚合查询......