Skip to main content

Sending e-mail on successful SSH login / detecting SSH log-ins

First, there are longer articles on this very subject if you are looking for something more elaborate. This is my take at a condensed version.

I have a script at /usr/local/bin/on_ssh_login.sh like this:

#! /usr/bin/env bash
if [ "${PAM_TYPE}" != "open_session" ]; then
    exit 0
fi

cat <<BODY | mailx -s "Log-in to ${PAM_USER:-???}@$(hostname -f) \
(${PAM_SERVICE:-???}) detected" mail@hostname.invalid
# $(LC_ALL=C date +'%Y-%m-%d %H:%M (UTC%z)')
$(env | grep '^PAM_' | sort)
BODY

exit 0

It uses command mailx of S-Nail to send e-mail. A config file for S-Nail at /root/.mailrc as simple as two lines total like…

set smtp-use-starttls
set smtp=your.smtp.server.here.invalid

…made it send e-mail for me, but if you need a different port, TLS rather than STARTTLS and/or logging in with SMTP as a specific user, some of these docs [1] [2] [3] [4] should have you covered.

The script can and should first be tested like this:

# PAM_TYPE=open_session /usr/local/bin/on_ssh_login.sh

Once that worked, we can make PAM call out to the script for every login to SSH by appending line…

session    required     pam_exec.so /usr/local/bin/on_ssh_login.sh

to file /etc/pam.d/sshd.

NOTE: Be sure to keep a second SSH shell session open while trying out if a new login to SSH sends e-mail to you as expected.

Done. Cheers!