If you’re googling this topic there is an unbelievable amount of grossly negligent “solutions” to this problem.
The top two results in my search engine tell you to do this:
$ cd /root
$ vi .bashrc
And trigger some mail there with the information wanted. This is insecure for multiple reasons:
ssh -N
This is the reason why I have the following setup I hereby share with you:
This script (placed somewhere in your system) is used to send a mail after a login. To trigger it, PAM has to be told so in /etc/pam.d/sshd:
session optional pam_exec.so seteuid /etc/ssh/login_notify.sh
The second word optional is important here as it allows a login even if the script doesn’t exit with code 0. If you replace it with required the login will fail if the script fails. This might not be what you want because the mail sending process may be broken because some issues your server might have and this will prevent you from logging in. Don’t forget to make the script itself executable:
chmod +x /path/to/login_notify.sh