Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Created February 20, 2023 10:35
Show Gist options
  • Save gilangvperdana/202e3e066cf50c2ef323110b1bed428a to your computer and use it in GitHub Desktop.
Save gilangvperdana/202e3e066cf50c2ef323110b1bed428a to your computer and use it in GitHub Desktop.
Alert when IP Address on Specific Interface Changed

Script

#!/bin/bash

# Atur token bot Telegram dan ID obrolan
TOKEN="TOKEN_CHAT"
CHAT_ID="CHAT_ID"
HOSTNAME=$(hostname)
EXPECTATION="OUR_EXPECTATION_IP"

# Ambil nama interface yang mengandung kata "tun" dan memiliki alamat IP yang dimulai dengan "10.8."
INTERFACE=$(ip addr | grep -oP '^\d+:\s+\Ktun.*(?=\:)' | while read i; do if [[ "$(ip addr show dev "$i" | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | cut -d. -f1,2)" == "10.8" ]]; then echo "$i"; fi; done)

# Jika interface yang memenuhi syarat ditemukan, ambil alamat IP saat ini dari interface tersebut
if [ -n "$INTERFACE" ]; then
  CURRENT_IP=$(ip addr show dev "$INTERFACE" | grep -oP '(?<=inet\s)\d+(\.\d+){3}')

  # Jika alamat IP berubah, kirimkan pesan ke Telegram
  if [ "$CURRENT_IP" != "$(cat /tmp/last_ip)" ]; then
    OLD_IP=$(cat /tmp/last_ip)
    MESSAGE="IP address of $INTERFACE interface on Instance $HOSTNAME has changed. Old IP address was $OLD_IP, new IP address is $CURRENT_IP. IP Should Be $EXPECTATION"
    curl -s -X POST "https://api.telegram.org/bot$TOKEN/sendMessage" \
      -d chat_id="$CHAT_ID" \
      -d text="$MESSAGE"
    echo "$CURRENT_IP" > /tmp/last_ip
  fi
else
  echo "Interface not found"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment