Shell script to realize memory management and email alerts when memory usage is too high
One create email alert script
1.1 Install Mail Components
Use the Xmanager Enterprise 5 tool to import the software package into the /root directory of the Linux virtual machine, and
then perform a series of operations such as decompression, copying, and permissions
[root@localhost ~]# tar -zxvf sendEmail-v1.56.tar.gz
[root@localhost ~]# cp sendEmail-v1.56/sendEmail /usr/local/bin/
[root@localhost ~]# chmod 755 /usr/local/bin/sendEmail
[root@localhost ~]# vim /opt/sendEmail.sh
1.2 Email configuration script
Need to modify the variables username, password, from_email_address in the script, where password is the QQ mailbox authorization code
#!/bin/bash
# 脚本的日志文件
LOGFILE="/tmp/Email.log"
:>"$LOGFILE"
exec 1>"$LOGFILE"
exec 2>&1
SMTP_server='smtp.qq.com' # SMTP服务器,变量值需要自行修改
username='[email protected]' # 用户名,变量值需要自行修改
password='xxxxxxx' # 密码(QQ邮箱用的是授权码),变量值需要自行修改
from_email_address='[email protected]' #### 发件人Email地址,变量值需要自行修改
to_email_address="$1" # 收件人Email地址,tang传入的第一个参数
message_subject_utf8="$2" # 邮件标题,root传入的第二个参数
message_body_utf8="$3" # 邮件内容,root传入的第三个参数
# 转换邮件标题为GB2312,解决邮件标题含有中文,收到邮件显示乱码的问题。
message_subject_gb2312=`iconv -t GB2312 -f UTF-8 << EOF
$message_subject_utf8
EOF`
[ $? -eq 0 ] && message_subject="$message_subject_gb2312" || message_subject="$message_subject_utf8"
# 转换邮件内容为GB2312,解决收到邮件内容乱码
message_body_gb2312=`iconv -t GB2312 -f UTF-8 << EOF
$message_body_utf8
EOF`
[ $? -eq 0 ] && message_body="$message_body_gb2312" || message_body="$message_body_utf8"
# 发送邮件
sendEmail='/usr/local/bin/sendEmail'
set -x
$sendEmail -s "$SMTP_server" -xu "$username" -xp "$password" -f "$from_email_address" -t "$to_email_address" -u "$message_subject" -m "$message_body" -o message-content-type=text -o message-charset=gb2312
1.3 Send mail test
[root@localhost ~]# chmod +x /opt/sendEmail.sh
[root@localhost ~]# /opt/sendEmail.sh [email protected] warning warning
Two memory management
Write a memory monitoring script in the shell, and send an email alert when the usage exceeds 80%.
Filter the total and used in the memory information. Here, use the awk tool
#!/bin/bash
total=`free -m |awk 'NR==2{print $2}'`
used=$[`free -m |awk 'NR==2{print $3}'`*1000] #由于无法进行浮点数计算,所以此处把被除数和商扩大1000倍,效果一样
bi=$[$used / $total]
if [ $bi -gt 800 ];then
/opt/sendEmail.sh [email protected] warning warning!!!
fi
Email successfully received