Automatic email sending during a SSH access

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 :

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

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 :

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 :