【问题标题】:How to find a grep-ed value in log files in a directory every 60 minutes in shell script?如何在 shell 脚本中每 60 分钟在目录中的日志文件中查找 grep 值?
【发布时间】:2020-02-13 17:20:24
【问题描述】:

我有一个名为 /qfs/input/ad_logs 的目录。每隔 15 分钟左右,就会将一个新文件转储到此目录中。我需要每小时检查一次这个目录,看看日志的第 10 个字段中是否有某个值。一直在使用命令lzop -cd file_name_20200209.lzo | cut -f10 -d, | grep mcid=在日志中查找值。

我如何执行这个 shell 脚本来自动化该过程并提醒我在日志中找到的值?

【问题讨论】:

  • 我建议不要检查计时器,而是使用像incron 这样的工具,它可以在任何新文件在写入后关闭时触发您的代码。

标签: linux bash shell scripting bin


【解决方案1】:

创建一个脚本:

#!/bin/sh
if lzop -cd file_name_20200209.lzo | cut -f10 -d, | grep -q mcid=; then
      # alert me of the found value in the logs?
      logger -p local3.info -t "VERY_IMPORTANT_SCRIPT" "alert! The value was found in the logs"
fi

然后将此脚本添加到cron(如果您有),或者创建一个system timer service(如果您的系统使用 systemd),它将每隔一小时运行一次您的脚本。例如创建两个文件:

# /etc/systemd/service/very_important_script.timer
[Unit]
Description=Run very_important_script hourly

[Timer]
OnCalendar=hourly
Persistent=true

[Install]
WantedBy=timers.target

和

# /etc/systemd/service/very_important_script.service
[Unit]
Description=very_important_script 

[Service]
ExecStart=/path/to/the/very_important_script

[Install]
WantedBy=multi-user.target

并执行systemctl deamon-refresh ; systemctl enable very_important_script.timer ; systemctl start very_important_script.timer 启动计时器。

例如,您可以仅考虑过去一小时内更改的文件:

#!/bin/sh
if 
      find . -maxdepth 1 -type f -name 'file_name_*.lzo' -mmin -60 |
      xargs lzip -cd | 
      cut -f10 -d, | grep -q mcid=  
      # maybe add -m1 to grep?
then
      # alert me of the found value in the logs?
      logger -p local3.info -t "VERY_IMPORTANT_SCRIPT" "alert! The value was found in the logs"
fi

【讨论】:

  • 谢谢你。我对脚本如何解释目录中的所有文件感到困惑。正如我提到的,文件每 15 分钟左右通过一次,但我只关心每小时检查一次在 cron 作业中设置的日志。我一直在使用带有 * 的 lzop -cd file_name_202002*.lzo | cut -f10 -d, | grep -q mcid= 来浏览所有不同的日志文件。我可以在这个脚本中执行此操作还是需要创建一个循环函数?对 bash/linux 非常陌生
  • 哦,不会的,我认为文件名将保持不变。当然,只需使用file_name_202002*.lzo。您也可以使用 find . -maxdepth 1 -type f -name 'file_name_*.lzo' -mmin -60 | xargs lzip -cd 之类的方法,例如仅解压缩不到一小时前更改的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多