我创建了一个脚本来了解用户的成功尝试和失败尝试,通常每天 /var/log/secure 文件都会进入 syslog 并压缩为“secure-20200910.gz”,但如果不提取文件,我想读取数据,为此我编写了以下脚本,该脚本在终端上运行良好,但在 cron 中失败
计划任务:
20 11 * * * /usr/bin/bash /root/audit.sh >> /root/output.txt
#!/bin/sh
echo "The output below is for: $(hostname -f)"
echo "Today date is: $(/usr/bin/date)"
filename="secure-$(/usr/bin/date +%Y%m%d).gz"
month=$(/usr/bin/date | awk '{print $2}')
while read username
do
for serial in {1..31}
do
successful_attempt=$(/usr/bin/gzip -cd ${filename} | grep -a -i "${month} ${serial}" | grep ${username} | /usr/bin/awk '/sshd.*session opened/ {print $11}' | /usr/bin/wc -l)
successful_result=${successful_attempt}
if [[ ${successful_result} -gt 0 ]]
then
echo "The successful attempts for ${username} on ${month}-${serial} is: ${successful_result}"
fi
failed_attempt=$(/usr/bin/gzip -cd ${filename} | grep -a -i "${month} ${serial}" | grep ${username} | /usr/bin/awk '/sshd.*Failed password/ {print $9}' | /usr/bin/wc -l)
failed_result=${failed_attempt}
if [[ ${failed_result} -gt 0 ]]
then
echo "The Failed attempts for ${username} on ${month}-${serial} is: ${failed_result}"
fi
done
done < /root/user.txt
输出:
The output below is for: ghdshsdfkerh
Today date is: Tue Sep 15 20:36:37 IST 2020
条件未得到执行
答案1
看起来您没有提供完整路径,$filename
并且该脚本由 cron 执行,其工作目录与您测试它的位置不同。
您可以重新格式化脚本以提高可读性吗?