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
這裏是獲取的30分鐘的報警數據html
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']
經過zabbix api獲取須要用到的事件內容,其中包含報警主機名,主機id,觸發器,觸發器嚴重性 git
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
這裏是將重複出現的觸發器進行去重並統計出現次數,將獲取到的觸發次數以及之前的信息都放到同一個表裏,並傳給HTMLgithub
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監控告警</title> </head> <body> <table width="900" border="0"> <tr> <td colspan="2" style="background-color:#FFA500;"> <h4>告警級別: 1 表示:信息 2 表示:告警 3 表示:通常嚴重 4 表示:嚴重 5 表示:災難</h4> </td> </tr> <tr> <td style="background-color:#FFD700;width:100px;"> <TABLE BORDER=1><TR><TH>主機</TH><TH>觸發器</TH><TH>告警級別</TH><TH>告警次數</TH></TR>%s</TABLE> </td> </tr> <tr> <td colspan="2" style="background-color:#FFA500;text-align:center;"> zabbix告警統計</td> </tr> </table> </body> </html> """ %tables return base_html
將傳入的列表進行遍歷並傳入HTML表格中json
將生成的HTML經過郵件發送api
def sendmail(base_html): from_addr = 'wanger@qq.com' password = '沒有故事的陳師傅' 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本週監控報表', 'utf-8').encode() try: server=SMTP(smtp_server,"25") #建立一個smtp對象 #server.starttls() #啓用安全傳輸模式 server.login(from_addr,password) #郵箱帳號登陸 server.sendmail(from_addr,to_addr,msg.as_string()) #發送郵件 server.quit() #斷開smtp鏈接 except smtplib.SMTPException as a: print (a)
完整腳本可經過GitHub:https://github.com/sunsharing-note/zabbix/blob/master/zhoubao.py 獲取,×××陳師傅」,回覆監控報表獲取安全
歡×××陳師傅」app