1. Prepare the tool to send the message:
#!/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 (' Mail sent successfully email has send out! ')
if __name__ = = ' __main__ ':
msg = Email.mime.multipart.MIMEMultipart ()
msg[' Subject ' = ' sent subject '
msg[' from ' = ' sent mailbox '
msg[' to ' = ' received mailbox '
user = ' users '
PWD = ' password '
content= '%s\n%s '% (' \ n '. Join (Sys.argv[1:4]), '. Join (sys.argv[4:]) #格式处理, specifically for our message format
txt = email.mime.text.MIMEText (content, _charset= ' Utf-8 ')
Msg.attach (TXT)
SendMail (SERVER,PORT,USER,PWD,MSG)
2. Copy the above file contents to/usr/bin/mail and Chmod+x/usr/bin/mail
3. Then create a new script servermonitor.sh
#!/bin/bash
Mem_limit=0 #内存使用超过90% Alarm
function Monitor_mem () {
mem_total= ' free |awk ' Nr==2{print
mem_user= ' free |awk ' nr==2{print $ '
mem_per= ' echo ' scale=2; $mem _user/$mem _total "|bc-l|cut-d.-f2 "
if [$mem _per-gt $mem _limit]
Then
msg= "time:$ (data +%f_%t)
hostname:$ (HOSTNAME)
ipaddr:$ (ifconfig |awk ' Nr==18{print $} ' |awk-f: ' {print $} ')
msg:memory usage exceeds the Limit,current value is ${mem_per}% "
Echo $msg
/usr/bin/mail $msg
fi
}
Monitor_mem &>>/root/wang/monitor.log
4. Write the Scheduled tasks:
* * * * * */root/servermonitor.sh #每分钟执行一次这个脚本
Shell scripting monitors memory and sends messages