A cuban around the globe

Receiving email alerts when an SSH login is detected


For some time I was wondering how to know if someone else was accessing to my servers remotely and if this happened, I also knew when it happened. I know there are several tools for intrusion detection and monitoring, but I always thought it was too much work for a simple task. Also those who accessed to my servers were usually work colleagues and I just wanted to keep a simple record of it without having to filter logs, just by looking at my email.

This task was relatively easy for me combining some system features. This solution allows to notify every time an ssh authentication occurs in a server using a specific user, in my case root (yes! I know it is not recommended but that was the access policy).

We will explain how to implement this solution for Debian however it can be used in other GNU/Linux distros.

Very important to have the sending of email from the server enabled, otherwise notifications will not arrive.

With our preferred text editor

$ vim ~/.bashrc

At the end of the file we add the following line

echo 'ALERT: User [user] login to [server] on:' `date` `who` | mail -s "Alert: User login from `who | cut -d'(' -f2 | cut -d')' -f1`"

Important: All in one line

  • We must replace
    • [user] -> By the user we want to monitor (in my case root)
    • [server] -> By the IP address or hostname of the server we want to monitor
    • -> Destination email where notifications will arrive

Save and close the file.

What is happening?:

When a user accesses our server using ssh, the system will read the file .bashrc, this action will execute the line we have added, and will send the notification.


We are free to customized the line we add.

In case you don’t know how to configure a local mail server, I recommend using msmtp who I will be talking about in a next post.

Another more elaborate and flexible solution, but just as simple would be use Sagan.

All for today…

Leave a Reply

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

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>