Bash script to send a mail when new user account is created in system

There are many open source monitoring tools are currently available in market to monitor Linux systems performance.which will send an email alert when the system reaches the specified threshold limit.

It monitors everything such as CPU utilization, Memory utilization, swap utilization, disk space utilization and much more.

But i don’t think they have an option to monitor  new user creation activity and alert the admins when it happens.

If not, it doesn’t really matter as we can write our own bash script to achieve this.

We had added many useful shell scripts in the past. If you want to check those, navigate to the below link.

What this script actually does? It monitors /var/log/secure file and alert admin when a new account is created in system.

We can’t run this script frequently since user creation is not happening very often. However, I’m planning to run this script once in a day.

So, that we can get a consolidated report about the user creation.

If useradd string was found in “/var/log/secure” file for yesterday’s date, then the script will send an email alert to given email id with new users details.

Note: We have used our email id for demonstrate purpose.

# vi /opt/scripts/


#Set the variable which equal to zero

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

Set an executable permission to file.

$ chmod +x /opt/scripts/

Finally add a cronjob to automate this. It will run everyday at 7’o clock.

# crontab -e

0 7 * * * /bin/bash /opt/scripts/

Note: You will be getting an email alert everyday at 7 o’clock, which is for previous day’s activity.

Output: You will be getting an email alert similar to below.

# cat /tmp/logs.txt


The New User Details are below.
+------------------------------+ name=magesh name=daygeek

About Magesh Maruthamuthu

Love to play with all Linux distribution

View all posts by Magesh Maruthamuthu

Leave a Reply

Your email address will not be published. Required fields are marked *