Skip to content

Instantly share code, notes, and snippets.

@mattes
Last active September 23, 2017 07:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattes/6e3fbc5ad02140dd428fe4abf9bd74e8 to your computer and use it in GitHub Desktop.
Save mattes/6e3fbc5ad02140dd428fe4abf9bd74e8 to your computer and use it in GitHub Desktop.
On IP Change

ON IP CHANGE

Installation

# Copy files into /usr/local/bin/on-ip-change.sh and /etc/systemd/system/on-ip-change.service
mkdir -p /usr/local/var/on-ip-change/scripts
sudo systemctl enable on-ip-change.service
sudo systemctl start on-ip-change.service
# Add your scripts to /usr/local/var/on-ip-change/scripts

# Follow logs ...
sudo journalctl -f -u on-ip-change
#!/usr/bin/env bash
# copy to /usr/local/var/on-ip-change/scripts/example-script.sh
# echo new ip address
echo $1
[Unit]
Description=Run scripts when IP changes
Requires=network.target
[Service]
ExecStart=/usr/local/bin/on-ip-change.sh /usr/local/var/on-ip-change/scripts 30
Restart=on-failure
[Install]
WantedBy=multi-user.target
#!/usr/bin/env bash
# run all *.sh scripts when IP changes
scripts_dir="$1"
# run IP detection every n seconds
check_interval_sec=$2
current_ip=""
while true; do
# get current ip and verify syntax
new_ip=$(dig +short myip.opendns.com @resolver1.opendns.com)
if [[ ! "$new_ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
echo "Invalid IP returned $new_ip"
else
# check if ip has changed
if [[ "$new_ip" != "$current_ip" ]]; then
current_ip="$new_ip"
echo "--> New IP $new_ip"
# run scripts
for file in $scripts_dir/*.sh; do
echo "--> $file"
( $file "$new_ip" )
echo
done
fi
fi
# wait until next check
sleep $check_interval_sec
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment