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.bkpaas.baonengmotor.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.98|10.210.99|10.210.100|10.210.101|0.0.0" #测试网段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)
python自动统计zabbix系统监控覆盖率的更多相关文章
- 通过python脚本和zabbix配合监控zookeeper的节点数
通过python脚本和zabbix配合监控zookeeper的节点数 需求描述: 在日常zabbix监控zookeeper的时候,无法通过shell来获取zookeeper的具体节点信息,没有开放具体 ...
- 自动统计zabbix过去一周监控告警
# -*- coding:utf-8 -*-import jsonimport requestsimport time,datetimeimport csv,chardetdef getToken(u ...
- Python抓取zabbix性能监控图
一.通过查询zabbix db的方式通过主机IP获取到所需要的graphid(比如CPU监控图.内存监控图等,每个图对应一个graphid),最后将图片保存到本地 注:该graph必须要在 scree ...
- python对 windows系统监控插件
在python编程的windows系统监控中,需要监控监控硬件信息需要两个模块:WMI 和 pypiwin32 .
- 25 Zabbix系统数据表结构介绍
点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 25 Zabbix系统数据表结构介绍 自学Zabbix之路15.1 Zabbix数据库表结构简单解 ...
- 建设DevOps统一运维监控平台,全面的系统监控 Zabbix VS Nagios VS Open-Falcon OR Prometheus
前言 随着Devops.云计算.微服务.容器等理念的逐步落地和大力发展,机器越来越多,应用越来越多,服务越来越微,应用运行基础环境越来多样化,容器.虚拟机.物理机不一而足.面对动辄几百上千个虚拟机.容 ...
- Python之路,Day20 - 分布式监控系统开发
Python之路,Day20 - 分布式监控系统开发 本节内容 为什么要做监控? 常用监控系统设计讨论 监控系统架构设计 监控表结构设计 为什么要做监控? –熟悉IT监控系统的设计原理 –开发一个 ...
- zabbix自动发现与自动注册、自定义监控
一.自动发现与自动注册在上面的介绍中,我们演示了手动添加一台主机的方法,虽然简单,但是当要添加的主机非常多时,也将变得非常繁琐,那么有没有一种方法,可以实现主机的批量添加呢,这样就会极大的提高运维效率 ...
- zabbix—自动发现端口并监控
自动批量检查agent开放的端口 PS:如果服务器上的应用都是固定的,不会随机产生的都可以使用自动发现端口来监控: 如果服务器会随机出现端口且每次启动程序都会改变,可以采用第二种方法,来监控指定的端 ...
随机推荐
- NGINX configure auto generator
NGINX configure auto generator The easiest way to configure a performant, secure, and stable NGINX s ...
- web cache & web storage all in one
web cache & web storage all in one web cache in action web cache best practices web storage in a ...
- 开发工具-scala处理json格式利器-json4s
1.为什么是json4s 从json4s的官方描述 At this moment there are at least 6 json libraries for scala, not counting ...
- 从跳频技术聊CDMA/WIFI之母海蒂·拉玛传奇的一生
导语:本篇的内容都是 文末的参考文章摘要而来的,本人根据自己的癖好,以及对 海蒂·拉玛 人生的感慨整理成本文. "WiFi"之母的海蒂·拉玛在中国的知名度,比起克劳德·香农应该也不 ...
- Vue使用 空白占位符
当有时候需要在页面显示时显示空格时,可以使用 ,但是使用这个占位符时,无论写多少个,就只能显示一个空格.要想显示多个空格进行占位,这种方式显然是可行的,解决方法是使用转义字符. 先看代码: <t ...
- Charles 抓取https 包
1. Recording Settings中 include 添加 host , port端口为443 2. SSL Proxying Settings 选中 Enable SSL Proxyin ...
- JAVA基础(零)—— 踩坑与错误(常更)
JAVA基础(零)-- 踩坑与错误(常更) 1 坑 考虑输入为null的情况 自动转换 x/Math.pow(10,i)*Math.pow(10,i) //由于math.pow()返回double类型 ...
- 如何删除Image元素下面的空白行及为什么行内元素有底线
翻译练习 原博客地址:Removing White Space Below Image Elements, or Why Inline Elements Have Descenders HTML中Im ...
- 记录core中GRPC长连接导致负载均衡不均衡问题 二,解决长连接问题
题外话: 1.这几天收到蔚来的面试邀请,但是自己没做准备,并且远程面试,还在上班时间,再加上老东家对我还不错.没想着换工作,导致在自己工位上做算法题不想被人看见,然后非常紧张.估计over了.不过没事 ...
- vue3中的通过proxy实现双向数据绑定的原理
1.什么是Proxy?它的作用是? 据阮一峰文章介绍:Proxy可以理解成,在目标对象之前架设一层 "拦截",当外界对该对象访问的时候,都必须经过这层拦截,而Proxy就充当了这种 ...