Send a Telegram message on SSH login

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/


#!/usr/bin/env bash

# Import credentials form config file
. /etc/ssh-login-alert-telegram/credentials.conf

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 ""`


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

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.


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/

Step 3: Save the Configuration Variables

Save the KEY and USERID in a separate file.  It can really be stored anywhere but I choose to store mine in /etc/ssh-login-alert-telegram/credentials.conf since I am backing up my /etc directory nightly.

Make the directory:

sudo mkdir /etc/ssh-login-alert-telegram

Create the file:

sudo nano /etc/ssh-login-alert-telegram/credentials.conf

Enter the credential information:


Save that file.  

That should be it.  Now, every time someone logs into the server you get a message to tell you that someone logged in with their IP and some other details.  Modify the message to suit your needs.

Leave a Comment