Example code for python to automatically count the monitoring coverage rate of zabbix system

  • 2021-10-24 23:15:48
  • OfStack

Main functions of scripts:

1) Collecting ip addresses of all monitoring hosts through zabbix api interfaces;

2) Collect IP address, host name, operating system and power state of all production hosts through cmdb system (blue whale) interface;

3) Comparing the data returned in the above two steps, finding out the ip address of the unmonitored host and generating an csv file;

4) Send mail.

The script is as follows:


#!/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

#  From cmdb The system acquires the virtualized production host 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"   # Test network segment 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

# Get zabbix System login authentication 
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 Production system not monitored IP List " + info + time.strftime('_%Y%m%d%H%M%S', time.localtime(time.time())) + ".csv"
    # print(csvfile)
    #  Create a file object 
    f = open(csvfile, 'w', newline='')

    #  Create from a file csv Object 
    csv_write = csv.writer(f)

    # writerow:  Write by line, writerows:  Is a batch write 
    #  Write data   Take the first of the list 1 Line dictionary, using the key value of the dictionary as the first line data 
    # csv_write.writerow(rows[0].keys())
    csv_write.writerow([" Production is not monitored IP", " Hostname ", " Operating system ", " Power state "])

    #  The dictionary inside the loop will value Write it in as data 
    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]])

    #  Close an open file 
    f.close()
    print(" Read and write complete :",csvfile)
    return csvfile

def sendmail(csvfile,receiver):
  sender = 'xxx@xxx.com'
  smtpserver = 'xx.xx.xx.xx'
  username = 'xxx@xxx.com'
  password = '******'
  mail_title = 'zabbix Production host not monitored IP Address '

  #  Create 1 Examples with attachments 
  message = MIMEMultipart()
  message['From'] = sender
  message['To'] = ','.join(receiver)
  message['Subject'] = Header(mail_title, 'utf-8')

  #  Message body content 
  message.attach(MIMEText(' Automatically count the monitoring coverage rate every day ', 'plain', 'utf-8'))

  #  Structural attachment 
  att1 = MIMEApplication(open(csvfile, 'rb').read()) #  Open attachment 
  att1.add_header('Content-Disposition', 'attachment', filename=csvfile) #  Name the attachment 
  message.attach(att1)

  smtpObj = smtplib.SMTP_SSL() #  Note: If you encounter a send failure (prompting the remote host to reject the connection), you should use the SMTP_SSL Method 
  smtpObj.connect(smtpserver)
  smtpObj.login(username, password)
  smtpObj.sendmail(sender, message['To'].split(','), message.as_string())
  print(" The mail was sent successfully! ! ! ")
  smtpObj.quit()

if __name__ == '__main__':
  url = 'http://xx.xx.xx.xx/api_jsonrpc.php'         #zabbix Monitoring system interface address 
  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)       # Get zabbix Monitoring host ip Address list 
  cmdbhostdict = getCmdbProdHost()               # Get cmdb Host address list 
  #zabbix Monitor the host and cmdb Host comparison 
  data = compare(zabhostlist, cmdbhostdict)

  # Export csv Documents 
  info = ' Statistics '
  write = writeToCsv(data, info)
  resp = write.write_to_csv()
  receiver = ['hushanshan2@bngrp.com']   #y Mail recipients, many people are distinguished by commas 
  sendmail(resp, receiver)

Related articles: