How to Get Root and User SSH Login Email Alerts

Whenever we install, configure, and secure Linux servers in a production environment, it’s crucial to keep track of what is happening on the servers and who logs into them, especially concerning server security.

Why? Because if someone logs into the server as the root user using brute force tactics over SSH, then think about how they will destroy your server.

Any user who gains root access can do whatever they want. To block such SSH attacks, read our following articles that describe how to protect servers from such attacks.

So, it’s not a good practice to allow direct root login via SSH session, and recommend creating non-root accounts with sudo access. Whenever root access is needed, first log in as a normal user and then use ‘su‘ to switch over to the root user.

To disable direct SSH root logins, follow this article, which shows how to disable and limit root logins in SSH.

However, this guide demonstrates a simple method to receive email alert notifications when someone logs in as root or a normal user. It should send an email alert notification to the specified email address, along with the IP address of the last login.

Therefore, once you identify the IP address of the last login made by an unknown user, you can block SSH login from that particular IP address using the Firewall rule as shown.

Using iptables:

sudo iptables -A INPUT -s <IP_Address> -p tcp --dport ssh -j DROP

Using firewalld:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="<IP_Address>" port protocol="tcp" port="22" reject'
sudo firewall-cmd --reload

Using UFW (Uncomplicated Firewall):

sudo ufw deny from <IP_Address> to any port 22
sudo ufw reload

How to Set SSH Login Email Alerts in Linux Server

To carry out this tutorial, you must have root level access on the server and a little knowledge of nano or vi text editor and also mailx (mail client) installed on the server to send the emails.

Depending upon your Linux distribution you can install mailx client using one of the following commands.

sudo apt install mailutils     [On Debian, Ubuntu and Mint]
sudo yum install mailx         [On RHEL/CentOS/Fedora and Rocky/AlmaLinux]
sudo emerge -a sys-apps/mailx  [On Gentoo Linux]
sudo apk add mailx             [On Alpine Linux]
sudo pacman -S mailx           [On Arch Linux]
sudo zypper install mailx      [On OpenSUSE]    
sudo pkg install mailx         [On FreeBSD]

Set SSH Root Login Email Alerts

Now login as the root user and go to the root’s home directory by typing the cd /root command.

cd /root

Next, add an entry to the .bashrc file, this sets local environment variables for the users and does some login tasks. For example, here we setting an email login alert.

Open the .bashrc file with either the vi or nano editor. Please remember that .bashrc is a hidden file; you won’t see it by using the ls -l command. You have to use the -a flag to see hidden files in Linux.

vi .bashrc
or
nano .bashrc

Add the following line at the bottom of the file. Make sure to replace ‘ServerName‘ with the hostname of your server and change ‘[email protected]‘ to your email address.

echo 'ALERT - Root Shell Access (ServerName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" [email protected]

Save and close the file, logout, and log back in.

Once you log in via SSH, a .bashrc file is executed by default and sends you an email alert for root login as shown.

Sample Email Alert:

ALERT - Root Shell Access (Database Replica) on: Thu Nov 28 16:59:40 IST 2023 tecmint pts/0 2023-11-28 16:59 (172.16.25.125)

Set SSH Normal User Login Email Alerts

Log in as a normal user (tecmint) and go to the user’s home directory by typing the cd /home/tecmint/ command.

cd /home/tecmint

Next, open .bashrc file and add the following line at the end of the file. Make sure to replace values as shown above.

echo 'ALERT - Root Shell Access (ServerName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" [email protected]

Save and close the file, log out, and log in again. Once you login back again, a .bashrc file is executed and sends you an email address of the user login alert.

This way you can set an email alert for any user to receive login alerts. Just open the user’s .bashrc file which should located under the user’s home directory (i.e. /home/username/.bashrc) and set the login alerts as described above.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

36 Comments

Leave a Reply
  1. It would be better to put this line in the .profile or .bash_login files since they are only executed at login (i.e., only one time), while .bashrc is executed every time a subshell is launched (likely, many times).

    Reply
  2. Create a alert on my server such that if anyone other than my and my manager IP’s login to the server we should get an mail based alert with the user ID & ip address.

    Please help.

    Reply
  3. Hi, I just tested this on my Linux box and it works well. However, if i need to reverse the script, how do i achieve that?

    echo ‘ALERT – Root Shell Access (ServerName) on:’ `date` `who` | mail -s “Alert: Root Access from `who | cut -d'(‘ -f2 | cut -d’)’ -f1`” [email protected]

    Reply
  4. Hello!

    I get this when attempting to install mailx the above command.

    Reading package lists ... Done
    Building the dependency tree
    Reading status information ... Done
    The mailx package is a virtual package provided by:
      mailutils 1: 3.1.1-1
      bsd-mailx 8.1.2-0.20160123cvs-4
    You must explicitly select a package to install.
    
    E: The "mailx" package does not have a version that can be installed
    

    As the message says, apt-get install mailutils works.

    Thank you for sharing your knowledge.

    Reply
  5. When i am trying the command i am getting.

    line 13: unexpected EOF while looking for matching `''
    line 14: syntax error: unexpected end of file
    

    i didn’t find any solutions

    Reply
  6. After I originally left a comment I seem to have clicked on the Notify me when new comments are added- checkbox and now each time a comment is added I receive four emails with the exact same comment. There has to be a way you are able to remove me from that service? Thanks a lot!

    Reply
  7. When I tried logging in as root, I get this error message. what does this mean?

    mail: option requires an argument -- 's'
    Try 'mail --help' or 'mail --usage' for more information.
    bash: $'Alert: Root Access from ip-address\nip-address': command not found
    
    Reply
  8. Sir, I need one help from you.

    can’t I get any user login email alert through the mail? I have tried but mail.err and mail log gives me an error. below is the code (changed hostname, email)

    echo 'ALERT - Root Shell Access (ServerName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" [email protected]

    I have written a script for capturing an image and email later notification

    Reply
      • Ravi – do you know why I would see :0 instead of an IP Address? Please let me know.

        ALERT – Root Shell Access (server-here) on: Mon May 1 11:52:31 EDT 2017 username-here tty7 2017-05-01 11:48 (:0)

        Reply
        • @Mike,

          Have you added following code correctly to your .bashrc file?

          echo 'ALERT - Root Shell Access (ServerName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" [email protected]

          Reply
          • Yes – and it works great every time I log in! But I had one time where I did not log into the system but got an email and it was from “:0” so I was wondering if that may have been the system or something else?

          • @Ravi,any word on the “:0”? It works great when I log in but one time when no one logged in I got an email with “:0” as the login … I thought it was odd…

  9. @Ravi Saive – what does it mean when I see :0 instead of an IP Address? See below:

    ALERT – Root Shell Access (server-here) on: Mon May 1 11:52:31 EDT 2017 username-here tty7 2017-05-01 11:48 (:0)

    Reply
  10. Hi, I think your site might be having browser compatibility issues. When I look at your blog in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, very good blog!

    Reply
  11. Hi,
    I always get the message (mail.log) “no recepient address found in message header”
    Where is this recepient address specified?

    Thanks for yr help im desperate..

    With kind regards,

    Edwin

    Reply
  12. Hi how can we set ssh mail alert othere then one specific ip.

    I want to set ssh login root mail alert same working as well now my requirment is i want to get ssh root alert mail if other then one specific ip are
    login.

    Thanks & regdras
    Randhr

    Reply
  13. Hi there,

    It’s possible to configure this alert only in some specific time of the day ?

    Like when i’m out of the company ?

    Thank you.

    Reply
  14. Dear Ravi Saive,

    I want to thank you, I learned a lot from your posts. This post works great. After I put these codes in the bashrc file, I receive email notification immediately when I login SSH.

    The smtp port 25 should be open and we should make sendmail or postfix working. Otherwise no emails go out.

    And if the email account has message arrival notification function to mobile phone, we receive sms messages when users login with SSH.

    Thank you very much.

    Lampk

    Reply
  15. Gr8 document. is it possible get system or root access alert on android mobile phone ? i checked with gnokii but for that we need nokia phone but i want to configure it on android phone.

    Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.