This is an email alert that is triggered once a SSH login succeeds
First we will create the script itself in the ssh folder /etc/ssh/login-notify.sh:
#!/bin/sh
# Change these two lines:
sender="[email protected]"
recepient="[email protected]"
if [ "$PAM_TYPE" != "close_session" ]; then
host="hostname"
subject="SSH Login: $PAM_USER from $PAM_RHOST on $host"
# Message to send, e.g. the current environment variables.
message="env"
echo "$message" | mailx -r "$sender" -s "$subject" "$recepient"
fi
Make the file executable, then add the following line to the end of the sshd pam file in /etc/pam.d/sshd
session optional pam_exec.so seteuid /etc/ssh/login-notify.sh
It’s set to optional for testing, as it would prevent login if the script fails, test it first before switching it to required