python自动统计zabbix系统监控覆盖率的示例代码

作者:huss 时间:2023-11-14 08:23:03 

脚本主要功能:

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

标签:python,统计,zabbix
0
投稿

猜你喜欢

  • pytorch实现用CNN和LSTM对文本进行分类方式

    2023-07-16 18:05:13
  • python抓取网页内容并进行语音播报的方法

    2021-03-08 14:02:53
  • MYSQL数据库使用UTF-8中文编码乱码的解决办法

    2024-01-23 00:22:28
  • pytho matplotlib工具栏源码探析一之禁用工具栏、默认工具栏和工具栏管理器三种模式的差异

    2021-08-31 05:15:21
  • Python实现图片裁剪的两种方式(Pillow和OpenCV)

    2022-07-08 12:42:47
  • SQL Server管理 这些你懂吗?

    2011-07-01 13:40:23
  • 在Python中通过机器学习实现人体姿势估计

    2022-05-20 13:08:25
  • python3.7 使用pymssql往sqlserver插入数据的方法

    2021-10-13 00:23:34
  • MySQL数据库备份过程的注意事项

    2024-01-26 23:16:59
  • 在python带权重的列表中随机取值的方法

    2022-05-09 01:44:25
  • Python中集合类型(set)学习小结

    2023-03-18 13:56:27
  • Python基于Tkinter实现的记事本实例

    2021-12-30 09:25:17
  • 如何在Django配置文件里配置session链接

    2022-09-08 18:17:33
  • 详解操作python容器的内置通用函数

    2022-12-09 04:52:39
  • python 如何利用chinese_calendar 获取上一个工作日日期

    2022-01-12 12:07:32
  • MySQL窗口函数实现榜单排名

    2024-01-16 20:22:22
  • Python产生batch数据的操作

    2022-11-22 16:00:59
  • 最常用的PHP正则表达式收集整理

    2024-05-03 15:34:56
  • 基于php无限分类的深入理解

    2023-11-15 04:07:39
  • 使用php+swoole对client数据实时更新(一)

    2024-05-03 15:13:08
  • asp之家 网络编程 m.aspxhome.com