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

有时候被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 ", eelse: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 listselse: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 listsdef 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.reasonelif hasattr(e, 'code'):print 'The server could not fulfill the request.'print 'Error code: ', e.codeelse:response = json.loads(result.read())result.close()lens=len(response['result'])if lens > 0:return response['result'][0]['hostid']else:print "error "+hostipreturn "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,类名为ZabbixToolsu1.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.mzph.cn/news/635661.shtml

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

相关文章

用 Golang 启动个简单的http服务器

本章通过编写功能逐渐复杂的 web 服务器来让开发者对如何运用 go 语言有一个初步的了解。web 服务的地址 http://localhost:8000。 1. 启动一个最简单的 web 服务器 package mainimport ("fmt""log""net/http" )func main() {http.HandleFunc(…

【C语言】linux内核ipoib模块 - ipoib_start_xmit

一、ipoib_start_xmit函数定义 static netdev_tx_t ipoib_start_xmit(struct sk_buff *skb, struct net_device *dev) {struct ipoib_dev_priv *priv ipoib_priv(dev);struct rdma_netdev *rn netdev_priv(dev);struct ipoib_neigh *neigh;struct ipoib_pseudo_header *phdr…

[AI]文心一言爆火的同时,ChatGPT-4.5的正确打开方式

前言 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家&#xff1a;https://www.captainbed.cn/z ChatGPT体验地址 文章目录 前言4.5key价格泄漏ChatGPT4.0使用地址ChatGPT正确打开方式最新功能语音助手存档…

STM32标准库开发——串口发送/单字节接收

USART基本结构 串口发送信息 启动串口一的时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);初始化对应串口一的时钟&#xff0c;引脚&#xff0c;将TX引脚设置为复用推挽输出。 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_In…

css绘制下拉框头部三角(分实心/空心)

1:需求图: 手绘下拉框 带三角 2:网上查了一些例子,但都是实心的, 可参考,如图: (原链接: https://blog.csdn.net/qq_33463449/article/details/113375804) 3:简洁版的: a: 实心: <view class"angle"/>.angle{width:0;height:0;border-left: 10px solid t…

121 二叉搜索树的最近公共祖先

问题描述&#xff1a;给定一个二叉搜索树&#xff0c;找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为&#xff1a;对于有根树T的两个节点p、q&#xff0c;最近公共祖先表示为一个节点x&#xff0c;满足x是p和q的祖先&#xff0c;且x的深度尽可能大。 …

java获取jvm内存信息 java获取jvm运行信息 java获取jvm运行信息

java获取jvm内存信息 java获取jvm运行信息 java获取jvm运行信息 1、创建需要使用的工具类2、创建一个 jvm信息对象类3、使用 1、创建需要使用的工具类 文件名 ByteConverter.java 用于将字节数值转为 MB数值 import java.math.BigDecimal; import java.math.RoundingMode;/***…

元宇宙:智慧城市建设的未来引擎与价值之源

在21世纪的技术大潮中&#xff0c;元宇宙的出现无疑是一场革命&#xff0c;其独特的概念与价值已经引发了全球范围内的关注。 作为新兴科技的前沿&#xff0c;元宇宙为智慧城市建设带来了无限的可能性和价值&#xff0c;有望成为未来城市发展的核心动力。 元宇宙&#xff0c;这…

「HDLBits题解」Counters

本专栏的目的是分享可以通过HDLBits仿真的Verilog代码 以提供参考 各位可同时参考我的代码和官方题解代码 或许会有所收益 题目链接&#xff1a;Count15 - HDLBits module top_module (input clk,input reset, // Synchronous active-high resetoutput [3:0] q ); always…

【linux】Linux编辑器-vim

rz指令&#xff0c;sz指令 关于 rzsz 这个工具用于 windows 机器和远端的 Linux 机器通过 XShell 传输文件. 安装完毕之后可以通过拖拽的方式将文件上传过去 1.查看软件包 通过 yum list 命令可以罗列出当前一共有哪些软件包. 由于包的数目可能非常之多, 这里我们需要使用 grep…

GitHub 一周热点汇总第6期(2024/01/14-01/20)

GitHub一周热点汇总第6期 (2024/01/14-01/20) &#xff0c;梳理每周热门的GitHub项目&#xff0c;这一周的热门项目中AI的比重难得的变低了&#xff0c;终于不像一个AI热门项目汇总了&#xff0c;一起来看看都有哪些项目吧。 #1Maybe 项目名称&#xff1a;Maybe - 个人理财应…

webpack.config.js配置文件报错:The ‘mode‘ option has not been set

报错 WARNING in configuration The mode option has not been set, webpack will fallback to production for this value. Set mode option to development or production to enable defaults for each environment. You can also set it to none to disable any default be…

pixel_avg2_w20_neon x264像素宽度为20的均值计算

一 C语言实现 static inline void pixel_avg2_w20_altivec(uint8_t *dst, intptr_t i_dst, uint8_t *src1, intptr_t i_src1, uint8_t *src2, int i_height) { pixel_avg2_w16_altivec(dst, idst, src1, i_src1, src2, i_height); //前面16列 pixel_avg2_w4_altivec(dst 16, i…

2种数控棋

目录 数控棋1 数控棋2 数控棋1 棋盘&#xff1a; 初始局面&#xff1a; 规则&#xff1a; 规则&#xff1a;双方轮流走棋&#xff0c;可走横格、竖格、可横竖转弯&#xff0c;不可走斜格。每一步均须按棋所在格的数字走步数&#xff0c;不可多不可少。 先无法走棋的一方为…

Java多线程并发篇----第二十五篇

系列文章目录 文章目录 系列文章目录前言一、如何在 Windows 和 Linux 上查找哪个线程使用的CPU 时间最长?二、什么是原子操作?在 Java Concurrency API 中有哪些原子类(atomic classes)?三、Java Concurrency API 中的 Lock 接口(Lockinterface)是什么?对比同步它有什么优…

【机组】算术逻辑单元带进位运算实验的解密与实战

​&#x1f308;个人主页&#xff1a;Sarapines Programmer&#x1f525; 系列专栏&#xff1a;《机组 | 模块单元实验》⏰诗赋清音&#xff1a;云生高巅梦远游&#xff0c; 星光点缀碧海愁。 山川深邃情难晤&#xff0c; 剑气凌云志自修。 ​ 目录 &#x1f33a;一、 实验目…

C语言第三弹---数据类型和变量

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】 数据类型和变量 1、数据类型介绍1.1、整型1.2、浮点型1.3、字符型1.4、布尔类型1.5、各种数据类型的长度1.5.1、sizeof操作符1.5.2、数据类型的长度1.5.3、sizeo…

win系统环境搭建(十二)——Windows系统下使用docker安装redis

windows环境搭建专栏&#x1f517;点击跳转 win系统环境搭建&#xff08;十二&#xff09;——Windows系统下使用docker安装redis 文章目录 win系统环境搭建&#xff08;十二&#xff09;——Windows系统下使用docker安装redis1.创建文件夹2.docker-compose.yaml配置文件3.red…

vulnhub通关-1 DC-1(含靶场资源)

一、环境搭建 1.环境描述 描述 描述&#xff1a; DC-1 is a purposely built vulnerable lab for the purpose of gaining experience in the world of penetration testing. Dc-1是一个专门构建的易受攻击的实验室&#xff0c;目的是获得渗透测试领域的经验。 It was design…

读懂比特币—bitcoin代码分析(一)

最近美国 SEC 通过了比特币的 ETF申请&#xff0c;比特币究竟是个什么东西&#xff0c;从技术上来说&#xff0c;bitcoin 是一个点对点的电子现金系统&#xff0c;它可以实现分布式的记账&#xff0c;不依赖中心化的账务系统&#xff08;比如银行&#xff0c;支付宝&#xff09…