Featured image of post Setting up notifications via Telegram for SSH login/logoff

Setting up notifications via Telegram for SSH login/logoff

Setting up notifications via Telegram for SSH login/logoff

SSH Telegram Notification

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:

1
/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:

1
mkdir /etc/pam.scripts

Now we create a file with the name “login-notification.sh” in the newly created folder:

1
/etc/pam.scripts/login-notification.sh

We now insert the following code there:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/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:

1
sudo chmod +x /etc/pam.scripts/login-notification.sh

Now let’s edit the PAM config for SSHD:

1
nano /etc/pam.d/sshd

We insert the following line at the bottom:

1
2
# 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
Last updated on Jun 01, 2024 00:00 UTC
Servus.
Built with Hugo
Theme Stack designed by Jimmy