Search code examples
linuxshellcronsendmailamazon-linux-2

how to setup bash script to send a mail when new user account is created in Linux


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="[email protected]"

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```

Solution

  • 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="[email protected]"
    
        ( \
            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