Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Created October 6, 2022 12:09
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 gilangvperdana/d979b548d5d3bfead5a31328004d00c2 to your computer and use it in GitHub Desktop.
Save gilangvperdana/d979b548d5d3bfead5a31328004d00c2 to your computer and use it in GitHub Desktop.
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