Script executes perfectly in command line but failing in cron
I have created a script to know the successful attempts and failed attempts of users,usually everyday the /var/log/secure file goes to syslog and zipped like "secure-20200910.gz" but without extracting the file i want to read the data, for that i have written below script and this script works fine in terminal but failing in cron
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
output:
The output below is for: ghdshsdfkerh
Today date is: Tue Sep 15 20:36:37 IST 2020
Condition is not getting executed
It looks like you did not provide a full path for $filename
and the script is executed by cron with a different working directory than where you tested it.
Can you reformat the script for better readability?