Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Alert IP Client when Connect to SSH

Goals

  • We can monitor IP of SSH Client.
  • Alert will be goes to Telegram.

Execute

Make Alert Script

mkdir -p /opt/alert-ssh-remote/
nano alert.sh
# CREATE THIS FILE ON /opt/alert-ssh-remote/alert.sh
#!/usr/bin/env bash

# Import credentials form config file
. /opt/alert-ssh-remote/credentials.config
for i in "${USERID[@]}"
do
URL="https://api.telegram.org/bot${KEY}/sendMessage"
DATE="$(date "+%d %b %Y %H:%M")"

if [ -n "$SSH_CLIENT" ]; then
        CLIENT_IP=$(echo $SSH_CLIENT | awk '{print $1}')

        SRV_HOSTNAME=$(hostname -f)
        SRV_IP=$(hostname -I | awk '{print $1}')

        IPINFO="https://ipinfo.io/${CLIENT_IP}"

        TEXT="Connection from *${CLIENT_IP}* as ${USER} on *${SRV_HOSTNAME}* (*${SRV_IP}*)
        Date: ${DATE}
        More informations: [${IPINFO}](${IPINFO})"

        curl -s -d "chat_id=$i&text=${TEXT}&disable_web_page_preview=true&parse_mode=markdown" $URL > /dev/null
fi
done
chmod +x alert.sh

Make Telegram Credentials

nano /opt/alert-ssh-remote/credentials.config
# CREATE THIS FILE ON /opt/alert-ssh-remote/credentials.config
# Your USERID or Channel ID to display alert and key, we recommend you create new bot with @BotFather on Telegram

USERID=( -74638xxxx )
KEY="5416297136:AAHAx3p-yFsDr4nG8h5YNBI6nRyPe6xxxx"

Make profile.d to execute sh every client connect

nano /etc/profile.d/telegram-alert.sh
# CREATE THIS FILE ON /etc/profile.d/telegram-alert.sh
#!/usr/bin/env bash
# Log connections
bash /opt/alert-ssh-remote/alert.sh
chmod +x /etc/profile.d/telegram-alert.sh

Verify

If you want to verify, lets restart connection from SSH then monitor on your BOT Telegram

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment