Skip to content

Instantly share code, notes, and snippets.

@mpalet
Last active February 1, 2018 09:05
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 mpalet/a4cd05bc775a1a06f1f9ee27a2dfc58d to your computer and use it in GitHub Desktop.
Save mpalet/a4cd05bc775a1a06f1f9ee27a2dfc58d to your computer and use it in GitHub Desktop.
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