0

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

Mureinik
  • 113
  • 6
Naveen
  • 1

1 Answers1

1

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?

Mathias Weidner
  • 417
  • 3
  • 10
  • I agree, I think that's most likely the issue here. – Layne Bernardo Sep 15 '20 at 18:17
  • i will check and confirm back – Naveen Sep 16 '20 at 01:11
  • Hi mathias weidner i changed the filename but still the output is same The output below is for: ghdshsdfkerh Today date is: Tue Sep 15 20:36:37 IST 2020 – Naveen Sep 16 '20 at 15:52
  • i have #!/bin/sh inside the script but iam running in cron with /usr/bin/bash,does it make any issue or is it the reaason why script is getting not executed becase iam only getting the output like The output below is for: ghdshsdfkerh Today date is: Tue Sep 15 20:36:37 IST 2020 – Naveen Sep 17 '20 at 04:02