zabbix automatically generates monitoring reports and sends mail regularly

Realization ideas:

  1. zabbix provides an api to retrieve events from which the original alarm data of zabbix can be retrieved
  2. The original data obtained will be counted to remove duplication, count the number of flip-flops, and delete duplicate flip-flops. The data needed will be unified into a list.
  3. Traverse the list in step two and pass it into HTML, or you can use pandas to model the data directly, and then automatically generate HTML tables.
  4. Send the generated HTML as mail content

Define the time interval for acquisition

x=(datetime.datetime.now()-datetime.timedelta(minutes=30)).strftime("%Y-%m-%d %H:%M:%S")
y=(datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
def timestamp(x,y):
    p=time.strptime(x,"%Y-%m-%d %H:%M:%S")
    starttime = str(int(time.mktime(p)))
    q=time.strptime(y,"%Y-%m-%d %H:%M:%S")
    endtime= str(int(time.mktime(q)))
    return starttime,endtime

Here is the 30-minute alarm data.

Getting event data

def getevent(auth,timestamp):
    data={
        "jsonrpc": "2.0",
        "method": "event.get",
        "params": {
            "output": [
                "name",
                "severity"
            ],
            "value":1,
            "time_from":timestamp[0],
            "time_till":timestamp[1],
            "selectHosts":[
                #"hostid",
                "name"
            ]
        },
        "auth": auth,
        "id": 1
    }
    getevent=requests.post(url=ApiUrl,headers=header,json=data)
    triname=json.loads(getevent.content)['result']  

Get the event content needed by zabbix api, which includes alarm host name, host id, trigger, trigger severity

Processing the acquired data

triggers=[]
a={}
for i in triname:
     triggers.append(i['name'])
for i in triggers:
     a[i]=triggers.count(i)
list2=[]
print(triname)
#print(a)
for key in a:
     b={}
     b['name']=key
     b['host']=[i['hosts'][0]['name'] for i in triname if i['name']==key][0]
     b['severity']=[i['severity'] for i in triname if i['name']==key][0]
     b['count']=a[key]
     list2.append(b)
return list2

Here, the repeated triggers are de-duplicated and the number of occurrences is counted. The number of triggers and previous information obtained are put in the same table and passed to HTML.

Send data to HTML

def datatohtml(list2):
    tables = ''
    for i in range(len(list2)):
        name,host,severity,count = list2[i]['name'], list2[i]['host'], list2[i]['severity'], list2[i]['count']
        td = "<td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td>"%(name, host, severity, count)
        tables = tables + "<tr>%s</tr>"%td
    base_html="""
    <!DOCTYPE html>
    <html>
    <head> 
    <meta charset="utf-8"> 
    <title>zabbix Monitoring alarm</title> 
    </head>
    <body>
    <table width="900" border="0">
    <tr>
    <td colspan="2" style="background-color:#FFA500;">
    <h4>Alarm level: 1 Express:Information 2 Representation:Warning 3 Representation:General Seriousness 4 Representation:Serious 5 Representation:disaster</h4>
    </td>
    </tr>
    <tr>
    <td style="background-color:#FFD700;width:100px;">
    <TABLE BORDER=1><TR><TH>Host</TH><TH>trigger</TH><TH>Alarm level</TH><TH>Number of alerts</TH></TR>%s</TABLE>
    </td>
    </tr>
    <tr>
    <td colspan="2" style="background-color:#FFA500;text-align:center;">
    zabbix Alarm Statistics</td>
    </tr>
    </table>
    </body>
    </html>
    """ %tables
    return base_html

Traverse the incoming list and pass it into the HTML table

Send Report Mail

Send the generated HTML by mail

def sendmail(base_html):
    from_addr = 'wanger@qq.com'
    password = 'Master Chen without Stories'
    to_addr = 'wanger@163.com'
    smtp_server = 'smtp.qq.com'

    msg = MIMEText(base_html, 'html', 'utf-8')
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = Header('Zabbix Weekly Monitoring Report', 'utf-8').encode()

    try:
        server=SMTP(smtp_server,"25")   #Create a smtp object
        #server.starttls()    #Enable secure transport mode
        server.login(from_addr,password)  #Mail account login
        server.sendmail(from_addr,to_addr,msg.as_string())  #Send mail  
        server.quit()   #Disconnect smtp connection
    except smtplib.SMTPException as a:
        print (a)

The full script is available through GitHub: https://github.com/sunsharing-note/zabbix/blob/master/zhoubao.py Obtain, or pay attention to the public number "Master Chen without stories", reply to monitor report acquisition

Welcome to the personal public number "Master Chen without Stories"

Keywords: Linux Zabbix JSON github

Added by chrome29 on Fri, 09 Aug 2019 09:41:47 +0300