ZABBIX根据IP列表,主机描述,或IP子网批量创建主机的维护任务

news2024/10/6 20:39:18

有时候被ZABBIX监控的主机可能需要关机重启等维护操作,为了在此期间不触发告警,需要创建主机的维护任务,以免出现误告警

ZABBIX本身有这个API可供调用(不同版本细节略有不同,本次用的ZABBIX6.*),实现批量化建立主机的维护任务

无论哪种方式(IP列表,主机描述,或IP子网)创建维护,都是向maintenance.create这个方法传递参数的过程,除了起始和终止的时间,最主要的一个参数就是hostids这个参数,它是一个列表(也可以是单个hostid)

    def create_host_maintenance(self,names,ips,starttimes,stoptimes):

        starts=self.retimes(starttimes)
        stops=self.retimes(stoptimes)

        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method":"maintenance.create",
                           "params": {
	                        "name": names,
	                        "active_since": starts,
	                        "active_till": stops,
	                        #"hostids": [ "12345","54321" ],
                            "hostids": ips,
	                        "timeperiods": [
                             {
                                "timeperiod_type": 0,
		                        "start_date": starts,
		                        #"start_time": 0,zabbix6不用这个参数,低版本的有用
                                 "period": int(int(stops)-int(starts))
                                }
                                            ]
                                     },
            "auth": self.authID,
            "id": 1,
        })

        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])

        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Error as ", e
        else:
            response = json.loads(result.read())
            result.close()
            print "maintenance is created!"

1.简单说明hostids这个列表参数产生的过程

按IP列表产生hostids的LIST,并调用方法创建维护

def djmaintenanceiplist(self,ipliststr="strs",area="none",byip="none"):
	lists = []
	if area=="none":                                #通过IP列表来创建维护,只向函数传递ipliststr这个参数,其它参数为空
		for line in ipliststr.splitlines():
			con = line.split()
			ipaddr = con[0].strip()
			hostids = self.host_getbyip(ipaddr)
			if hostids != "error" and hostids not in lists:
				lists.append(hostids)
		return lists
	else:
		if area !="ip" and ipliststr != "strs":    #按主机描述匹配创建维护,ipliststr参数因定为strs,area参数为主机描述,byip参数为空(因为网络环境的原因,本例弃用这个条件)
			sqls="select hostid from zabbixdb.hosts where name like '%"+area+"%' "
			tests=pysql.conn_mysql()
			datas=tests.query_mysqlrelists(sqls)
			if datas != "error":
				for ids, in datas:
					if ids not in lists:
						lists.append(ids)
		else:
			if byip != "none":                     #按主机IP子网创建维护,byip参数不为空(因为网络环境的原因,本例弃用这个条件)
				sqls = "select hosts.hostid from zabbixdb.hosts,zabbixdb.interface where `hosts`.hostid=interface.hostid and (interface.ip like '%" + byip + "%' or hosts.name like '%" + byip + "%')"
				tests = pysql.conn_mysql()
				datas = tests.query_mysqlrelists(sqls)
				if datas != "error":
					for ids, in datas:
						if ids not in lists:
							lists.append(ids)

		return lists


def djiplist(self,starttime,stoptime,strlins):  #strlins为IP列表的参数,可由WEB前端传递进来
	test = ZabbixTools()
	test.user_login()
	lists = test.djmaintenanceiplist(strlins)
	nowtime = str(time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())))
	test.create_host_maintenance(nowtime, lists, starttime, stoptime)

按主机描述和IP子网产生hostids的LIST,并调用方法创建维护

def djdescript(self,starttime,stoptime,descstr,ipnets="none"):
	lists = []
	if descstr != "ip":          #descstr参数不为ip的时候,表示根据主机的描述信息匹配创建维护,此时不传递innets参数
		for line in descstr.splitlines():
			con = line.split()
			descstrnew = con[0].strip()
			sqls = "select hostid from dbname.hosts where name like '%" + descstrnew + "%' "
			tests = pysql.conn_mysql()
			datas = tests.query_mysqlrelists(sqls)
			if datas != "error":
				for ids, in datas:
					if ids not in lists:
						lists.append(ids)

	else:
		if ipnets != "none":    #ipnets参数不为空,表示按照IP子网匹配创建维护,此时descstr参数一定为"ip"
			sqls = "select hosts.hostid from dbname.hosts,dbname.interface where `hosts`.hostid=interface.hostid and (interface.ip like '%" + ipnets + "%' or hosts.name like '%" + ipnets + "%')"
			tests = pysql.conn_mysql()
			datas = tests.query_mysqlrelists(sqls)
			if datas != "error":
				for ids, in datas:
					if ids not in lists:
						lists.append(ids)

	test = ZabbixTools()
	test.user_login()
	nowtime = str(time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())))
	test.create_host_maintenance(nowtime, lists, starttime, stoptime)

2.create_host_maintenance和djmaintenanceiplist,及djdescript函数调用方法的说明

时间转换函数self.retimes,将用户传递/的"%Y-%m-%d %H:%M:%S"日期时间转换为时间时间戳

    def retimes(self,times):
        timeArray = time.strptime(times, "%Y-%m-%d %H:%M:%S")
        timestamp = time.mktime(timeArray)
        return timestamp

self.host_getbyip(ipaddr)通过主机IP获取zabbix的hostid,这个方法应用很广泛

函数中的self.authID通过zabbix的API 的"user.login"方法获取,参考ZABBIX官方文档

    def host_getbyip(self,hostip):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method":"host.get",
                           "params":{
                                     "output":["hostid","name","status","available"],
                                     "filter": {"ip": hostip,"custom_interfaces":0}
                                     },
                     
                            "auth":self.authID,
                           "id":1,
                           })

        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
        try:
            result = urllib2.urlopen(request)
        except URLError 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
        else:
            response = json.loads(result.read())
            result.close()
            lens=len(response['result'])
            if lens > 0:
                return response['result'][0]['hostid']
            else:
                print "error "+hostip
                return "error"
pysql.conn_mysql()的实现
#coding:utf-8
import pymysql
class conn_mysql:
    def __init__(self):
        self.db_host = 'zabbixdbip'
        self.db_user = 'dbusername'
        self.db_passwd = 'dbuserpassword'
        self.database = "dbname"

    def query_mysqlrelists(self, sql):
        conn = pymysql.connect(host=self.db_host, user=self.db_user, passwd=self.db_passwd,database=self.database)
        cur = conn.cursor()
        cur.execute(sql)
        data = cur.fetchall()
        cur.close()
        conn.close()
        #print data
        # 查询到有数据则进入行判断,row有值且值有效则取指定行数据,无值则默认第一行
        if data != None and len(data) > 0:
            return data
            #调用方式:for ids, in datas:
        else:
            return "error"
        #此方法返回的数据不含数据库字段的列表,如果要返回包含列名(KEY)的字典列表,则:conn = pymysql.connect(host=self.db_host, user=self.db_user, passwd=self.db_passwd,database=self.database,cursorclass=pymysql.cursors.DictCursor)  解决:tuple indices must be integers, not str

3.VIEWS.PY及前端和前端伟递参数的说明

views.py对应的方法

#@login_required
def zabbixmanage(request):
    if request.method=="POST":
        uptime = request.POST.get('uptime')
        downtime= request.POST.get('downtime')

        UTC_FORMAT = "%Y-%m-%dT%H:%M"
        utcTime = datetime.datetime.strptime(uptime, UTC_FORMAT)
        uptime = str(utcTime + datetime.timedelta(hours=0))
        utcTime = datetime.datetime.strptime(downtime, UTC_FORMAT)
        downtime = str(utcTime + datetime.timedelta(hours=0))

        if request.POST.has_key('iplists'):
            try:
                sqlstr=request.POST.get("sqlstr")
                u1=upproxy.ZabbixTools()  #前面的python文件名为upproxy.py,类名为ZabbixTools
                u1.djiplist(uptime,downtime,sqlstr)
            except Exception:
                return render(request,"zbx1.html",{"login_err":"FAILSTEP1"})
        if request.POST.has_key('descs'):
            try:
                sqlstr = request.POST.get("sqlstr")
                u1 = upproxy.ZabbixTools()  
                u1.djdescript(uptime,downtime,sqlstr)
            except Exception:
                return render(request,"zbx1.html",{"login_err":"FAILSTEP2"})
        if request.POST.has_key('ipnets'):
            try:
                sqlstr = request.POST.get("sqlstr")
                u1 = upproxy.ZabbixTools()
                u1.djdescript(uptime,downtime,"ip",sqlstr)
            except Exception:
                return render(request,"zbx1.html",{"login_err":"FAILSTEP3"})

HTML的简单写法,不太会写,很潦草

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>ZABBIXMANAGE</title>
</head>
<body>
	<div id="container" class="cls-container">
		<div id="bg-overlay" ></div>
		<div class="cls-header cls-header-lg">
			<div class="cls-brand">
                <h3>ZABBIX主机维护模式</h3>
                <h4>开始时间小于结束时间</h4>
			</div>
		</div>
		<div class="cls-content">
			<div class="cls-content-sm panel">
				<div class="panel-body">

					<form id="loginForm" action="{% url 'zabbixmanage' %}" method="POST"> {% csrf_token %}
						<div class="form-group">
							<div class="input-group">
								<div class="input-group-addon"><i class="fa fa-user"></i></div>
                                <textarea type="text" class="form-control" name="sqlstr" placeholder="IP列表,关键字或者IP网段" style="width:300px;height:111px"></textarea></br>
							</div>
						</div>
                        </br></br>
                        开始时间:<input type="datetime-local" name="uptime">
                        </br></br>
                        结束时间:<input type="datetime-local" name="downtime">
                        </br></br>
                        <p class="pad-btm">按IP列表维护:按行输入IP列表加入维护,一行一个IP,多行输入</p>
                        <p class="pad-btm">按关键字匹配:主机描述信息的关键字匹配的加入维护,一般用于虚拟机宿主机和关键字匹配</p>
                        <p class="pad-btm">匹配子网关键字维护:IP网段匹配的加入维护,一次填写一个子网,多个子网多次设置,写法示例:172.16.</p>
						<button class="btn btn-success btn-block" type="submit" name="iplists">
							<b>按IP列表维护一般情况用这个就行</b>
						</button>
                        </br></br>
                        <button class="btn btn-success btn-block" type="submit" name="descs">
							<b>按关键字匹配</b>
						</button>
                        <button class="btn btn-success btn-block" type="submit" name="ipnets">
							<b>匹配子网关键字维护</b>
						</button>
                        <h4 style="color: red"><b>{{ login_err }}</b></h4>
					</form>
				</div>
			</div>
		</div>		
	</div>
</body>
</html>

跑起来大约是这个界面,用户填写主机IP列表,或匹配的描述,或子网的信息,选好时间,点个按钮就能实现批量的维护任务

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1390847.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

服务器里面很卡,打开文件卡住了一般是什么问题,怎么解决

随着互联网业务的快速发展&#xff0c;各项业务都绕不开服务器。在日常使用中&#xff0c;服务器有着非常重要的作用。而我们日常使用中&#xff0c;也会遇到各种各样的问题。最近就有遇到用户联系咨询德迅云安全&#xff0c;询问自己服务器突然很卡&#xff0c;打开文件都卡住…

预备知识02-自动微分

线性代数、微积分 这两个不作介绍&#xff0c;可以点击下方链接阅读原文 2.3. 线性代数 — 动手学深度学习 2.0.0 documentation (d2l.ai) 2.4. 微积分 — 动手学深度学习 2.0.0 documentation (d2l.ai) 梯度 在微积分中&#xff0c;对多元函数的参数求偏导&#xff0c;把…

【RabbitMQ】RabbitMQ高级:死信队列和延迟队列

目录 设置TTL&#xff08;过期时间&#xff09;概述RabbitMQ使用TTL原生API案例springboot案例 死信队列概述原生API案例springboot案例 延迟队列概述插件实现延迟队列安装插件代码 TTL实现延迟队列实现延迟队列优化 设置TTL&#xff08;过期时间&#xff09; 概述 在电商平台…

《数据结构》实验报告-实验二 栈与队列的应用

《数据结构》实验报告-实验二 栈与队列的应用 一、问题分析 &#xff08;1&#xff09;实验1中&#xff0c;火车进站和出站的过程&#xff0c;与后进先出的数据结构栈很相似。因为火车只能单方向进出站&#xff0c;前面进来的火车反而要等后面的火车先出站&#xff0c;这也导…

MongoDB面试系列-01

1. MongoDB 是什么&#xff1f; MongoDB是由C语言编写的&#xff0c;是一个基于分布式文件存储的开源数据库系统。再高负载的情况下&#xff0c;添加更多的节点&#xff0c;可以保证服务器性能。MongoDB旨在给Web应用提供可扩展的高性能数据存储解决方案。 MongoDB将数据存储…

php网站上传文件失败File upload failed(文件大小超过限制)

php项目中&#xff0c;用户上传文件报错&#xff1a;“File upload failed”&#xff0c;按如下代码输出文件名&#xff1a; $temp_name $_FILES[file][tmp_name]; $file_name basename($_FILES[file][name]);echo "Temporary File Name: " . $temp_name . "…

软件设计师3--CPU组成(运算器与控制器)

软件设计师3--CPU组成&#xff08;运算器与控制器&#xff09; 考点1&#xff1a;计算机结构考点2&#xff1a;CPU结构CPU包括运算器和控制器例题&#xff1a; 考点1&#xff1a;计算机结构 考点2&#xff1a;CPU结构 CPU包括运算器和控制器 运算器&#xff1a; 算数逻辑运算…

Git 使用与问题记录 二(公司快速上手版)

写在前面 记录自己学习的内容&#xff0c;方便后面忘记的时候查看。给像我一样的新手提供一点参考 正文 上一章已经安装好了Git&#xff0c;如何使用呢。我这里会分享两种办法&#xff0c;第一种是在VS2022中克隆代码&#xff0c;修改和提交&#xff1b;第二种是用命令提交。…

决战排序之巅(二)

决战排序之巅&#xff08;二&#xff09; 排序测试函数 void verify(int* arr, int n) 归并排序递归方案代码可行性测试 非递归方案代码可行性测试 特点分析 计数排序代码实现代码可行性测试 特点分析 归并排序 VS 计数排序&#xff08;Release版本&#xff09;说明1w rand( ) …

Ubuntu20.4 Mono C# gtk 编程习练笔记(一)

简言 Mono是Linux环境下C#的开发、编译及运行环境。gtk是gnome独具特色的图形库&#xff0c;Mono对它进行了C#封装。Linux环境下&#xff0c;许多的编程语言使用gtk界面库&#xff0c;有比较好的编程群众基础。另外&#xff0c;Mono相对于DOTNET来说要轻量许多&#xff0c;它们…

uniapp 使用canvas制作柱状图

效果图&#xff1a; 实现思路&#xff1a; 1、通过展示数据计算需要画几根柱子&#xff1b; 2、通过组件宽度、高度计算出每根柱子的宽度及高度&#xff1b; 3、for循环依次绘制每根柱子&#xff1b; 4、绘制柱子时&#xff0c;先绘制顶部百分比、value值&#xff0c;再绘制柱…

Grafana(二)Grafana 两种数据源图表展示(json-api与数据库)

一. 背景介绍 在先前的博客文章中&#xff0c;我们搭建了Grafana &#xff0c;它是一个开源的度量分析和可视化工具&#xff0c;可以通过将采集的数据分析、查询&#xff0c;然后进行可视化的展示&#xff0c;接下来我们重点介绍如何使用它来进行数据渲染图表展示 Docker安装G…

跟着pink老师前端入门教程-day03

6. 表格标签 6.1 表格的主要作用 主要用于显示、展示数据&#xff0c;可以让数据显示的规整&#xff0c;可读性非常好&#xff0c;特别是后台展示数据时&#xff0c;能够熟练运用表格就显得很重要。 6.2 基本语法 <!--1. <table> </table> 是用于定义表格的标…

MySQL的内部XA的二阶段提交

内部XA 可能大家一听感觉很陌生&#xff0c;什么是XA&#xff1f;XA是一种分布式事务管理规范&#xff0c;MySQL内部有一个XA事务管理器来支持分布式事务&#xff0c;可能这么一听更懵了&#xff0c;那么我这么解释一下&#xff0c;MySQL是支持主从的&#xff0c;主从分布在不…

导入失败,报错:“too many filtered rows xxx, “ErrorURL“:“

一、问题&#xff1a; 注&#xff1a;前面能正常写入&#xff0c;突然就报错&#xff0c;导入失败&#xff0c;报错&#xff1a;“too many filtered rows xxx, "ErrorURL":" {"TxnId":769494,"Label":"datax_doris_writer_bf176078-…

预处理/预编译详解(C/C++)

在上一篇的bolg中的编译与链接中提到过预处理&#xff0c;但只是较为简单的讲解&#xff0c;本篇将会对预处理进行详细的讲解。 其中在预处理中很重要的一个一个知识点是#define定义常量与宏&#xff0c;还区分了宏与函数的区别&#xff0c;以及#和##符号&#xff0c;还涉及条件…

【Java SE】类和对象详解

文章目录 1.什么是面向对象2. 类的定义和使用2.1 简单认识类2.2 类的定义格式 3. 类的实例化3.1 什么是实例化3.1.1 练习&#xff08;定义一学生类&#xff09; 3.2 类和对象的说明 4. this 引用5. 构造方法6. 对象的初始化6.1 默认初始化6.2 就地初始化 7. 封装7.1 封装的概念…

Angular系列教程之单向绑定与双向绑定

文章目录 介绍单向绑定双向绑定在自定义组件中实现双向绑定属性总结 介绍 在Angular开发中&#xff0c;数据的绑定是非常重要的概念。它允许我们将应用程序的数据与用户界面进行交互&#xff0c;实现数据的动态更新。在本文中&#xff0c;我们将探讨Angular中的两种数据绑定方…

学习k8s的应用(三)

一、k8s部署ngnix 1、一些查看命令 1-1、所有命令空间 kubectl get pod --all-namespaces kubectl get svc --all-namespaces1-2、指定命令空间 kubectl get pod -n yabin kubectl get svc -n yabin2、单节点集群兼容 # 因为目前只有一个master节点&#xff0c;默认安装后…

workflow源码解析:ThreadTask

1、使用程序&#xff0c;一个简单的加法运算程序 #include <iostream> #include <workflow/WFTaskFactory.h> #include <errno.h>// 直接定义thread_task三要素 // 一个典型的后端程序由三个部分组成&#xff0c;并且完全独立开发。即&#xff1a;程序协议算…