【问题标题】:Tail a log file on linux and trigger a script if words are matched在 linux 上跟踪日志文件并在匹配单词时触发脚本
【发布时间】:2016-02-08 09:04:25
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

  • stackoverflow.com/questions/4331309/… 但不要尝试使用 'f' 来处理日志轮换
  • 我正在寻找可以连续运行并且可以随服务器自动启动的东西(基于 cron 或基于 init.d)

标签: linux logging monitor logfiles


【解决方案1】:

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

例子:

使用 $( 任何命令 ) 将命令输出转换为字符串
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 随便一个字 /dev/null

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

"kill 会杀死剩余的tail -f 进程,并且我们隐藏错误,因为 到 kill 时尾巴可能会消失 调用。”

【讨论】:

  • 感谢您的建议,我已将其添加到我的代码库中,但与此同时,我想让大家知道我找到了完全符合我需要的东西。它叫做 SEC(在 CentOS 上你可以运行 yum install sec)。
  • 这里还有一些讨论:superuser.com/questions/270529/…
  • 太好了,我会试试 SEC。我的回答在您不能或不允许安装任何东西的环境中非常有效。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多