if [ "$prev_count" -lt "$count" ] ; then # Send a mail to given email id when errors found in log SUBJECT="WARNING: Errors found in log on "`date --date='yesterday''+%b %e'`"" # This is a temp file, which is created to store the email message. MESSAGE="/tmp/logs.txt" TO="2daygeek@gmail.com" echo"ATTENTION: Errors are found in /var/log/messages. Please Check with Linux admin." >> $MESSAGE echo"Hostname: `hostname`" >> $MESSAGE echo -e "\n" >> $MESSAGE echo"+------------------------------------------------------------------------------------+" >> $MESSAGE echo"Error messages in the log file as below" >> $MESSAGE echo"+------------------------------------------------------------------------------------+" >> $MESSAGE grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | awk '{ $3=""; print}' | egrep -wi 'warning|error|critical' >> $MESSAGE mail -s "$SUBJECT""$TO" < $MESSAGE #rm $MESSAGE fi
为 os-log-alert.sh 文件设置可执行权限。
1
$ chmod +x /opt/scripts/os-log-alert.sh
最后添加一个 cron 任务来自动执行此操作。它将每天 7 点钟运行。
1
# crontab -e
1
0 7 * * * /bin/bash /opt/scripts/os-log-alert.sh
注意:你将在每天 7 点收到昨天日志的电子邮件提醒。
输出:你将收到类似下面的电子邮件提醒。
1 2 3 4 5 6 7 8 9 10 11
ATTENTION: Errors are found in /var/log/messages. Please Check with Linux admin.
+-----------------------------------------------------+ Error messages in the log file as below +-----------------------------------------------------+ Jul 3 02:40:11 ns1 kernel: php-fpm[3175]: segfault at 299 ip 000055dfe7cc7e25 sp 00007ffd799d7d38 error 4 in php-fpm[55dfe7a89000+3a7000] Jul 3 02:50:14 ns1 kernel: lmtp[8249]: segfault at 20 ip 00007f9cc05295e4 sp 00007ffc57bca1a0 error 4 in libdovecot-storage.so.0.0.0[7f9cc04df000+148000] Jul 3 15:36:09 ns1 kernel: php-fpm[17846]: segfault at 299 ip 000055dfe7cc7e25 sp 00007ffd799d7d38 error 4 in php-fpm[55dfe7a89000+3a7000] Jul 3 15:45:54 ns1 pure-ftpd: (?@5.188.62.5) [WARNING] Authentication failed for user [daygeek] Jul 3 16:25:36 ns1 pure-ftpd: (?@104.140.148.58) [WARNING] Sorry, cleartext sessions and weak ciphers are not accepted on this server.#012Please reconnect using TLS security mechanisms. Jul 3 16:44:20 ns1 kernel: php-fpm[8979]: segfault at 299 ip 000055dfe7cc7e25 sp 00007ffd799d7d38 error 4 in php-fpm[55dfe7a89000+3a7000]