# 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
Last active
September 23, 2017 07:15
-
-
Save mattes/6e3fbc5ad02140dd428fe4abf9bd74e8 to your computer and use it in GitHub Desktop.
On IP Change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# copy to /usr/local/var/on-ip-change/scripts/example-script.sh | |
# echo new ip address | |
echo $1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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