There are cases where you are interested in getting a email message on every successful login through SSH. This could have been solved by adding a simple line in .bash_profile for every user, but this solution does not catch all SSH logins. The preferred way of doing it is by using PAM and a custom email notify script.
Add the following line to the bottom of file /etc/pam.d/sshd
session optional pam_exec.so seteuid /usr/local/bin/login-notify.sh
This is the contents of /usr/local/bin/login-notify.sh
#!/bin/sh # Change these two lines: sender="firstname.lastname@example.org" recepient="root" 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 script executable
# chmod 0700 /usr/local/bin/login-notify.sh
This is the email message you receive the next time you or someone else log in using SSH
SSH Login: username from hostname-remote.user.com on target-host.example.com
This has been tested on CentOS 7 and Ubuntu 18.04, but I guess most recent distributions supports this.
Sending emails on login may conflict with data privacy on multiuser systems. This can be circumvented by just sending emails for specific users or root (if at all accessible via SSH). I might cover that in a later post.