在 linux 上跟踪日志文件并在单词匹配时触发脚本

Tail a log file on linux and trigger a script if words are matched

我正在寻找一种方法来查看 linux 上的多个日志文件并在其中查找单词或短语,如果找到,则触发脚本或操作,这需要保持不变。

我知道这可以通过一些 grep、tail hack 来完成,但我想知道是否有一些预制的配置选项,例如,我认为 logtail 可以监视文件但不能触发操作。

有什么想法吗?

您可以将 grep 的输出设置为一个变量,然后评估它是否为空 运行 您的 script/actions。

示例:

使用 $( whatever command ) 将命令输出转换为字符串
line=$(  grep -m 1 YourKeyWord <( exec tail -f /directory/of/log.out ); kill $! 2> /dev/null)
然后您可以开始评估每个日志,并确定以下操作。
if [ "$line"!="" ]
then
echo "Found $line"
service something start
line=""
echo "Now we can look for ABC"
fi

line=$(  grep -m 1 ABC <( exec tail -f /your/otherdir/of/log.out ); kill $! 2> /dev/null)
if [ "$linea!="" ]
then
echo "Found the other $linea"
ntpstat (or whatever command you need)
line=""
echo "And we can keep doing this"
fi

您可以使用两个函数来完成此操作(一个用于重置 $line,另一个用于执行 grep,使用 $Dir var)但是为了详细的答案,让我们这样吧。

行,

grep -m 1 WhateverWord <( exec tail -f /your/otherdir/of/log.out ); kill $! 2> /dev/null

摘自答案 https://superuser.com/questions/275827/how-to-read-one-line-from-tail-f-through-a-pipeline-and-then-terminate 并附有以下解释,它确实避免了服务器中的逻辑问题。

"kill will kill leftover tail -f process, and we hide errors, because it's possible that the tail will be gone by the time kill will be invoked."

答案是 SEC (yum install sec)。它的作用是监视任何日志文件并使用规则使用正则表达式扫描文件,然后您可以 运行 shell 脚本、插入日志和其他一些东西。

它 运行 作为一项服务,因此机器重启、cron 等都没有问题。

希望这可以帮助任何人尝试做我想做的事。