zabbix批量导入监控主机

简介: 从excel表中批量导入被监控主机自动根据分组名称创建分组根据模板名称匹配主机监控模板

zabbix_import_hosts

zabbix批量导入监控主机

用途

从excel表中批量导入被监控主机

自动根据分组名称创建分组

根据模板名称匹配主机监控模板

使用前提

程序需要使用pyzabbix xlrd requests三个库

pip install xlrd
pip install requests
pip install pyzabbix

用法演示

python zabbix_import_hosts.py 

请输入导入文件名hostlist.xls
主机 主机1 已经存在
添加主机: 数据库1 
添加主机: 数据库2
添加主机: WEB主机1
添加主机: WEB主机2 
添加主机: WEB主机3

脚本内容

#!/usr/bin/python2
# -*- coding: utf-8 -*- 
from pyzabbix import ZabbixAPI
import pprint
import subprocess
import os.path

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

#配置Zabbix AIP信息
zabbixUrl   = "http://${ip}:${port}/zabbix"
zabbixUser  = "Admin"
zabbixPwd   = "zabbix"

#是否添加Macros
MACROS = False

#获取导入的xls文件名
#hostFile="host_list.csv"

if len(sys.argv) <= 1:
    print("Error: Please input file")
    sys.exit()
else:
    hostFile=sys.argv[1]

if not os.path.isfile(hostFile) :
    print('file is not exist')
    sys.exit()


#尝试登陆zabbix平台
try:
    zapi = ZabbixAPI(zabbixUrl)
    zapi.login(zabbixUser, zabbixPwd)
except:
    print '\n 登录zabbix平台出现错误'
    sys.exit()

#通过模板名获取模板ID
def get_templateid(template_name):
    template_data = {
        "host": [template_name]
    }
    #print template_data
    result = zapi.template.get(filter=template_data)
    if result:
        return result[0]['templateid']
    else:
        return result

#检查组名是否已经存在
def check_group(group_name):
    group_data = {
        "name":[group_name]
    }
    return zapi.hostgroup.get(filter=group_data)

#创建组
def create_group(group_name):
    groupid=zapi.hostgroup.create(name=group_name)

#通过组名获取组ID
def get_groupid(group_name):
    group_date = {
        "name":[group_name]
    }
    return str(zapi.hostgroup.get(filter=group_date)[0]['groupid'])

#添加主机
def create_host(host_data):
    data = {
        "name":[host_data['host']]
    }
    
    if zapi.host.get(filter=data):
        print "主机 %s 已经存在" % host_data["host"]
        return False
    else:
        #print host_data
        res = zapi.host.create(host_data)
        if res: 
            #print "hostid is " + res['hostids'][0]
            if MACROS:
                macro = {
                    "hostid": res['hostids'][0],
                    "macro": "{$SNMP_COMMUNITY}",
                    "value": "ht-read"
                }
                zapi.usermacro.create(macro)
            print "添加主机: %s " % (host_data["host"])
            return True
        else:
            print "添加失败: %s " % (host_data["host"])
            return False

#打开xls文件 
def open_excel( file ):
     try:
         data = xlrd.open_workbook(file)
         return data
     except Exception,e:
         print str(e)

#打开CSV文件
def open_csv( file ):
    hostlist = []

    stdout = subprocess.check_output("file "+file, shell=True)
    charset = stdout.split(':')[1].strip() 
    if charset != "UTF-8 Unicode text" and charset != "ASCII text":
        print "Warning: file is not UTF-8 Unicode text, please use dos2unix convertion"
        sys.exit()

    try:
        for line in open(file):
            t = tuple(line.strip().split(','))
            if line.startswith('#'):
                continue
            hostlist.append(t)
        return hostlist
    except Exception,e:
        print str(e)

#将xls文件内主机导入到list
def get_hosts(file):
    data = open_excel(file)
    table = data.sheets()[0]
    nrows = table.nrows
    ncols = table.ncols
    list = []
    for rownum in range(1,nrows):
      #print table.row_values(rownum)[0]
      list.append(table.row_values(rownum)) 
    return list

def main():
    hosts=open_csv(hostFile)
    countTotal=0
    countSucc=0
    countFail=0
    
    #print hosts
    for host in hosts:
        countTotal += 1
        hostName     = host[0].strip()
        visibleName  = host[1].strip()
        hostIp       = host[2].strip()
        groupName    = host[3].strip()
        template     = host[4].strip()
        templateId   = get_templateid(template)
        interfaceType = host[5].strip()
        port = host[6].strip()
        print "creating " + hostName
        #print "templateid = " + templateId
        if  not check_group(groupName) :
            print u'添加主机组: %s' % groupName
            groupid=create_group(groupName)
            #print groupid
        groupId = get_groupid(groupName)
        host_data = {
            "host": host[0].strip(),
            "name": visibleName,
            "interfaces": [
              {
                  "type": interfaceType,
                  "main": 1,
                  "useip": 1,
                  "ip": hostIp,
                  "dns": "",
                  "port": port
              }
            ],
            "groups": [
              {
                  "groupid": groupId
              }
            ],
            "templates": [
              {
                  "templateid": templateId
              }
            ],
            "inventory": {
              "location": ""
            }
        }
        #print "添加主机: %s ,分组: %s ,模板ID: %s" % (visible_name,group,templateid)
        #print host_data
        res = create_host(host_data)
        if res:
            countSucc += 1
        else:
            countFail += 1
    print("\n\n导入主机: %s 主机, 成功导入:%s, 失败导入:%s" % (countTotal,countSucc,countFail))
    

if __name__=="__main__":
    main()

以下图片为CSV文件格式

image.png

目录
相关文章
|
2月前
|
监控 安全 Linux
在Linux中,zabbix如何监控脑裂?
在Linux中,zabbix如何监控脑裂?
|
12天前
|
SQL 监控 数据库
OceanBase社区版可以通过Zabbix监控
【10月更文挑战第5天】随着OceanBase社区版的广泛应用,企业纷纷采用这一高性能、高可用的分布式数据库系统。为了确保系统的稳定运行,使用成熟的Zabbix监控工具进行全面监控至关重要。本文通过具体示例介绍了如何配置Zabbix监控OceanBase,包括安装配置、创建监控模板和监控项、编写脚本、设置触发器及图形展示等步骤,帮助读者快速上手,及时发现并解决问题,确保业务始终处于最佳状态。
22 2
|
1月前
|
监控 关系型数据库 MySQL
zabbix agent集成percona监控MySQL的插件实战案例
这篇文章是关于如何使用Percona监控插件集成Zabbix agent来监控MySQL的实战案例。
37 2
zabbix agent集成percona监控MySQL的插件实战案例
|
2月前
|
SQL 监控 分布式数据库
【解锁数据库监控的神秘力量!】OceanBase社区版与Zabbix的完美邂逅 —— 揭秘分布式数据库监控的终极奥秘!
【8月更文挑战第7天】随着OceanBase社区版的普及,企业广泛采用这一高性能、高可用的分布式数据库。为保障系统稳定,使用成熟的Zabbix监控工具对其进行全方位监控至关重要。本文通过实例介绍如何在Zabbix中配置监控OceanBase的方法,包括创建监控模板、添加监控项(如TPS)、设置触发器及图形展示,并提供示例脚本帮助快速上手。通过这些步骤,可以有效监控OceanBase状态,确保业务连续性。
90 0
|
4月前
|
监控 数据库 Docker
Zabbix监控神通数据库教程
**摘要:** 本文介绍了如何使用Docker安装和配置神舟通用数据库,并利用Zabbix进行监控。首先,通过Docker安装数据库镜像,启动容器并映射端口。接着,使用默认凭证连接数据库并验证安装。然后,将数据库的Python模块和库文件复制到主机,并安装Python3.5及相应模块,创建外部检查脚本以实现Zabbix的监控功能。示例展示了查询数据库版本的监控指标配置。最后,提到了监控结果的界面展示,并邀请读者探索更多Zabbix监控技巧。
69 0
Zabbix监控神通数据库教程
|
3月前
|
监控 关系型数据库 应用服务中间件
Linux zabbix监控 软件的安装
Linux zabbix监控 软件的安装
|
5月前
|
监控 关系型数据库 MySQL
zabbix 监控mysql服务
zabbix 监控mysql服务
81 0
zabbix 监控mysql服务
|
5月前
|
数据采集 监控 数据库
请问OceanBase社区版能否通过zabbix监控,然后将报错信息展现到grafana?
【2月更文挑战第25天】请问OceanBase社区版能否通过zabbix监控,然后将报错信息展现到grafana?
65 2
|
5月前
|
监控 网络协议 Unix
centos7 zabbix安装客户端agent -配置监控远程主机 在需要监控的电脑上安装
centos7 zabbix安装客户端agent -配置监控远程主机 在需要监控的电脑上安装
178 0
|
5月前
|
监控 Cloud Native 关系型数据库
使用 Grafana 统一监控展示 - 对接 Zabbix
使用 Grafana 统一监控展示 - 对接 Zabbix

推荐镜像

更多