1. 程式人生 > >python指令碼監控logstash程序並郵件告警

python指令碼監控logstash程序並郵件告警

supervisor雖然也能拉起來logstash程序,但是有時候supervisor也會掛,也有時會拉不起,就算拉起來了也沒有郵件告警功能 ,所以編寫一個python指令碼監控所有伺服器,以下程式碼只列舉了一臺伺服器,需要更多伺服器在列表裡面新增就行!

(日誌採集過程中連續幾天資料異常,由於伺服器太多,當時不太想一一去將近40臺伺服器檢視logstash程序,但又一直查不出原因,後來就每臺伺服器檢視logstash程序,果然發現3臺採集搜尋日誌的logstash程序沒了,然後就編寫了此指令碼監控,效果很好)

# coding=utf-8
#!/usr/bin/env python
_author_ = 'liuzc'
import os
import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 定義日誌輸出檔案
log = "/home/data/liuzc/check_ps/logstash_process.log"
ipAndUrlList = [
        ["
[email protected]
","aiu-service-agent.conf"] ] def checkPS(): beginTime = datetime.datetime.now() print("開始檢查程序。。。時間為:%s" % beginTime) for ipAndUrl in ipAndUrlList: ip = ipAndUrl[0] configName = ipAndUrl[1] alist = ip.split("@") username = alist[0] #將程序資訊寫入log檔案 os.system("ssh %s ps -ef |grep %s |grep -v 'grep'> %s" %(ip,configName,log)) #判斷檔案大小,當logstash沒有執行時上一步寫入log的內容為空 if not(os.path.getsize(log)): # 重啟程序 print("ip為%s,配置檔名稱為 %s 不在程序中,正在重啟程序......" %(ip,configName)) # os.system('ssh %s /home/%s/elk/logstash/bin/logstash -f %s &'%(ip,username,url)) os.system('ssh %s /home/%s/elk/logstash/bin/logstash -f /home/%s/elk/logstash/etc/%s &' % (ip, username,username, configName)) print("重啟程序成功,開始傳送郵件") # 傳送郵件 sendMail(ip,configName) endTime = datetime.datetime.now() print("檢查程序結束。。。時間為:%s" % endTime) print("=============================================================================") def sendMail(ip,configName): # 當前時間 now = datetime.datetime.now() # 第三方 SMTP 服務 mail_host = "mail.qq.com" # 設定伺服器 mail_user = "
[email protected]
" # 使用者名稱 mail_pass = "deretrgt4556h" # 口令 sender = '[email protected]' receivers = ['[email protected]','[email protected]','[email protected]'] # 接收郵件,可設定為你的QQ郵箱或者其他郵箱 message = MIMEText('logstash程序異常,但已自動重啟...伺服器為 %s , 配置檔案為 %s , 時間為 %s ' %(ip,configName,now), 'plain', 'utf-8') message['From'] = Header("logstash_ps", 'utf-8') message['To'] = Header("users", 'utf-8') subject = 'logstash程序異常告警!!!' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 為 SMTP 埠號 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print ("郵件傳送成功!!!") except smtplib.SMTPException: print("Error: 郵件傳送失敗。。。") if __name__ == '__main__': while True: try: checkPS() except Exception as e: print('Error:', e)