#!/usr/bin/env bash # monitor-ip.sh checks whether the external IP address has changed, and if so, sends a mail notification and Gotify. host=$(hostname) redbold="\033[1;31m" greenbold="\033[1;32m" green="\033[0;32m" yellow="\033[0;33m" yellowbold="\033[1;33m" bold="\033[1m" #bold_under="\033[1;4m" underline="\033[4m" reset="\033[0m" notif=true ### Help Function: Help() { echo "monitor-ip.sh checks whether the external IP address has changed," echo " and if so, sends a mail notification and Gotify." echo echo "Syntax: monitor-ip.sh [OPTION]" echo "Example: monitor-ip.sh -h display this help !" echo echo "Options:" echo "-h Print this Help." echo "-n Just check IP. Don't send notification'." } while getopts "hn" options; do case "${options}" in n) notif=false ;; h|*) Help ; exit 2 ;; esac done shift "$((OPTIND-1))" MSMTP=$(which msmtp) SSMTP=$(which ssmtp) if [ -n $MSMPT ] ; then MAIL=$MSMTP elif [ -n $SSMTP ] && [ -z $MAIL ] ; then MAIL=$SSMTP else echo "No msmtp or ssmtp binary found in PATH: $PATH" ; exit 1 fi dotenv () { set -a # shellcheck disable=SC1091 [ -f ".env" ] && . ".env" || echo -e "${red}\nNo .env file found ! No token for gotify.${reset}" set +a } send_mail_notification() { FromHost=$(hostname) # User variables: SendMailFrom="router@clicclac.info" SendMailTo="router@clicclac.info" SubjectTag="monitor_ip.sh" printf "\nSending email notification ...\n" $MAIL $SendMailTo << __EOF From: "$FromHost" <$SendMailFrom> date:$(date -R) To: <$SendMailTo> Subject: [$SubjectTag] L IP sur $FromHost a changée ! Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Ancienne IP: $old_ip_externe Nouvelle IP: $ip_externe __EOF } send_gotify_notification() { now=$(date +"%d-%m-%Y %T") gotify_server="https://gotify.maboiteverte.fr" TITLE="IP has changed on $host" MESSAGE="**L'IP externe a changé:**\n\n - ancienne IP: $old_ip_externe\n - **nouvelle IP: $ip_externe**\n\n [^]: $now\n" PRIORITY=8 URL="$gotify_server/message?token=$token_gotify&?format=markdown" echo -e "Sending notification to $gotify_server ..." curl -L -S -s --data '{"message": "'"${MESSAGE}"'", "title": "'"${TITLE}"'", "priority":'"${PRIORITY}"', "extras": {"client::display": {"contentType": "text/markdown"}}}' -H 'Content-Type: application/json' "$URL" > /dev/null [ $? -eq 0 ] && echo -e "${greenbold}Gotify notification sent successfully !${reset}" || echo -e "${redbold}error sending Gotify notification !${reset}" } dotenv old_ip_externe=$(cat monitor-ip.pref) ip_externe=$(dig @resolver4.opendns.com myip.opendns.com +short) echo $ip_externe > monitor-ip.pref if [ "$ip_externe" != "$old_ip_externe" ]; then echo "L'IP externe a changé" echo "IP externe: $ip_externe" if [ $notif == true ]; then send_mail_notification #send_gotify_notification pushover -a "syno" -m "L'IP externe a changé:
- ancienne IP: $old_ip_externe
- nouvelle IP: $ip_externe" -f 1 fi else echo "L'IP externe n'a pas changé" echo "IP externe: $ip_externe" fi