Notify when ssh-ing on a debian system

Configure the Pluggable Authentication Modules in the /etc/pam.d/ directory, specifically in the ssh file.

Append the following line to the file.

 session optional pam_exec.so seteuid /home/user/notify_login.sh

The script /home/user/notify_login.sh with execution rights, can do whaetever you need to.

Here is an example of the script, which sends a notification on a Telegram chatroom.

#!/bin/bash

# notify_login.sh
# sends a message on a telegram chat

TOKEN=""
CHAT_ID=""
URL="https://api.telegram.org/bot$TOKEN/sendMessage"

username=${PAM_USER}
ddate=$(date)
MESSAGE="
**New Login detected**
$(hostname)
from : $PAM_RHOST
user : $PAM_USER
date : $ddate                   
"

function verify_login_ip()
{
	local ip="$1"
	local found=1 # not found
	local known_ips=$(last | tr -s " "| cut -d " " -f3|sort|uniq|grep -E "^[0-9]")
	local netname=""
	local warn=""
	for i in $known_ips;do
		if [ "$ip" == "$i" ];then
			found=0
		fi
	done
	if [ $found -eq 1 ];then
		netname=$(whois $ip|grep -i netname|tr -s " "| cut -d " " -f2)
		warn="**WARNING**
Logging detected from unknown ip address $ip, net-name $netname, please check."
		curl -s -X POST "$URL" -d chat_id="$CHAT_ID" -d text="$warn"
	fi
}

if [ "${PAM_TYPE}" == "open_session" ]; then
	verify_login_ip "$PAM_RHOST"
	curl -s -X POST "$URL" -d chat_id="$CHAT_ID" -d text="$MESSAGE"
fi