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.com

Make it executable:

chmod +x /usr/local/bin/notify_login.sh

Hook 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.sh

This 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@yourserver

Then check your email inbox for the alert.

Troubleshooting

If you don't get the email:

  • Make sure the mail command works.
  • Install an MTA or a lightweight relay:
  • Debian/Ubuntu: sudo apt install mailutils
  • Red Hat/CentOS: sudo dnf install mailx
  • Or configure msmtp or ssmtp to 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.com

This 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.log

Final 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.