How to Set Up Email Alerts for SSH Logins on Linux
This guide shows how to configure Linux systems to send email notifications whenever an SSH login occurs, covering root, specific users, and all users by adding appropriate scripts to .bashrc or /etc/bashrc and using the mail command.
The .bashrc file is a script executed each time an interactive terminal session starts, making it a convenient place to add custom commands.
1) Enable email alerts for the root user
Log in as root and append the following line to /root/.bashrc (replace the placeholder email address with your own):
echo 'ALERT - SSH root shell access found on ' $HOSTNAME ' on:' `date` `who` | mail -s "Alert: SSH root shell access" [email protected]After saving, apply the changes with: source .bashrc Now, when you log in as root via SSH, an email similar to the screenshot will be sent.
2) Enable email alerts for a specific user
Edit the target user's .bashrc (e.g., /home/bob/.bashrc) and add:
echo 'ALERT - ' $USER ' shell access found on ' $HOSTNAME ' on:' `date` `who` | mail -s "Alert: User shell access" [email protected]Replace [email protected] with the address that should receive the alerts, then source the file or log in again to test.
3) Enable email alerts for all users
To apply the alert globally, edit /etc/bashrc and append a similar script at the end of the file:
echo 'ALERT - ' $USER ' shell access found on ' $HOSTNAME ' on:' `date` `who` | mail -s "Alert: User shell access" [email protected]After saving, any SSH login by any user will trigger an email notification.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
