Member-only story
Stop Intruders in Their Tracks: Get an Email Every Time Someone Logs In via SSH
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.