In this tutorial, we are going to learn how to configure an email sending during a SSH access to a Linux server.


This simple and quick solution will allow you to know if someone is connecting to your server in near-real time (mail sending wait).
This method can apply to all users connections in SSH.
The most interesting to configure is the user root because it allows the supervision of SSH connections for root, and also to detect abnormal connections.

The file .bashrc

Each user own a file .bashrc in his folder home that can contain, among others, executed commands during his shell initialization.
This file is used to configure alias as well.
It is from this file that we are going to send the email while putting in the adequate commands as long as your server is able to send it.

Particular user

We intend that, for each SSH connection for user root, an email is sent in order to point out this connection via the following commands :

echo 'Access SSH FROM '`id | cut -d "(" -f2 | cut -d ")" -f1`' ON :  '`hostname`' THE '`date` SINCE `who`

mail -s "NOTIFICATION - Connection in "`id | cut -d '(' -f2 | cut -d ')' -f1`" via SSH since: `who | cut -d"(" -f2 | cut -d")" -f1`"<>

So, we edit the file .bashrc from the user root to include our commands :

echo 'Access SSH FROM '` id | cut -d "(" -f2 | cut -d ")" -f1`' ON :  '`hostname`' THE '`date`  via SSH since: `who` | mail -s "NOTIFICATION - Access SSH "`id | cut -d '(' -f2 | cut -d ')' -f1`"SINCE `who | cut -d"(" -f2 | cut -d")" -f1`"<> > /home/root/.bashrc

Make sure that quotes and apostrophes are well maintained in order to isolate the command and the text.

Command to get the user’s information back (UID, GID and name) with “id” then cut the output chain in order to only retrieve the user’s name and display it in the email with cut.

Command to retrieve information on on-going sessions with who used earlier as well, and then cut the output to only retrieve the IP source connection with cut.

Command for date display and hourly connection.

Command including hostname.

Command for mail sending

writing on the file /home/root/.bashrc

The email received on the provided address gets the following form :

Object: NOTIFICATION - Connection in ROOT via SSH since:
Access SSH FROM root SUR jn-community IN 2017, on June 27th Tuesday, 13:01:23 (UTC+0200) SINCE root pts/0 2017-06-27 13:01 (

All users

The file /etc/bash/.bashrc allows to make only one modification that’ll be taken into account by all files .bashrc of the users.
The notifications will be sent by all the users’ SSH connections.
So, we will use the same command as previously towards a different file :

echo 'Access SSH FROM '` id | cut -d "(" -f2 | cut -d ")" -f1`' ON :  '`hostname`' THE '`date`  via SSH since: `who` | mail -s "NOTIFICATION - Access SSH "`id | cut -d '(' -f2 | cut -d ')' -f1`"SINCE `who | cut -d"(" -f2 | cut -d")" -f1`"<> > /etc/bash/.bashrc