1. 程式人生 > >利用python指令碼監控Tomcat伺服器

利用python指令碼監控Tomcat伺服器

---------------------------------------------------------------------------------------------
[版權申明:本文系作者原創,轉載請註明出處] 
文章出處:https://blog.csdn.net/sdksdk0/article/details/80933444
作者:朱培      ID:sdksdk0     
--------------------------------------------------------------------------------------------

對於最近的開發環境,偶爾會有掛掉的現象發生,然而並沒有及時發現,下載需要新增一個監控功能,當服務掛掉的時候需要有郵件提醒,同時我們的系統每天晚上會跑定時任務,想知道有沒有異常發生,所以添加了兩個python監本監控,因為本身系統不大,所以沒必要去配置kafka+storm這種日誌監控了,只用了很簡單的方式來處理了。

1、監控tomcat是否掛掉

from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.header import Header
from os.path import getsize
from sys import exit
from re import compile, IGNORECASE
import sys, time
import os


#定義主機 帳號 密碼 收件人 郵件主題

#定義主機 帳號 密碼 收件人 郵件主題
mail_info = {
    "from": "[email protected]
", "to": "[email protected]", "hostname": "smtp.exmail.qq.com", "username": "[email protected]sogoucloud.cn", "password": "123456", "mail_subject": "qybd伺服器異常", "mail_text": "hello, tomcat伺服器出現異常了!,請及時處理", "mail_encoding": "utf-8" } #傳送郵件函式 def send_mail(error): #定義郵件的頭部資訊 #連線SMTP伺服器,然後傳送資訊 smtp = SMTP_SSL(mail_info["hostname"]) smtp.set_debuglevel(1) smtp.ehlo(mail_info["hostname"]) smtp.login(mail_info["username"], mail_info["password"]) msg = MIMEText(error, "plain", mail_info["mail_encoding"]) msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"]) msg["from"] = mail_info["from"] msg["to"] = mail_info["to"] smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string()) smtp.quit() def isRunning(process_name): try: process = len(os.popen('ps aux | grep "' + process_name + '" | grep -v grep').readlines()) if process >= 1: return True else: return False except: print("Check process ERROR!!!") return False #呼叫傳送郵件函式傳送郵件 if __name__ == '__main__': process_name = "qybd" isrunning = isRunning(process_name) print(isrunning) if isrunning == False: send_mail("老鐵!qybd伺服器掛了!")

2、新增crontab定時任務:

*/3 * * * * python  /usr/tools/qybd/cmd/sendEmail.py >> /usr/tools/qybd/cmd/tomcatlife.py.log 2>&1

3、使用crontab -u root -l 命令檢視當前執行的定時任務

4、監控日誌的指令碼

from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.header import Header
from os.path import getsize
from sys import exit
from re import compile, IGNORECASE


#定義主機 帳號 密碼 收件人 郵件主題

#定義主機 帳號 密碼 收件人 郵件主題
mail_info = {
    "from": "[email protected]",
    "to": "[email protected]",
    "hostname": "smtp.exmail.qq.com",
    "username": "[email protected]",
    "password": "123456",
    "mail_subject": "qybd伺服器異常",
    "mail_text": "hello, tomcat伺服器出現異常了!,請及時處理",
    "mail_encoding": "utf-8"
}

#定義tomcat日誌檔案位置
tomcat_log = '/usr/tools/qybd/tomcat/logs/catalina.out'

#該檔案是用於記錄上次讀取日誌檔案的位置,執行指令碼的使用者要有建立該檔案的許可權
last_position_logfile = '/usr/tools/qybd/tomcat/logs/last_position.txt'

#匹配的錯誤資訊關鍵字的正則表示式
pattern = compile(r'Exception|^\t+\bat\b',IGNORECASE)


#傳送郵件函式
def send_mail(error):

    #定義郵件的頭部資訊
    #連線SMTP伺服器,然後傳送資訊
    smtp = SMTP_SSL(mail_info["hostname"])
    smtp.set_debuglevel(1)
    smtp.ehlo(mail_info["hostname"])
    smtp.login(mail_info["username"], mail_info["password"])
    msg = MIMEText(error, "plain", mail_info["mail_encoding"])
    msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"])
    msg["from"] = mail_info["from"]
    msg["to"] = mail_info["to"]
    smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string())
    smtp.quit()


#讀取上一次日誌檔案的讀取位置
def get_last_position(file):
    try:
        data = open(file,'r')
        last_position = data.readline()
        if last_position:
            last_position = int(last_position)
        else:
            last_position = 0
    except:
        last_position = 0

    return last_position

#寫入本次日誌檔案的本次位置
def write_this_position(file,last_positon):
    try:
        data = open(file,'w')
        data.write(str(last_positon))
        data.write('\n' + "Don't Delete This File,It is Very important for Looking Tomcat Error Log !! \n")
        data.close()
    except:
        print "Can't Create File !" + file
        exit()

#分析檔案找出異常的行
def analysis_log(file):

    error_list = []                                         #定義一個列表,用於存放錯誤資訊.
    try:
        data = open(file,'r')
    except:
        exit()
    last_position = get_last_position(last_position_logfile) #得到上一次檔案指標在日誌檔案中的位置
    this_postion = getsize(tomcat_log)                      #得到現在檔案的大小,相當於得到了檔案指標在末尾的位置
    if this_postion < last_position:                        #如果這次的位置 小於 上次的位置說明 日誌檔案輪換過了,那麼就從頭開始
        data.seek(0)
    elif this_postion == last_position:                     #如果這次的位置 等於 上次的位置 說明 還沒有新的日誌產生
        exit()
    elif this_postion > last_position:                      #如果是大於上一次的位置,就移動檔案指標到上次的位置
        data.seek(last_position)

    for line in data:
        if pattern.search(line):
            error_list.append(line)
    write_this_position(last_position_logfile,data.tell())  #寫入本次讀取的位置
    data.close()

    return ''.join(error_list)                              #形成一個字串

#呼叫傳送郵件函式傳送郵件
error_info = analysis_log(tomcat_log)
if error_info:
    send_mail(error_info)
5、新增crontab定時任務:

*/10 * * * * python  /usr/tools/qybd/cmd/tomcat_log_error_analysis.py >> /usr/tools/qybd/cmd/crontest.py.log 2>&1

效果如下: