-1

I need to setup bash script to send a mail when new ssh user account is created in AWS Ec2 Linux.

I have used below script but its not working. Let me know anything wrong in below script or share the scripts if anything related to this task.


#Set the variable which equal to zero
prev_count=0

count=$(grep -i "`date --date='yesterday' '+%b %e'`" /var/log/secure | egrep -wi 'useradd' | wc -l)
if [ "$prev_count" -lt "$count" ] ; then

# Send a mail to given email id when errors found in log
SUBJECT="ATTENTION: New User Account is created on server : `date --date='yesterday' '+%b %e'`"

# This is a temp file, which is created to store the email message.
MESSAGE="/tmp/new-user-logs.txt"
TO="mail-name@example.com"

echo  "Hostname: `hostname`" >> $MESSAGE
echo -e "\n" >> $MESSAGE
echo "The New User Details are below." >> $MESSAGE
echo "+------------------------------+" >> $MESSAGE
grep -i "`date --date='yesterday' '+%b %e'`" /var/log/secure | egrep -wi 'useradd' | grep -v 'failed adding'| awk '{print $4,$8}' | uniq | sed 's/,/ /' >>  $MESSAGE
echo "+------------------------------+" >> $MESSAGE
mail -s "$SUBJECT" "$TO" < $MESSAGE
rm $MESSAGE
fi```
Bala
  • 117
  • 4
  • 13
  • 1
    I’m voting to close this question because ["Can Someone Help Me" is not an actual question](https://meta.stackoverflow.com/a/284237/162698) – Rob Sep 06 '22 at 08:47
  • no its not showing any errors – Bala Sep 08 '22 at 05:03

1 Answers1

1

I implemented a couple of improvements to your script.

  • On most Linux systems /var/log/secure does not exist. Records concerning accounts are usually logged in /var/log/auth.log.
  • Writing to a file is best avoided when possible. In this case I had everything just pipe into mail.

My version of your script:

#!/bin/bash

#Set the variable which equal to zero
prev_count=0

count=$(grep -s -i "`date --date='yesterday' '+%b %e'`" /var/log/auth.log /var/log/secure | egrep -wi 'useradd' | wc -l)

if [ "$prev_count" -lt "$count" ] ; then

    # Send a mail to given email id when errors found in log
    SUBJECT="ATTENTION: New User Account is created on server : `date --date='yesterday' '+%b %e'`"

    TO="mail-name@example.com"

    ( \
        echo  "Hostname: `hostname`"; \
        echo -e "\n"; \
        echo "The New User Details are below."; \
        echo "+------------------------------+"; \
        grep -s -i "`date --date='yesterday' '+%b %e'`" \
            /var/log/auth.log /var/log/secure | \
            egrep -wi 'useradd' | grep -v 'failed adding'| \
            awk '{print $4,$8}' | uniq | sed 's/,/ /'; \
        echo "+------------------------------+"; \
    ) | mail -s "$SUBJECT" "$TO"
fi
James Risner
  • 5,451
  • 11
  • 25
  • 47