Skip to content

Instantly share code, notes, and snippets.

@hu553in
Last active May 18, 2024 00:05
Show Gist options
  • Save hu553in/d33e4d645166ede0fd3f97190256705e to your computer and use it in GitHub Desktop.
Save hu553in/d33e4d645166ede0fd3f97190256705e to your computer and use it in GitHub Desktop.
Send Telegram notification about SSH login
#!/bin/bash
# this file need to be stored in /etc/profile.d
# variables below must be initialized in order to make script working
CHAT_ID=""
BOT_TOKEN=""
DATE_EXEC="$(date "+%d %b %Y %H:%M")"
TMPFILE='/tmp/ipinfo-$DATE_EXEC.txt'
if [ -n "$SSH_CLIENT" ] && [ -z "$TMUX" ]; 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 https://ipinfo.io/$IP -s -o $TMPFILE
ORG=$(cat $TMPFILE | sed -n 's/^ "org":[[:space:]]*//p' | sed 's/"//g')
CITY=$(cat $TMPFILE | sed -n 's/^ "city":[[:space:]]*//p' | sed 's/"//g')
REGION=$(cat $TMPFILE | sed -n 's/^ "region":[[:space:]]*//p' | sed 's/"//g')
COUNTRY=$(cat $TMPFILE | sed -n 's/^ "country":[[:space:]]*//p' | sed 's/"//g')
TEXT="Date: $DATE_EXEC\n\nUser: $USER\n\nHostname: $HOSTNAME\n\nHost IP: $IPADDR\n\nFrom: $IP\n\nOrg: $ORG\n\nLocation: $CITY $REGION $COUNTRY\n\nPort: $PORT"
curl \
--request POST \
--url "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
--header "Content-Type:application/json" \
--data "{\"chat_id\":$CHAT_ID,\"text\":\"$TEXT\"}" > /dev/null
rm $TMPFILE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment