我有一个每 10 分钟执行一次 bash 文件的 cronjob。bash 文件包含一个 Curl 命令,如果 var/log/auth.log 文件包含任何带有"接受密码"的行,则向我发送短信。(显然,如果条件每次都为真(.
现在我想添加另一个 if 条件,该条件仅在最后 10 分钟内检查字符串"接受的密码"。
我的问题是,日志文件包含这样的时间信息:
Sep 5 13:49:07 localhost sshd[565]: Server listening on 0.0.0.0 port 22.
Nov 28 21:39:25 soft-server sshd[11946]: Accepted password for myusername from 10.0.2.2 port 13494 ssh2
如何将当前时间与上述格式进行比较并编写 IF 语句?目前我正在这样做:
if [ grep -q "Accepted password for" var/log/auth.log] && (check timing for last 10 min)
then
curl 'www.example.com/send-a-text'
fi
提前谢谢你。
比较时间的最佳方法是将它们转换为纪元中的秒,这样您就可以将它们视为整数。下面是一个示例:
#! /bin/bash
# time in seconds from epoch 10 minutes ago is the limit
limit="$(date -d '10 minutes ago' +%s)"
# read matches from the file starting from the end up to the limit
while read -r logrow; do
# cut out the timestamp from the logrow
timestamp="$(cut -d ' ' -f 1,2,3 <<<"$logrow")"
# convert timestamp to seconds from epoch
from_epoch="$(date -d "$timestamp" +%s)"
# if the line was newer than 10 minutes ago, send a message
if (( from_epoch > limit )); then
# send the logrow
curl "www.example.com/send-a-text?logrow=${logrow}"
else
# after reaching the limit, stop the loop
break
fi
done < <(tac /var/log/auth.log | grep "Accepted")