Parts of this guide were pulled from this askubuntu article https://bit.ly/3mKrrQd
Warning: As always when you change the login configuration, leave a backup ssh session open in the background and test the login from a new terminal.
Sign up for Pushover if you haven’t already. Create an Application and grab the app and user keys.
Create file /etc/ssh/login-notify.sh
with the following contents:
#!/bin/sh
# Change these two lines:
PUSHOVER_USER_KEY="***USERKEY***"
PUSHOVER_APP_KEY="***APPKEY***"
CLIENT="***NAME_OF_YOUR_SERVER***"
USE_HTML_FORMAT=0
# update line below to point to the interface you want the IP Address for. Ex. eth0, wlan0, etc.
IPADDRESS=$(ifconfig eth0 | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
if [ "$PAM_TYPE" != "close_session" ]; then
host="`hostname`"
TITLE="SSH Login :: $CLIENT :: User '$PAM_USER' [$PAM_RHOST] logged into '$CLIENT' [$IPADDRESS]"
# Message to send, e.g. the current environment variables.
MESSAGE="`env`"
wget https://api.pushover.net/1/messages.json --post-data="token=$PUSHOVER_APP_KEY&user=$PUSHOVER_USER_KEY&message=$MESSAGE&title=$TITLE&html=$USE_HTML_FORMAT" -qO- > /dev/null 2>&1 &
fi
if [ "$PAM_TYPE" = "close_session" ]; then
host="`hostname`"
TITLE="SSH Disconnect :: $CLIENT :: User '$PAM_USER' disconnected from '$CLIENT' [$IPADDRESS]"
# Message to send, e.g. the current environment variables.
MESSAGE="`env`"
wget https://api.pushover.net/1/messages.json --post-data="token=$PUSHOVER_APP_KEY&user=$PUSHOVER_USER_KEY&message=$MESSAGE&title=$TITLE&html=$USE_HTML_FORMAT" -qO- > /dev/null 2>&1 &
fi
Runsudo chmod +x login-notify.sh
to make it executable.
Give ownership to root with sudo chown root:root login-notify.sh
, so that nobody can mess with the script.
Once you have that, you can add the following line to /etc/pam.d/sshd
(with the correct /path/to/login-notify.sh
of course). I placed it right below the line that prints the users mailbox info.
# Send notification on user connect/disconnect
session optional pam_exec.so seteuid /etc/ssh/login-notify.sh
For testing purposes, the module is included as optional
, so that you can still log in if the execution fails. You could change optional
to required
. However, this will prevent any SSH login unless the script is runs successfully.