Shell scripting monitors memory and sends messages

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.