本文介绍了如果自上次警报以来发生,则仅 bash 发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在监视特定单词的日志文件并使用 tac 输出它前后的 5 行

I'm monitoring a log file for a specific word and using tac to output the 5 lines before and after it

#!/bin/bash
tac /var/log/syslog |grep -m1 -A5 -B5 'WORD' | tac >> /tmp/systemp
mailx email commands
rm /tmp/systemp

我已经设置了一个 cron 每 5 分钟运行一次,但是正如预期的那样,我收到了重复的警报电子邮件,我该如何让它在最后一次发生时发送一封电子邮件,而不是在下一次之前再次发送?

and I've setup a cron to run every 5 minutes however as expected I receive duplicate alert emails, how do I make it send an email for the last occurrence and not again until the next one?

Feb 27 15:05:39 WORD (email)
Cron runs again after 5 minutes
Feb 27 15:05:39 WORD (don't email)
Cron runs again after 5 minutes
Feb 27 15:35:39 WORD (email)

推荐答案

你应该只搜索最后 5 分钟的数据:

You should only search trough last 5 min of data:

data5m=$(awk '$0>=from' from="$(date +"%b %e %H:%M:%S" -d -5min)" /var/log/syslog)

然后你可以从这个数据中grep:

Then you can grep from this data:

grep -m1 -C5 'WORD' <<< "$data5m"

更新:

awk '$0>=from' from="$(date +"%b %e %H:%M:%S" -d -5min)" /var/log/syslog | grep -m1 -C5 'WORD'

或多合一awk

awk '{a[NR]=$0} /pattern/ && $0>=from {f=NR} END {for (i=f-5;i<=f+5;i++) print a[i]}' from="$(date +"%b %e %H:%M:%S" -d -5min)" /var/log/syslog

这篇关于如果自上次警报以来发生,则仅 bash 发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:08