This is a useful hack for VPS servers to send an email as a login-notify to an email address.
Prerequisites
You need to have a working mail subsystem on your host so that the mail command works.
This works with Ubuntu 22.04 and later versions.
Modify PAM to notify on login
Open the file /etc/pam.d/common-session
and at the bottom add the following line:
session optional pam_exec.so /root/script/login-notify
Login-Notify script
Create the following script in /root/script/login-notify
#!/bin/bash
#
# This script is run by PAM from /etc/pam.d/common-session by adding the following
# line to the bottom of the configuration file:
#
# session optional pam_exec.so /root/script/login-notify
#
# Make sure the script is executeable
#
# ichi@ichimusai.org
# Revision 1.0.0
#
[ "$PAM_TYPE" = "open_session" ] || exit 0
{
echo "User: $PAM_USER"
echo "Ruser: $PAM_RUSER"
echo "Rhost: $PAM_RHOST"
echo "Service: $PAM_SERVICE"
echo "TTY: $PAM_TTY"
echo "Date: `date +"%y%m%d-%H%M%S"`"
echo "Server: `hostname -s`"
} | mail -s "[`hostname -s`] $PAM_SERVICE login: $PAM_USER" anders@sikvall.se &
This script will now be executed upon login and should send an email to the recipient with login matters.