小樱 发表于 2018/9/24 05:39

Linux centos物理独立服务器使用bash检测硬盘坏道自动mail邮件报警通知脚本

好了,下方代码,你只用改SEND_TO和mailgun的API KEY就行了,当然,如果你的sendmail可用就不用管mailgun

sendmail客户端,只要没卸载就可以,我一般卸载了,不过也有的会装ssmtp,因为sendmail一般会进垃圾箱,ssmtp可以把sendmail命令变成用smtp发邮件


说明实现,通过smartctl -H,没passed的就告警
所以要安装运行库
yum -y install smartmontools
手动尝试运行,确保当前服务器无坏道状态
smartctl -H /dev/sda
正常硬盘返回数据
=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

代码
#!/usr/bin/env bash

SEND_TO="@gmail.com"
IP_ADDRESSES=$(ifconfig|grep 'inet '|grep -v '127.0.0.1'|awk '{print $2}')

function send_mail {
    echo "IP address: ${IP_ADDRESSES}" | mail -s "$1 on <$HOSTNAME>!" ${SEND_TO}
    curl -s --user 'api:key-' \
      https://api.mailgun.net/v3/mg.oldcai.com/messages \
      -F from='Disk <notify@mg.oldcai.com>' \
      -F to=${SEND_TO} \
      -F subject="$1 on <$HOSTNAME>!" \
      -F text="IP address: ${IP_ADDRESSES}"
    date
}

function alert_if_empty {
if [ $? != 0 ]; then
    send_mail 'Disk Error'
fi
}

function check_drive {
    echo "checking ${1}"
    smartctl -l error /dev/${1} | grep 'No Errors Logged\|SMART Error Log not supported'
    alert_if_empty
    smartctl -H /dev/${1} | grep 'PASSED'
    alert_if_empty
}

lsblk -d|awk '{print $1}'|grep -v 'NAME' | while read drive;
do
    check_drive ${drive}
done

df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
    echo $output
    usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
    re='^+


    if [[ $usep =~ $re ]] ; then
      partition=$(echo $output | awk '{ print $2 }' )
      if (( $usep > 95 )); then
            echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
            send_mail "Disk Almost out of disk space $usep%"
      fi
    fi
done

页: [1]
查看完整版本: Linux centos物理独立服务器使用bash检测硬盘坏道自动mail邮件报警通知脚本