Skip to content

Instantly share code, notes, and snippets.

@6d61726b760a
Created February 27, 2023 02:51
Show Gist options
  • Save 6d61726b760a/857dcd20203ec5b93bfb5def919558a9 to your computer and use it in GitHub Desktop.
Save 6d61726b760a/857dcd20203ec5b93bfb5def919558a9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# set -euxo pipefail
# ----
#
# report ip address changes to slack channel
#
# this script detects and reports ip address changes
# to me via personal slack message.
#
# this is useful for those times when i want to connect
# via VPN and then SSH to my work pc.
#
# ----
ipfile="/tmp/ip_address_reporter.txt"
tmpfile=$(mktemp /tmp/ip_address_reporter.XXXXX)
# if ipfile doesnt exist, create it
test -f "${ipfile}" || touch "${ipfile}"
# add the hostname to tmpfile
hostname_s="$(hostname -s)"
printf "hostname: %s\n" "${hostname_s}" | tee -a ${tmpfile} >/dev/null
# get a list of interfaces
interfaces="$(ipconfig getiflist | xargs)"
# add interface addresses to tmpfile
for interface in ${interfaces}; do
interface_addr="$(ipconfig getifaddr ${interface} || echo 'null')"
printf "%s: %s\n" "${interface}" "${interface_addr}" | tee -a ${tmpfile} >/dev/null
done
# diff ipfile/tmpfile
diff_output=$(diff -u ${ipfile} ${tmpfile})
diff_result=$?
# if files are different
if [ $diff_result -ne 0 ]; then
# log message
printf "%s | ip change detected \n" "$(date +'%Y/%m/%d %H:%M:%S')"
# ping slack
printf "%s | sending message to slack \n" "$(date +'%Y/%m/%d %H:%M:%S')"
slack_payload=$(jq \
--null-input \
--arg x "\`\`\`${diff_output##*@}\`\`\`" \
'{blocks: [{type: "header", text: {type: "plain_text", text: "ip change detected", emoji: false}},{type: "section", text: {type: "mrkdwn", text: $x }}]}')
slack_response=$(curl -sS \
-H "Content-Type: application/json" \
-X POST https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX \
-d "${slack_payload}")
printf "%s | slack response: %s \n" "$(date +'%Y/%m/%d %H:%M:%S')" "${slack_response}"
# update ipfile
printf "%s | %s\n" "$(date +'%Y/%m/%d %H:%M:%S')" "$(cp -v ${tmpfile} ${ipfile})"
else
printf "%s | no ip change detected \n" "$(date +'%Y/%m/%d %H:%M:%S')"
fi
# clean up tmpfile
printf "%s | %s\n" "$(date +'%Y/%m/%d %H:%M:%S')" "$(rm -rfv ${tmpfile})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment