How To Get Email Alerts for SSH Login on Linux Server
Introduce
Enabling an SSH server on a virtual private server (VPS) will expose the server to the Internet and provide opportunities for hacking activities, especially when VPS still using root as primary access.
VPS should be configured with an email alert automatically to each successful login attempt via the SSH server. VPS server owner shall be notified of any SSH server access log, such as who, when, and which source IP address. This is an important security concern for server owners to protect the server from unknown login attempts. This is because if hackers use brute force to log into your VPS via ssh then it can be very dangerous. In this article, I will explain how to set up an email alert to all SSH login users on Linux
Set SSH Root Login Email Alerts
1. Login to your server as the root user:
Before you can use mailx to send emails, You need to install Postfix is the default Mail Transfer Agent (MTA) and configured on your system. The MTA is responsible for sending and receiving emails over the network.
On Debian/Ubuntu/Linux Mint run the command below:
apt install postfix
apt-get install mailx
On RHEL/CentOS/Fedora run the command below:
yum install -y postfix
yum install mailx
2. Configure at alert from source global definitions (/etc/bashrc). This will enabled for root and normal users :
vi /etc/bashrc
Add the following at the bottom of the files. Make sure to replace “ServerName” with a hostname of your server and change “[email protected]” with 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]
3. Optionally you can enable alert for root only:
vi .bashrc
Add the following at the bottom of /root/.bashrc:
echo 'ALERT - Root Shell Access (ServerName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" [email protected]
Full Configuration file example:
4. Optionally you can enable alert for specifying normal users (e.g green ):
vi /home/green/.bashrc
Add the following at the bottom of /home/green/.bashrc :
echo 'ALERT - Root Shell Access (ServerName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" [email protected]
Check email alerts
You can access your email and check the warning information displayed as follows: