1. 程式人生 > >監控mysql和mongo數據庫服務腳本--shell編寫

監控mysql和mongo數據庫服務腳本--shell編寫

郵件內容 ccs main min def ack dmi 執行 import

應帥氣的領導要求,需要腳本監控生產環境mysql和mongo數據庫服務。不僅要connect successful還要進行數據交互進一步確認數據庫服務正常。

代碼如下:

    #!/bin/bash
    #author:吳青聰
    #email:[email protected]
    #encoding: utf-8

    #聲明四個數據,存放數據庫信息 ip、用戶、密碼、端口
    declare -a host 
    declare -a user
    declare -a passwd
    declare -a port

    #定義一個計數變量,初始值 0
    n=0 
    #指明收件郵箱
    [email protected]  

    #按行讀取記錄了數據地址端口用戶名密碼信息的文件,存放進對應數組,此處文件為mysqldb_message.txt,其格式如下:
    #host:192.168.0.32 user:test passwd:123456 port:3306    註意行首無空格
    while read line 
    do
            eval $(echo $line | awk -F"[: ]" ‘{printf("host[$n]=%s; user[$n]=%s; passwd[$n]=%s; port[$n]=%s",$2,$4,$6,$8)}‘)
        let n++
    done < mysqldb_message.txt

    #檢測數據庫服務
    let n--
    for i in $(seq 0 $n);do
        # 檢測命令
        mysql -h${host[$i]} -u${user[$i]} -p${passwd[$i]} -P${port[$i]} -e "select 1 from dual;" --connect-timeout=5 &> /dev/null
        #判斷執行結果$?,為0執行成功,為1出現錯誤異常
        if [ $? -ne 0 ]
        then
            python3 mail.py $mail "mysqldb down " "please check mysql-service on ${host[$i]}"
            echo "mysql$i is down"
        else
            # python3 mail.py $mail "mysqldb is fine " "Do not need check mysql-service on ${host[$i]} "
            echo "mysql$i is fine"
        fi

    done

    #檢測mongodb
    #清空計數變量
    n=0
    #按行讀取記錄了數據地址端口用戶名密碼信息的文件,存放進對應數組,此處文件為mongodb_message.txt,其格式如下:
    #host:127.0.0.1 user:root passwd:root port:27017 authDB:admin   註意行首無空格
    while read line
    do
                    eval $(echo $line | awk -F"[: ]" ‘{printf("host[$n]=%s; user[$n]=%s; passwd[$n]=%s; port[$n]=%s; db[$n]=%s",$2,$4,$6,$8,$10)}‘)
        let n++
    done < mongodb_message.txt

    let n--

    for i in $(seq 0 $n);do

        echo "show tables maxTimeMS(5000)" | mongo ${host[$i]}:${port[$i]}/${db[$i]} -u ${user[$i]} -p ${passwd[$i]} &> /dev/null

        if [ $? -ne 0 ]
        then
            server=${host[$i]}
            python3 mail.py $mail "mongodb down " "please check mysql-service on $server"
            echo "mongodb$i is down"
        else
            # python3 mail.py $mail "mongodb is fine " "Do not need check mysql-service on ${host[$i]}"
            echo "mongodb$i is fine"
        fi

    done

郵件腳本為參考他人腳本,用Python編寫,存放上述代碼腳本同目錄即可,郵件腳本代碼如下:

#!/usr/bin/env python
# 
#  encoding: utf-8

import sys
import smtplib  # 加載smtplib模塊
import traceback
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

login_name = ‘[email protected]‘  # 發件人郵箱賬號,為了後面易於維護,所以寫成了變量
login_pass = ‘*******‘      # 因發博客而隱藏,自己腳本中需要指定
smtp_port = 465

def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((                 Header(name, ‘utf-8‘).encode(),                 addr))
        # addr.encode(‘utf-8‘) if isinstance(addr, unicode) else addr))

def send_mail(sender, recps, Ccs, subject, htmlmsg, fileAttachment):
        smtpserver = ‘smtp.exmail.qq.com‘

        receivers = recps + Ccs

        try:
                # msg = MIMEText(htmlmsg, ‘html‘, ‘utf-8‘)
                msg = MIMEMultipart()

                msg.attach(MIMEText(htmlmsg, ‘html‘, ‘utf-8‘))

                # msg[‘Subject‘] = subject
                msg[‘Subject‘] = Header(subject, ‘utf-8‘).encode()
                # msg[‘From‘] = sender
                msg[‘From‘] = _format_addr(sender)

                Recp = []
                for recp in recps:
                        Recp.append(_format_addr(recp))

                ccs = []
                for cc in Ccs:
                        ccs.append(_format_addr(cc))

                msg[‘To‘] = ‘,‘.join(Recp)
                msg[‘Cc‘] = ‘,‘.join(ccs)

                # if fileAttachment!=‘‘ :
                #     # 附件
                for file in fileAttachment:
                        part = MIMEApplication(open(file, ‘rb‘).read())
                        attFileName = file.split(‘/‘)[-1]
                        part.add_header(‘Content-Disposition‘, ‘attachment‘, filename=attFileName)
                        msg.attach(part)
                # part = MIMEApplication(open(fileAttachment, ‘rb‘).read())
                # part.add_header(‘Content-Disposition‘, ‘attachment‘, filename=fileAttachment)
                # msg.attach(part)

                smtp = smtplib.SMTP_SSL()
                smtp.connect(smtpserver, smtp_port)
                smtp.login(login_name, login_pass)
                #        smtp.login(username, password)
                smtp.sendmail(sender, receivers, msg.as_string())
                smtp.quit()
                print(‘SendEmail success‘)
        except:
                traceback.print_exc()

def main():
        to=sys.argv[1]
        subject=sys.argv[2]
        content=sys.argv[3]

        # send_mail("監控中心<[email protected]>", ["吳青聰<[email protected]>"], [], subject, "郵件內容2", "")
        send_mail("監控中心<[email protected]>", [to], [], subject, content, "")

if __name__ == "__main__":
        main()

監控mysql和mongo數據庫服務腳本--shell編寫