編寫ping腳本檢測網絡狀态,結合計劃任務自動發送郵件告警
系統版本
[[email protected] ~]# cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core)
如果不想使用系統自帶郵件包,先進行删除
#rpm -qa |grep mailx sendmail
#rpm -e xxx
一、yum安裝依賴包
[[email protected] ~]# yum install -y mailx
[[email protected] ~]# yum install -y sendmail
[[email protected] ~]# yum install -y sendmail-cf
二、配置sendmail.mc
[[email protected] ~]# vim /etc/mail/sendmail.mc
把這兩句開頭的dnl去掉,在sendmail檔案中,dnl是注釋的意思,去掉dnl開啟相應的設定行
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL5IzNzIzNxQTMyIzMwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
改為
将此處的127.0.0.1改為0.0.0.0,意思是任意主機都可以通路sendmail服務
改為
然後儲存退出
三、生成配置檔案
[[email protected] ~]# m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
如果系統無法識别m4指令,則說明沒有安裝sendmail-cf包。m4工具在sendmail-cf包中
四、發送郵件配置
[[email protected] ~]# vim /etc/mail.rc
在末尾添加内容,=号兩邊不能有空格
set from=發送人名稱
set smtp=smtp.163.com
set smtp-auth-user=使用者名
set smtp-auth-password=163郵箱的授權碼
set smtp-auth=login
五、啟動或重新開機sendmail
systemctl restart sendmail #重新開機sendmail服務
systemctl status sendmail #檢視sendmail服務狀态
systemctl enable sendmail #設定endmail服務開機自啟
六、測試
[[email protected] ~]# echo "hello world" | mail -s "test" 郵箱@qq.com
如果郵箱授權碼不符合則出現以下提示
七、編寫檢測腳本
[[email protected] ~]# vim mail.sh
#!/bin/bash
#Network Checking script
iplist="114.114.114.114 10.1.1.1" #需要監控的IP位址池
for ip in $iplist
do
if ping -I ens32 -c 20 $ip >iplog.txt;cat iplog.txt | grep -w '0% packet loss'
#ens32本機網卡
then
rm -f iplog.txt
echo $ip line is ok
elif
cat iplog.txt | grep -w '100% packet loss'
then
rm -f iplog.txt
echo "$ip line is down! The time is `date`" | mail -s "Network Check Warning!" [email protected] #接收人郵箱
fi
done
添加執行權限
[[email protected] ~]# chmod 777 mail.sh
八、添加計劃任務,每隔兩分鐘檢測一次
[[email protected] ~]# pwd
/root
[[email protected] ~]# ll
-rwxrwxrwx. 1 root root 446 Mar 22 04:32 mail.sh
[[email protected] ~]# crontab -e
*/2 * * * * /root/mail.sh
九、驗證結果