How to get email alerts when someone logs in as root via SSH

This is a very useful script that will alert you whenever someone logs into your server via ssh, it you ever get this and it’s not you, then it may be too late but who knows, there may be a way to do something about it before it gets worse.

To setup email notification, login to your server as root.
Edit .bashrc

nano .bashrc

add the following line at the end, changing “ServerName” to the hostname of your server and “[email protected]” to your own email address.

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

Make sure to change ServerName for the real server name and the email address it will be sent to, save and exit.

If you’re on CenOS you can add:

-r “ServerName Root Login Alert <[email protected]>”

right before your email address and it will set a from name and email,

for Debian that would be:

-a “From: ServerName Root Login Alert <[email protected]>”

Next time someone logs on as root, you will get an email about this and this can be done for any user, you only have to make sure that the user can email out from your server.