Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Setup ssh login push notifications with telegram bot
#!/bin/bash
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit
fi
#create ssh wrapper to execute pushmessage
SSH_WRAPPER_PATH=/usr/local/sbin/ssh-wrapper
cat - > $SSH_WRAPPER_PATH <<'EOF'
#!/bin/bash
SHELL=$(getent passwd $USER | cut -d: -f7)
IP=$(echo $SSH_CONNECTION | cut -d " " -f 1)
HOSTNAME=$(dig -x $IP +short)
if [ -z "${HOSTNAME}" ]; then
HOSTNAME=$IP
fi
LOCALHOST=$(hostname)
/usr/local/bin/pushmessage \
"SSH login on $LOCALHOST" \
"User ${USER} has logged in from ${HOSTNAME}"
${SSH_ORIGINAL_COMMAND-$SHELL}
EOF
chmod +x $SSH_WRAPPER_PATH
#add ssh wrapper to sshd_config
LINE='ForceCommand /usr/local/sbin/ssh-wrapper'
FILE=/etc/ssh/sshd_config
grep -qF "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
#create pushmessage script
PUSHMESSAGE_PATH=/usr/local/bin/pushmessage
echo "Enter telegram chatid:"
read pchatid
echo "Enter telegram bot API token:"
read ptoken
cat - > $PUSHMESSAGE_PATH <<'EOF'
#!/bin/bash
if [ "$#" != 2 ]; then
echo "Usage: $0 TITLE MESSAGE" >&2
exit 1
fi
EOF
echo "APITOKEN=$ptoken" >> $PUSHMESSAGE_PATH
echo "CHATID=$pchatid" >> $PUSHMESSAGE_PATH
cat - >> $PUSHMESSAGE_PATH <<'EOF'
curl -s -X POST \
--form-string "chat_id=$CHATID" \
--form-string "text=*$1*"$'\n'"$2" \
--form-string "parse_mode=markdown" \
https://api.telegram.org/bot$APITOKEN/sendMessage >/dev/null
EOF
chmod +x $PUSHMESSAGE_PATH
systemctl restart sshd
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.