Ever wondered who's logging into your Linux box? Whether it's a critical production server or a personal VPS, it's smart to get notified the moment someone connects over SSH. Here's how to make your system send you an automatic email alert whenever a login occurs — no heavy monitoring tools needed.
Create the Notification Script
We'll use a short Bash script that gathers the username, IP, hostname, and login time, then sends it via email.
#!/bin/bash
# /usr/local/bin/notify_login.sh
user="$PAM_USER"
host="$(hostname)"
ip="$PAM_RHOST"
time="$(date '+%Y-%m-%d %H:%M:%S')"
echo "SSH login on $host by $user from $ip at $time" | \
mail -s "SSH login alert: $user@$host" admin@example.comMake it executable:
chmod +x /usr/local/bin/notify_login.shHook It Into SSH
Add a PAM execution rule so the script runs automatically when a user logs in. Edit /etc/pam.d/sshd and add this at the end
session optional pam_exec.so /usr/local/bin/notify_login.shThis tells PAM (Pluggable Authentication Module) to execute your script on every SSH session start.
Test It
Log in to your machine via SSH
ssh user@yourserverThen check your email inbox for the alert.
Troubleshooting
If you don't get the email:
- Make sure the
mailcommand works. - Install an MTA or a lightweight relay:
- Debian/Ubuntu:
sudo apt install mailutils - Red Hat/CentOS:
sudo dnf install mailx - Or configure
msmtporssmtpto send via your email provider's SMTP.
Alternative (Simpler, Less Secure)
Instead of PAM, you can append this to /etc/ssh/sshrc:
(echo "SSH login: $(whoami) from $(echo $SSH_CONNECTION | awk '{print $1}') on $(hostname) at $(date)") \
| mail -s "SSH login alert" admin@example.comThis works too, but PAM is cleaner and triggers for all SSH logins — even automated ones.
Bonus Tip: Log to a File Too
To maintain a local audit trail, modify the script to also write to /var/log/ssh_login_alerts.log:
echo "$time | user=$user | ip=$ip | host=$host" >> /var/log/ssh_login_alerts.logFinal Thoughts
This simple setup provides instant awareness of who's logging into your servers. It's light, fast, and can save you from a nasty surprise.