This article explains how to set SSH login email alerts on a Linux server. Receiving email alerts for SSH logins is a simple and effective way to monitor unauthorised or suspicious access on your Linux server.
This guide shows you how to configure SSH login alerts for root and regular users using the .bashrc file and the mailx command-line email client.
Requirements:
- Root access to the server.
- Basic knowledge of vi or nano text editors.
- mailx (or equivalent) mail client installed on your server.
Install mailx Based on Your Linux Distribution:
- Debian/Ubuntu/Mint
sudo apt install mailutils
- RHEL/CentOS/Fedora/Rocky/AlmaLinux
sudo yum install mailx
- Gentoo
sudo emerge -a sys-apps/mailx
- Alpine
sudo apk add mailx
- Arch
sudo pacman -S mailx
- openSUSE
sudo zypper install mailx
- FreeBSD
sudo pkg install mailx
Set Email Alerts for Root SSH Logins:
- Log in as root and navigate to the home directory:
cd /root
- Open the hidden .bashrc file:
nano .bashrc # or vi .bashrc
- Add the following line at the bottom of the file. Replace ServerName with your actual server hostname and [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]
- Save and close the file. Then, log out and log back in via SSH to test it.
Sample Email Alert
ALERT - Root Shell Access (WebServer1) on: Mon Jun 30 17:43:11 IST 2025 root pts/0 2025-06-30 17:43 (192.168.1.100)
Set Email Alerts for Normal User SSH Logins:
- Log in as the desired user and go to the home directory:
cd ~
- Open the .bashrc file:
nano .bashrc # or vi .bashrc
- Add the same email alert line from the root section, adjusting the server name and email as needed.
- Save the file, then log out and log back in. An alert email will be sent upon each SSH login.
Tip:
You can configure email login alerts for any user by editing the “.bashrc” file in their home directory:
/home/username/.bashrc
By following this guide, you can set up SSH login email alerts for root and other users, improving your server’s security and awareness. These alerts can help detect unauthorised access attempts or simply keep track of login activity in real time.
Enhancing server security? Learn How to change the root user password via WHM