Skip to content

Instantly share code, notes, and snippets.

@yarons
Forked from matriphe/ssh-telegram.sh
Last active January 6, 2017 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yarons/532bcf4b9ebe75997b15e178cfe106f3 to your computer and use it in GitHub Desktop.
Save yarons/532bcf4b9ebe75997b15e178cfe106f3 to your computer and use it in GitHub Desktop.
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=$(awk '{print $1}' <<< $SSH_CLIENT)
PORT=$(awk '{print $3}' <<< $SSH_CLIENT)
HOSTNAME=$(hostname -f)
IPADDR=$(hostname -I | awk '{print $1}')
curl http://ipinfo.io/$IP -s -o $TMPFILE
CITY=$(jq -r '.city' < $TMPFILE)
REGION=$(jq -r '.region' < $TMPFILE)
COUNTRY=$(jq -r '.country' < $TMPFILE)
ORG=$(jq -r '.org' < $TMPFILE)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment