shell腳本-監控及郵件提醒


首先寫一個郵件提醒python文件

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import smtplib
import email.mime.multipart
import email.mime.text

server = 'smtp.163.com'
port = '25'

def sendmail(server,port,user,pwd,msg):
    smtp = smtplib.SMTP()
    smtp.connect(server,port)
    smtp.login(user, pwd)
    smtp.sendmail(msg['from'], msg['to'], msg.as_string())
    smtp.quit()
    print('郵件發送成功email has send out !')


if __name__ == '__main__':
    msg = email.mime.multipart.MIMEMultipart()
    msg['Subject'] = '服務器報警請注意!'
    msg['From'] = 'python4_mail@163.com'
    msg['To'] = 'longbaby1101@qq.com'
    user = 'python4_mail'
    pwd = 'sbalex3714'
    content='%s\n%s' %('\n'.join(sys.argv[1:4]),' '.join(sys.argv[4:])) #格式處理,專門針對我們的郵件格式

    txt = email.mime.text.MIMEText(content, _charset='utf-8')
    msg.attach(txt)

    sendmail(server,port,user,pwd,msg)

然后寫自己的監控腳本

#/bin/bash
bu=`free | awk 'NR==2{print $6}'`
to=`free | awk 'NR==2{print $2}'`
mem=`expr "scale=2;$bu/$to" |bc -l | cut -d. -f2`
if(($mem >= 70))
        then
        msg="TIME:$(date +%F_%T)
                 HOSTNAME:$(hostname)
                 IPADDR:$(ifconfig |awk 'NR==2{print $2}')
                 MSG:內存high了high了!已經用了${mem}%"
            echo $msg
        /usr/bin/pymail.py $msg
fi
systemctl status nginx
if(($?!=0))
        then
                msg="TIME:$(date +%F_%T)
                 HOSTNAME:$(hostname)
                 IPADDR:$(ifconfig |awk 'NR==2{print $2}')
                 MSG:   Nginx 進程出現異常請注意查看!"
            echo $msg
        /usr/bin/pymail.py $msg
fi
systemctl status nfs
if(($?!=0))
        then
                msg="TIME:$(date +%F_%T)
                 HOSTNAME:$(hostname)
                 IPADDR:$(ifconfig |awk 'NR==2{print $2}')
                 MSG:   NFS 進程出現異常請注意查看!"
            echo $msg
        /usr/bin/pymail.py $msg
fi

之后再定時任務中寫入每分鍾執行一次

把兩個nginx 和 nfs 服務關閉

等待一分鍾之后

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM