Its been awhile since I posted but I found a neat little trick to send a Telegram alert when a user logs in via SSH to one of my VPS’s.
Its pretty simple so it doesn’t take too long to setup.
Step 1: Create the Telegram Bot
You will need to message @BotFather to get started. This guide isn’t really about setting up Telegram bots. I may do a guide in the future but for now I am assuming you have that part setup.
If you need more information about setting it up you can refer to the documentation Telegram Documentation or another guide on the internet.
All you will need for now is your USERID which looks like: -123456789
and the KEY which is in the format of: 123456789:AAAAAAAAAAAAAAA
Step 2: Script to Send the Message
Scripts in /etc/profile.d will execute when a SSH user logs in.
Create a new script:
sudo nano /etc/profile.d/telegram-login-alert.sh
Script:
#!/usr/bin/env bash
# Import credentials form config file
. /etc/ssh-login-alert-telegram/credentials.conf
URL="https://api.telegram.org/bot${KEY}/sendMessage"
DATE="$(date "+%d %b %Y %H:%M")"
if [ -n "$SSH_CLIENT" ]; then
CLIENT_IP=$(echo $SSH_CLIENT | awk '{print $1}')
SRV_HOSTNAME=$(hostname -f)
SRV_IP=`curl -s "https://scott.stevensononthe.net/whatismyip.php"`
IPINFO="https://www.infobyip.com/ip-${CLIENT_IP}.html"
TEXT="Connection from *${CLIENT_IP}* as ${USER} on *${SRV_HOSTNAME}* (*${SRV_IP}*)%0A%0ADate: ${DATE}%0A%0AIP information: [${IPINFO}](${IPINFO})"
curl -s -d "chat_id=$i&text=${TEXT}&disable_web_page_preview=true&parse_mode=markdown" $URL > /dev/null
fi
The script will read another file with the credentials of the channel and user. We will make that next.
The URL that the message needs to be sent to include our KEY.
URL="https://api.telegram.org/bot${KEY}/sendMessage"
The majority of the code is just generating data for the message. It can be stripped down to the sending of the message:
curl -s -d "chat_id=$i&text=${TEXT}&disable_web_page_preview=true&parse_mode=markdown" $URL > /dev/null
Ensure the script is executable:
sudo chmod +x /etc/profile.d/telegram-login-alert.sh
(more…)