First we have to write to the “BotFather” in Telegram, because we have to create a bot.
Simply send the following command and then follow the process:
/newbot
You will then receive your API token. Please treat it like a password and save it in the PWS.
Now create a new group in Telegram and add the bot you have just created.
Then open Telegram in the browser of your choice and select the group you have created. You will then see the group ID in the address bar at the top. Everything after the # symbol belongs to the ID. The “-” symbol belongs to the ID!
In my case, the group ID is “-4250408318”, for example.
We will now create a new folder on our Linux server:
mkdir /etc/pam.scripts
Now we create a file with the name “login-notification.sh” in the newly created folder:
/etc/pam.scripts/login-notification.sh
We now insert the following code there:
#!/bin/bash
TOKEN="Euer-Telegram-Bot-Token"
ID="Eure-Telegram-Group-ID"
HOSTNAME=$(hostname -f)
DATE="$(date +"%d.%b.%Y -- %H:%M")"
MESSAGE="<b>$PAM_USER</b> did action: '<b>$PAM_TYPE</b>' at <u>$DATE</u> on $HOSTNAME from IP: <code>$PAM_RHOST</code> !"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"
curl -s -X POST $URL -d chat_id=$ID -d text="$MESSAGE" -d parse_mode='HTML' 2>&1 /dev/null
exit 0
Then save the file with CTRL + O + Enter and close it with CTRL + X.
As it is a script, we still need to make it executable:
sudo chmod +x /etc/pam.scripts/login-notification.sh
Now let's edit the PAM config for SSHD:
nano /etc/pam.d/sshd
We insert the following line at the bottom:
# SSH Notification script
session required pam_exec.so /etc/pam.scripts/login-notification.sh
Save the file again with CTRL + O + Enter and then close with CTRL + X.
You will now receive a notification in the Telegram group every time you successfully log in and log out.
Licensed under CC BY-NC-SA 4.0.
