Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash Script to notify via Telegram Bot API when user log in SSH
# save it as /etc/profile.d/ssh-telegram.sh
# use jq to parse JSON from ipinfo.io
# get jq from here http://stedolan.github.io/jq/
USERID="<target_user_id>"
KEY="<bot_private_key>"
TIMEOUT="10"
URL="https://api.telegram.org/bot$KEY/sendMessage"
DATE_EXEC="$(date "+%d %b %Y %H:%M")"
TMPFILE='/tmp/ipinfo-$DATE_EXEC.txt'
if [ -n "$SSH_CLIENT" ]; then
IP=$(echo $SSH_CLIENT | awk '{print $1}')
PORT=$(echo $SSH_CLIENT | awk '{print $3}')
HOSTNAME=$(hostname -f)
IPADDR=$(hostname -I | awk '{print $1}')
curl http://ipinfo.io/$IP -s -o $TMPFILE
CITY=$(cat $TMPFILE | jq '.city' | sed 's/"//g')
REGION=$(cat $TMPFILE | jq '.region' | sed 's/"//g')
COUNTRY=$(cat $TMPFILE | jq '.country' | sed 's/"//g')
ORG=$(cat $TMPFILE | jq '.org' | sed 's/"//g')
TEXT="$DATE_EXEC: ${USER} logged in to $HOSTNAME ($IPADDR) from $IP - $ORG - $CITY, $REGION, $COUNTRY on port $PORT"
curl -s --max-time $TIMEOUT -d "chat_id=$USERID&disable_web_page_preview=1&text=$TEXT" $URL > /dev/null
rm $TMPFILE
fi
@yarons

This comment has been minimized.

Copy link

commented Jan 4, 2017

Nice script! I want to make some changes in order to make it read an image from a website and post it to a group, it's a group at work where we usually order from the same place and the menu is an image so this could be very handy.

I want to propose a change to simplify your script.
Instead of writing: cat $TMPFILE | jq '.city' | sed 's/"//g'
Just write: jq -r '.city' < $TMPFILE
-r argument will clear the quotes.
Piping instead of using cat and then piping is more elegant.

Another trick I would recommend is doing the same with awk.
Instead of: echo $SSH_CLIENT | awk '{print $1}'
Do this: awk '{print $1}' <<< $SSH_CLIENT

Thank you very much!

@TomSDEVSN

This comment has been minimized.

Copy link

commented Jan 29, 2017

License?

@zamber

This comment has been minimized.

Copy link

commented Feb 19, 2017

I made a fork that ditches jq for awk (it's not compiled for arm, so it didn't work on a Raspberry Pi).
Also added a note that you can get your $USERID from https://t.me/get_id_bot.
https://gist.github.com/zamber/88ef4f62632375c27b06d33295e68f73

@faffa42

This comment has been minimized.

Copy link

commented Dec 12, 2017

Hi! Cool script. Is there a way to get a notification when an IP address establish a connection to a specific port?

@Akelis

This comment has been minimized.

Copy link

commented Feb 26, 2018

Hi, how to get each parameter in seprate line ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.