實現思路:
- zabbix提供了一個獲取事件的api,可以根據此api獲取zabbix原始報警數據
- 將獲取到的原始數據進行統計去重,統計觸發器出現次數,並把重複的觸發器刪除,將需要用到的數據統一放到一個列表中
- 將第二步的列表進行遍歷,並傳入到HTML中,或者也可以使用pandas直接把數據建模,然後自動生成HTML表格
- 將生成的HTML作爲郵件內容發送
定義獲取的時間間隔
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分鐘的報警數據
獲取事件數據
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,觸發器,觸發器嚴重性
將獲取到的數據進行處理
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
這裏是將重複出現的觸發器進行去重並統計出現次數,將獲取到的觸發次數以及以前的信息都放到同一個表裏,並傳給HTML
將數據發送給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監控告警</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表格中
發送報表郵件
將生成的HTML通過郵件發送
def sendmail(base_html):
from_addr = '[email protected]'
password = '沒有故事的陳師傅'
to_addr = '[email protected]'
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 獲取,或者關注公衆號“沒有故事的陳師傅”,回覆監控報表獲取
歡迎關注個人公衆號“沒有故事的陳師傅”