Open original
Open original
Open original
Open original
the admin café

Menu / Linux

Setting up notifications via Telegram for SSH login/logoff

Get a Telegram message every time someone logs in to or out of your Linux server over SSH, with a Telegram bot, a small script and PAM.

Lukas·Jun 1, 2024·1 min · Espresso 1 min · Espresso· Beginner · Mild

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:

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

bash
mkdir /etc/pam.scripts

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

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

We now insert the following code there:

bash
#!/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:

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

Now let's edit the PAM config for SSHD:

bash
nano /etc/pam.d/sshd

We insert the following line at the bottom:

bash
# 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.

Still sipping? Another one?

pairs well with this one

the admin café

Open whenever the shell is. Right now, apparently.

Tip jar. Costs nothing, cheers me up anyway.

© 2023–2026 Lukas. Servus.

Esc

Fresh today

Type to search all articles. ↑ ↓ and Enter to open a result.