Last active
July 6, 2019 04:48
-
-
Save kenshin17/5a6dd27beea397587e83a99647abd66c to your computer and use it in GitHub Desktop.
SSH login alert via Telegram
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#File: /etc/profile.d/ssh_login_alert.sh | |
################################## | |
#wget https://raw.githubusercontent.com/xxxx -O /etc/profile.d/ssh_login_alert | |
#chmod +x /etc/profile.d/ssh_login_alert | |
################################## | |
USERID="xxx" | |
KEY="xxx:xx-xx" | |
TIMEOUT="10" | |
URL="https://api.telegram.org/bot$KEY/sendMessage" | |
#Collect date & time. | |
DATE_EXEC="$(date "+%d %b %Y %H:%M")" | |
#Create a temporary file to keep data in. | |
TMPFILE='/tmp/ipinfo-$DATE_EXEC.txt' | |
#Trigger | |
if [ -n "$SSH_CLIENT" ] && [ -z "$TMUX" ]; then | |
#Get Client IP address. | |
IP=$(echo $SSH_CLIENT | awk '{print $1}') | |
#Get SSH port | |
PORT=$(echo $SSH_CLIENT | awk '{print $3}') | |
#Get hostname | |
HOSTNAME=$(hostname -f) | |
IPADDR=$(hostname -I | awk '{print $1}') | |
#Get info on client IP. | |
curl https://ipinfo.io/$IP -s -o $TMPFILE | |
#Client IP info parsing | |
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') | |
ORG=$(cat $TMPFILE | sed -n 's/^ "org":[[:space:]]*//p' | sed 's/"//g') | |
TEXT="$DATE_EXEC: *${USER}* logged in to *$HOSTNAME* ($IPADDR) from $IP - $ORG - $CITY, $REGION, $COUNTRY port $PORT" | |
curl -s --max-time $TIMEOUT -d "chat_id=$USERID&disable_web_page_preview=1&text=$TEXT&parse_mode=markdown" $URL > /dev/null | |
#clean up after | |
rm $TMPFILE | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment