python自动统计zabbix系统监控覆盖率的示例代码
作者:huss 发布时间:2023-11-14 08:23:03
标签:python,统计,zabbix
脚本主要功能:
1)通过zabbix api接口采集所有监控主机ip地址;
2)通过cmdb系统(蓝鲸)接口采集所有生产主机IP地址、主机名、操作系统、电源状态;
3)以上2步返回数据对比,找出未监控主机ip地址,生成csv文件;
4)发送邮件。
脚本如下:
#!/usr/bin/python
#coding:utf-8
import requests
import json
import re
import time
import csv
from collections import Counter
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 从cmdb系统获取虚拟化生产主机ip
def getCmdbProdHost():
url1 = 'http://paas.xxxx.com/api/c/compapi/v2/cc/search_inst/'
data1 = {
"bk_app_secret": "**********************",
"bk_app_code": "bk_cmdb",
"bk_username": "admin",
"bk_obj_id": "host",
"page": {
"start": 0,
"limit": 2000,
"sort": "bk_inst_id"
},
"fields": {
"host": [
"bk_host_id",
"bq_hostname",
"bk_host_innerip",
"bq_hosttype",
"powerState",
"bq_osname"
]
} }
r1 = requests.post(url1, json=data1)
response_dict1 = r1.json()
#print(response_dict1)
prodip_dict = {}
testip = "10.210.xx|10.210.xx|10.210.xx|10.210.xx|xx.xx.xx" #测试网段ip
for i in response_dict1.get('data')["info"]:
if i["bq_hosttype"] == "t2" and i["powerState"] == "poweredOn" and not re.search("UAT", i["bq_hostname"]) and not re.match(testip, i["bk_host_innerip"]):
prodip_dictkey = i["bk_host_innerip"]
#prodip_dictvalue = i["bq_hostname"]
prodip_dictvalue = [i["bq_hostname"], i["bq_osname"], i["powerState"]]
prodip_dict[prodip_dictkey] = prodip_dictvalue
return prodip_dict
#获取zabbix系统登录认证
def getZabToken(url, post_headers, url_user, url_password):
post_data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": url_user,
"password": url_password
},
"id": 1
}
ret = requests.post(url, data=json.dumps(post_data), headers=post_headers)
return json.loads(ret.text).get("result")
def getZabHost(url,post_headers,token):
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 2,
"auth": token,
}
request = requests.post(url, headers=post_headers, data=json.dumps(data))
dict = json.loads(request.content)
zab_ip = []
for i in dict['result']:
zab_ip.append(i['host'])
return zab_ip
def compare(zabhostlist, cmdbhostdict):
zabbixiplist = Counter(zabhostlist)
cmdbiplist = Counter(list(cmdbhostdict.keys()))
nomonip = {}
for i in list((cmdbiplist - zabbixiplist).elements()):
nomonip_value = cmdbhostdict[i]
nomonip_key = i
nomonip[nomonip_key] = nomonip_value
print(nomonip)
return nomonip
class writeToCsv(object):
def __init__(self,data,info):
self.data = data
self.info = info
def write_to_csv(self):
rows = self.data
info = self.info
csvfile = "zabbix未监控生产系统IP列表" + info + time.strftime('_%Y%m%d%H%M%S', time.localtime(time.time())) + ".csv"
# print(csvfile)
# 创建文件对象
f = open(csvfile, 'w', newline='')
# 通过文件创建csv对象
csv_write = csv.writer(f)
# writerow: 按行写入,writerows: 是批量写入
# 写入数据 取列表的第一行字典,用字典的key值做为头行数据
# csv_write.writerow(rows[0].keys())
csv_write.writerow(["未监控生产IP", "主机名", "操作系统", "电源状态"])
# 循环里面的字典,将value作为数据写入进去
ip = list(rows.keys())
hostname = list(rows.values())
for row in range(len(ip)):
csv_write.writerow([ip[row], hostname[row][0], hostname[row][1], hostname[row][2]])
# 关闭打开的文件
f.close()
print("读写完成:",csvfile)
return csvfile
def sendmail(csvfile,receiver):
sender = 'xxx@xxx.com'
smtpserver = 'xx.xx.xx.xx'
username = 'xxx@xxx.com'
password = '******'
mail_title = 'zabbix未监控生产主机IP地址'
# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = sender
message['To'] = ','.join(receiver)
message['Subject'] = Header(mail_title, 'utf-8')
# 邮件正文内容
message.attach(MIMEText('每日自动统计监控覆盖率', 'plain', 'utf-8'))
# 构造附件
att1 = MIMEApplication(open(csvfile, 'rb').read()) # 打开附件
att1.add_header('Content-Disposition', 'attachment', filename=csvfile) # 为附件命名
message.attach(att1)
smtpObj = smtplib.SMTP_SSL() # 注意:如果遇到发送失败的情况(提示远程主机拒接连接),这里要使用SMTP_SSL方法
smtpObj.connect(smtpserver)
smtpObj.login(username, password)
smtpObj.sendmail(sender, message['To'].split(','), message.as_string())
print("邮件发送成功!!!")
smtpObj.quit()
if __name__ == '__main__':
url = 'http://xx.xx.xx.xx/api_jsonrpc.php' #zabbix监控系统接口地址
post_headers = {'Content-Type': 'application/json'}
url_user = "Admin"
url_passwd = "******"
auth = getZabToken(url,post_headers,url_user,url_passwd)
zabhostlist = getZabHost(url,post_headers,auth) #获取zabbix监控主机ip地址列表
cmdbhostdict = getCmdbProdHost() #获取cmdb主机地址列表
#zabbix监控主机和cmdb主机做比较
data = compare(zabhostlist, cmdbhostdict)
#导出csv文件
info = '统计'
write = writeToCsv(data, info)
resp = write.write_to_csv()
receiver = ['hushanshan2@bngrp.com'] #y邮件接收人,多人用逗号区分开
sendmail(resp, receiver)
来源:https://www.cnblogs.com/huss2016/p/14612203.html
0
投稿
猜你喜欢
- 1.利用装饰器在视图中拦截未登录的url@login_required(login_url='/user/login/')d
- “你不必严格遵守这些原则,违背它们也不会被处以宗教刑罚。但你应当把这些原则看成警铃,若违背了其中的一条,那么警铃就会响起
- 利用空闲几天把《JavaScript权威指南》安静的读了一篇。真是一本好书呀!呵呵,这句话见的太多了。好在什么地方呢?听我慢慢道来。从开始接
- 本文实例为大家分享了python贪吃蛇游戏的具体代码,供大家参考,具体内容如下贪吃蛇游戏截图:首先安装pygame,可以使用pip安装pyg
- 一、os__file__ 获取当前运行的.py文件所在的路径(D:\PycharmProjects\
- 总结调试网站获取cookies时请查看,r.header和r.request.header这两个属性,因为cookie说不准出现在他们俩谁里
- 各位想必都知道,onfocus="this.blur()"这条代码能消除链接时的虚线框,但你有没有想过,如果你的网页上有
- 均匀性度量图像分割是图像像素分割的一种方法,当然还有其他很多的方法。这里简单的介绍下其原理和实现代码【有源码】其流程大概分为一下几步1、确定
- 假设有一名为"addnewuser"的存储过程,其内容如下:Create PROCEDURE dbo
- 如下拉框的text是<input type=button value=ggg>,那么生成的combobox里
- 现在我主要教大家如何去实战,做一个简易的知乎日报API 首先你要熟悉django的基本用法,会写模型,会写视图函数,会配置url。1.配置字
- itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机
- 一、环境配置安装 Python请确保您已经安装了 Python 3.x。可以在Python 官网下载并安装。安装所需库在命令提示符或终端中运
- 如: 2000-1-1==> 2000-01-01、2000-01-1==>2000-01-01、2000-1-01==>
- 1. 场景大家好,我是J哥。前段时间有人私信我,说自己辛辛苦苦剪辑的短视频,上传到某平台后,由于播放量太大,收到 降权 的通知,直接导致这个
- Python复合语句复合语句是包含其它语句(语句组)的语句;它们会以某种方式影响或控制所包含其它语句的执行。通常,复合语句会跨越多行,虽然在
- 提起Apple,大部分人都会提起Apple的设计,除了Apple里拥有一批天才设计师外,还因为乔布斯对于设计有着苛刻的要求。所以在IT界,A
- QZONE平台的相册功能为保证加载速度一直以来以简洁的图片排列查看模式呈现相片,随着市场上各类相册产品推陈出新,用户越来越强烈的要求个人相册
- 为什么页面出现乱码?为什么数据库里出现乱码?为什么这些乱码的出现几率飘忽不定了?诸如此类的乱码问题困扰了很多WEB开发人员。假如不将这背后的
- 1:构图图形的层次感图形和元素之间的层次感,可以在干扰视觉的同时,突出自身所想体现的主题,这种表现方式往往是比较直接而且有效的方式。我们所说