/var/log/message 的警报脚本

问题描述 投票:0回答:2

`

#!/bin/bash

msg=$(find /home/testaccount/test.log -mmin -30 -exec grep test.service {} \; | tail -1)
test -n "$msg" &&
    echo "$msg" |
    mail -r '[email protected]' -s 'Database Aler' [email protected]

我上面有一个脚本,当有一个带有 test.service 的日志时,它会通过电子邮件发送给我,我已将其放入 cron 中,它将每 30 分钟运行一次,但我现在的问题是它总是每 30 分钟通过电子邮件发送相同的日志。

有没有办法给我发一次电子邮件,然后如果再次读取相同的日志,它就会停止向我发送电子邮件?

我需要阻止它每 30 分钟发送相同的日志,如果有带有 test.service 的新警报,它只会向我发送电子邮件。

linux bash shell unix alert
2个回答
0
投票

要实现仅在有带有

test.service
的新日志条目时发送电子邮件的功能,您可以在单独的文件中跟踪上次处理的日志条目。这是执行此操作的脚本的更新版本:

#!/bin/bash

log_file="/home/testaccount/test.log"
last_handled_file="/path/to/last_handled.log"

# Read the last handled log entry timestamp from the file
if [ -f "$last_handled_file" ]; then
    last_handled=$(cat "$last_handled_file")
else
    last_handled=""
fi

# Get the most recent log entry with test.service within the last 30 minutes
msg=$(find "$log_file" -mmin -30 -exec grep test.service {} \; | tail -1)

# Check if there's a new log entry and it differs from the last handled one
if [ -n "$msg" ] && [ "$msg" != "$last_handled" ]; then
    echo "$msg" |
    mail -r '[email protected]' -s 'Database Alert' [email protected]

    # Update the last handled log entry timestamp in the file
    echo "$msg" > "$last_handled_file"
fi

在此版本中,我们引入了一个

last_handled_file
变量,它指向存储最后处理的日志条目的文件的路径。当脚本运行时,它会从此文件中读取最后处理的条目(如果存在)。处理新的日志条目后,它将与上次处理的条目进行比较,如果不同,则会发送一封电子邮件并使用新的日志条目更新
last_handled_file

确保将

/path/to/last_handled.log
替换为您要存储最后处理的日志条目的实际路径。

通过使用此方法,仅当有带有

test.service
的新日志条目时,脚本才会发送电子邮件,并且不会每 30 分钟通过电子邮件重复发送相同的日志条目。


0
投票

您需要某种方法来记住您已经看到的内容。您可以尝试的最简单的方法是将您的 msg 存储在某个文件中,下次收到消息时,您将

diff
与您的“状态”文件相对应,并且仅在有新内容时才发送邮件。

作为更高级的方法,您可以围绕 logtail 构建脚本。它只能为您提供自上次调用以来日志文件的新行。 (在 Debian 上它是它自己的包

logtail

或者您可以使用现有项目,例如 logcheck,而不是编写自己的日志观察程序脚本。

© www.soinside.com 2019 - 2024. All rights reserved.