在本文中,我们添加了一个shell脚本来监视Linux系统上的Messages Log(消息日志),此脚本将检查/var/log/messages文件中的“警告、错误和严重”,并触发给定电子邮件ID。
脚本 注意:如果服务器有许多匹配的字符串,我们就不能经常运行这个可能填满收件箱的脚本,而是我们可以在一天内运行一次。 为了解决这个问题,我让脚本以不同的方式触发电子邮件。 如果在昨天的日期“/var/log/messages”文件中找到任何给定的字符串,则脚本将向给定的电子邮件ID发送电子邮件警报。 #---------------脚本开始---------------# # vi /opt/scripts/os-log-alert.sh #!/bin/bash #Set the variable which equal to zero prev_count=0 count=$(grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | egrep -wi 'warning|error|critical' | wc -l) 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="ywnz@163.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 #---------------脚本结束---------------# 注意:你需要更改电子邮件ID,而不是我们的电子邮件ID,此外,你可以根据你的要求更改内存利用率阈值。 为os-log-alert.sh文件设置可执行权限: $ chmod + x /opt/scripts/os-log-alert.sh 最后添加一个cronjob来自动执行此操作,它将每天7点钟运行: $ chmod +x /opt/scripts/os-log-alert.sh 注意:你将在每天7点收到一封电子邮件提醒,这是昨天的日志。 输出:你将收到类似下面的电子邮件提醒: 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]
相关主题 |