Published March 26, 2018 by

Set up an Email Alert when a User login in Linux System

This tutorial shows a simple way to know when someone logged in as root or normal user it should send an email alert notification to the specified email address along with the IP address of the last login. So, once you know the IP address of the last login made by an unknown user you can block SSH login of particular IP address on iptables Firewall.

Set up an email alert when a User login in Linux system

First, we need to email utility installed on our server for sending mail, So install email utility using this tutorial.


Set Root Login Email Alerts

Now log in as root user and go to root’s home directory by typing cd /root command.
 # cd /root  
Open .bashrc file. Please remember .bashrc is a hidden file.
 # vim .bashrc  
Add the following line at the bottom of the file. Make sure to replace "ServerKaka" with a hostname of your Server and change "it.subhashpatel@gmail.com" with your email address.
 echo 'ALERT - Root Shell Access (ServerKaKa) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" it.subhashpatel@gmail.com  

Save and close the file and log out and log back in. Once you log in via SSH, a .bashrc file by default executed and sends you an email address of the root login alert.


Set Normal User Login Email Alerts

Now log in as serverkaka (normal User) user and go to serverkaka’s home directory by typing cd /home/serverkaka command.
 # cd /home/serverkaka  
Open .bashrc file. Please remember .bashrc is a hidden file.
 # vim .bashrc  

Add the following line at the bottom of the file. Make sure to replace "ServerKaka" with a hostname of your Server and change "it.subhashpatel@gmail.com" with your email address.
 echo 'ALERT - Root Shell Access (ServerKaKa) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" it.subhashpatel@gmail.com  
Save and close the file and log out and log back in. Once you log in via SSH, a .bashrc file by default executed and sends you an email address of the root login alert.