婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > python自動統計zabbix系統監控覆蓋率的示例代碼

python自動統計zabbix系統監控覆蓋率的示例代碼

熱門標簽:西藏智能外呼系統五星服務 工廠智能電話機器人 千陽自動外呼系統 400電話申請服務商選什么 清遠360地圖標注方法 江蘇客服外呼系統廠家 原裝電話機器人 平頂山外呼系統免費 在哪里辦理400電話號碼

腳本主要功能:

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)

到此這篇關于python自動統計zabbix系統監控覆蓋率的文章就介紹到這了,更多相關python統計zabbix內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Python系統監控模塊psutil功能與經典用法分析
  • Python使用psutil獲取進程信息的例子
  • Python中psutil的介紹與用法
  • python使用psutil模塊獲取系統狀態
  • Python psutil模塊簡單使用實例
  • Python使用psutil庫對系統數據進行采集監控的方法

標簽:白城 日照 錦州 股票 西安 天水 隨州 安慶

巨人網絡通訊聲明:本文標題《python自動統計zabbix系統監控覆蓋率的示例代碼》,本文關鍵詞  python,自動,統計,zabbix,系統,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《python自動統計zabbix系統監控覆蓋率的示例代碼》相關的同類信息!
  • 本頁收集關于python自動統計zabbix系統監控覆蓋率的示例代碼的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 金川县| 昌图县| 台东县| 额济纳旗| 红安县| 锡林浩特市| 行唐县| 九龙县| 洪泽县| 八宿县| 大宁县| 宜都市| 莱西市| 清镇市| 乾安县| 句容市| 东兰县| 清远市| 琼海市| 五家渠市| 隆化县| 博兴县| 开原市| 陆河县| 邵阳县| 武功县| 敦煌市| 北安市| 江门市| 万宁市| 玛纳斯县| 平阳县| 黄大仙区| 宁都县| 邛崃市| 金门县| 确山县| 金寨县| 沽源县| 屯昌县| 轮台县|