#!/usr/bin/python # -*- coding: utf-8 -*- import requests,time import json,sys,re,os zabbixserver_url ='http://192.168.99.200/index.php' #定義遠端的web服務器地址,將圖片複製到遠端的web目錄下 pname_path='http://47.103.15.51/dingding_pic/' #定義獲取的圖片地址 testUrl = "http://192.168.99.200/chart.php" host='192.168.99.200' def get_itemid(): itemid=re.search(r'ITEM ID:(\d+)',sys.argv[2]).group(1) return itemid def get_picture(itemid,pname): #構建session,或者能夠一次構建以後使用cookie登陸 myRequests = requests.Session() try: loginHeaders = { "Host":host, "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" } # 構建登陸所需的信息 playLoad = { "name": "Admin", "password": 'zabbix', "autologin": "1", "enter": "Sign in", } myRequests.post(url=zabbixserver_url, headers=loginHeaders, data=playLoad) testUrlplayLoad = { "from": "now-10m", "to": "now", "itemids": itemid, "width": "700", } testGraph = myRequests.get(url=testUrl,params=testUrlplayLoad) IMAGEPATH = os.path.join('/usr/lib/zabbix/alertscripts/dingding_pic/', pname) #將獲取到的圖片數據寫入到文件中去 with open(IMAGEPATH,'wb') as f: f.write(testGraph.content) os.system("sudo scp %s root@47.103.15.51:/usr/share/nginx/html/dingding_pic" %IMAGEPATH) pname_url = pname_path+pname return pname_url except Exception as e: print(e) return False #構造發送消息的請求 def send_msg(pname_url,info3): headers = {'Content-Type': 'application/json;charset=utf-8'} print(info3) data = { "msgtype": "markdown", "markdown": { "title": info1, "text": "## 通知:\n"+info3+"![screenshot](%s)\n"%(pname_url) }, "at":{ "atMobiles": reminders, "isAtAll": False, }, } r = requests.post(url=webhook_url,json=data,headers=headers) print(r.text) #對報警信息進行格式化 def info_text(): new_text = "" x = info2.split('\n') for i in x: if re.search('ITEM ID',str(i)): pass else: new_text+="- "+str(i)+('\n') print(type(new_text)) return new_text if __name__ == '__main__': #將報警信息寫入日誌 os.system("echo hello >> /tmp/syslog.md") pname = str(int(time.time()))+'.png' info1 = str(sys.argv[1]) info2 = str(sys.argv[2]) info3 = info_text() with open('/tmp/syslog.md','a') as f: f.write(info1) f.write(info2) f.close() reminders = [] webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=771ded387e6be652c51a2b6c83cade4e048e3da4fdfe128f1db6b124b87df18a' itemid = get_itemid() pname_url=get_picture(itemid,pname) print(pname_url) send_msg(pname_url,info3)
點擊配置菜單中的動做,建立動做,而後根據圖片進行填寫 php
操做 默認標題 Zabbix告京:服務器:{HOSTNAME}發生: {TRIGGER.NAME}故障! ITEMID:{ITEM.ID} 告警主機:{HOST.NAME} 告警主機:{HOST.IP} 告警時間:{EVENT.DATE} {EVENT.TIME} 告警等級:{TRIGGER.SEVERITY} 告警信息: {TRIGGER.NAME} 告警項目:{TRIGGER.KEY} 問題詳情:{ITEM.NAME}:{ITEM.VALUE} 當前狀態:{TRIGGER.STATUS}:{ITEM.VALUE} 事件ID:{EVENT.ID} 恢復操做 Zabbix告京:服務器:{HOST.NAME}發生: {TRIGGER.NAME}已恢復! ITEMID:{ITEM.ID} 告警主機:{HOST.NAME} 告警主機:{HOST.IP} 告警時間:{EVENT.DATE} {EVENT.TIME} 告警等級:{TRIGGER.SEVERITY} 告警信息: {TRIGGER.NAME} 告警項目:{TRIGGER.KEY} 問題詳情:{ITEM.NAME}:{ITEM.VALUE} 當前狀態:{TRIGGER.STATUS}:{ITEM.VALUE} 事件ID:{EVENT.ID}
能夠手動觸發一個報警測試效果
html
歡迎關注我的公號「沒有故事的陳師傅」
python