SSH Login Notifications by Email on Ubuntu 26.04, Debian 13 and AlmaLinux 9
Get an email whenever someone logs in over SSH, using pam_exec or a profile script, with the limits of each method spelled out.
This guide sets up an email that is sent every time someone logs in to your server over SSH. It covers two methods: a PAM hook using pam_exec, which applies to every user and every kind of SSH session, and a profile script, which is simpler but only fires for interactive shells. The steps apply to Ubuntu 26.04 and 24.04, Debian 13 and 12, and AlmaLinux 9 and Rocky Linux 9.
A login notification tells you about successful logins after the fact. It does not stop anyone and it says nothing about failed attempts. Read the limitations section before you rely on it.
Requirements
- A user with
sudorights, and a second SSH session that you keep open while you edit the PAM configuration. - A working
mailcommand. On Debian and Ubuntu it comes from a package such asbsd-mailxormailutils; on AlmaLinux 9 and Rocky Linux 9 it is provided bys-nail. The command only hands the message to a local mail server, so you also need Postfix, Exim or a relay client that can deliver to the outside world.
Test mail delivery first. If this message does not arrive, nothing below will work either:
echo "Test from $(hostname)" | mail -s "Mail test" admin@example.com
Many hosting providers block outbound port 25 by default. In that case configure your mail server to relay through an authenticated SMTP service.
Method 1: pam_exec (all users, all SSH sessions)
pam_exec is a PAM module that runs an external command. Hooked into the session stack of the sshd PAM service, it runs your script whenever an SSH session is opened, whatever shell or command the user asked for. The module passes details to the script as environment variables: PAM_USER, PAM_RHOST (the remote host), PAM_SERVICE, PAM_TTY and PAM_TYPE.
1. Create the script
sudo nano /usr/local/sbin/ssh-login-notify
Paste the following and set your own address in TO:
#!/bin/sh
# Run by pam_exec from /etc/pam.d/sshd
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
# The session stack runs on login and on logout; only report logins.
[ "$PAM_TYPE" = "open_session" ] || exit 0
TO="admin@example.com"
HOST=$(hostname)
NOW=$(date '+%Y-%m-%d %H:%M:%S %Z')
printf 'User: %s\nFrom: %s\nService: %s\nTTY: %s\nTime: %s\n' \
"$PAM_USER" "$PAM_RHOST" "$PAM_SERVICE" "$PAM_TTY" "$NOW" |
mail -s "SSH login: $PAM_USER on $HOST from $PAM_RHOST" "$TO"
exit 0
The script always exits with 0 so that a mail problem is never reported as a failed session. Make it executable and writable by root only:
sudo chown root:root /usr/local/sbin/ssh-login-notify
sudo chmod 700 /usr/local/sbin/ssh-login-notify
2. Confirm that sshd uses PAM
sudo sshd -T | grep -i usepam
The output must be usepam yes. If it is no, PAM session modules are never called and this method cannot work.
3. Add the PAM line
Open the PAM configuration of the SSH service:
sudo nano /etc/pam.d/sshd
Add this line at the end of the file:
session optional pam_exec.so seteuid /usr/local/sbin/ssh-login-notify
What the parts mean:
sessionruns the module when a session is opened and closed, which is after authentication has succeeded.optionalmeans a failure of the module does not block the login. Do not userequiredhere: a broken script would then lock every user out of SSH.seteuidmakespam_execrun the command with the effective user ID of the calling process instead of the real one.
Add log=/var/log/ssh-login-notify.log before the script path while testing if you want the script's output appended to a file. Without it the output is discarded.
4. Test
PAM reads the file at each login, so there is nothing to restart. Keep your current session open, start a new SSH session from another terminal and check your inbox. If no message arrives, look at the SSH log, where pam_exec reports a failed command:
sudo journalctl -u ssh -n 30
On AlmaLinux and Rocky Linux the unit is called sshd. If the script works when you run it by hand but not from a login on those systems, check for SELinux denials with sudo ausearch -m avc -ts recent.
To run the script by hand, supply the variables yourself:
sudo env PAM_TYPE=open_session PAM_USER=deploy PAM_RHOST=203.0.113.50 PAM_SERVICE=sshd PAM_TTY=ssh /usr/local/sbin/ssh-login-notify
5. Reduce the noise
The hook fires for every session that goes through the sshd PAM service: interactive logins, but also scp, sftp, rsync, Git over SSH and automation tools. A backup job that connects every few minutes will fill your inbox. Skip known sources or accounts near the top of the script, after the PAM_TYPE check:
# No mail for the backup host or the backup account
case "$PAM_RHOST" in
198.51.100.7) exit 0 ;;
esac
[ "$PAM_USER" = "backup" ] && exit 0
Method 2: a profile script (interactive shells only)
If you only want to know about people opening a shell and do not want to touch PAM, a script in /etc/profile.d/ is enough. sshd sets the variable SSH_CONNECTION for SSH sessions; its first field is the client address.
sudo nano /etc/profile.d/ssh-login-notify.sh
if [ -n "$SSH_CONNECTION" ]; then
printf 'User: %s\nFrom: %s\nTime: %s\n' \
"$USER" "${SSH_CONNECTION%% *}" "$(date '+%Y-%m-%d %H:%M:%S %Z')" |
mail -s "SSH login: $USER on $(hostname)" admin@example.com
fi
Log in again to test. This method has real gaps:
- It only runs for login shells that read
/etc/profile. A command passed directly, such asssh deploy@203.0.113.10 cat /etc/passwd, andsftporscptransfers produce no mail. - It runs as the user who logs in, so that user must be able to send mail, and can see the recipient address.
- Older tutorials put the same lines in
~/.bashrcor~/.bash_profile. The account owner can edit or delete those files, and~/.bashrcalso runs for every new shell inside a session, so the system-wide location is the better choice.
Limitations of login notifications
- Successful logins only. Failed attempts never reach the session stage. Use your SSH logs or a tool such as Fail2ban for those.
- Not tamper-proof. Someone who gains root can remove the PAM line or stop the mail server. The message for their own login is generated before they get a shell, which is why the mail should leave the server immediately and go to a mailbox hosted elsewhere.
- The login waits for the script.
pam_execruns the command during session setup. A local mail server that queues the message returns at once; amailsetup that talks to a slow remote server directly delays every login. - The address may not be the real origin.
PAM_RHOSTis the host that connected to your server. For a login through a jump host or VPN it shows that intermediate system. - Environment variables are input. The
pam_execmanual warns that the user can influence the environment the command runs in. Keep the script short, quote every variable and setPATHexplicitly, as the example does.
Remove the notification
Delete the pam_exec line from /etc/pam.d/sshd and remove the script, or delete /etc/profile.d/ssh-login-notify.sh for the second method. Open a new session afterwards to confirm that logins still work.
Frequently asked questions
Are logins with an SSH key reported too?
Yes, with the PAM method. Key authentication is handled by sshd itself, but with UsePAM yes the PAM session modules still run for every session, whichever way the user authenticated.
Can I send the alert to a chat service instead of email?
Yes. Replace the mail command in the script with a curl call to the incoming-webhook URL of your chat or push service, and give curl a short timeout such as --max-time 5 so that an unreachable service does not hold up logins.
Will console logins trigger it?
No. The line is in the PAM file of the sshd service only. Logins on the provider's web console use the login service, which has its own file in /etc/pam.d/.
Why do I get two messages per login?
Without the PAM_TYPE check the script runs when the session opens and again when it closes. Keep the first test line of the script in place.