Add remove multiple IPv6 addresses on prefix change

A bash script to add and delete multiple IPv6 addresses on prefix change.

First step is to create a text file with "0000:0000:0000:0000" as text which will store the IPv6 prefix of your server. Create a file using this example.

IPv6Prefix.txt
echo "0000:0000:0000:0000" > $HOME/IPv6Prefix.txt
chmod 777 $HOME/IPv6Prefix.txt

If you choose to manually create the file then first create a blank file IPv6Prefix.txt and save it in /root/IPv6Prefix.txt, now open the file and type 0000:0000:0000:0000 and save and close the file. For some reason the IPv6Prefix.txt should not be empty for comparison this is why I had to type zero and save the file. Give the permissions 0777 to IPv6Prefix.txt so the script can write to it.

Now the second step is to create a text file containing all your IPv6 suffixes that you want to add to your server. For example

ipv6-addresses.txt
printf %s '5e37:080b:66b7:68bb
52bf:52fe:a1df:60e3
3b32:a9d4:a9f3:074f
9ec7:f4da:b166:0a5f
620c:eb97:3e93:ece3
551b:dda7:d78d:c09a
cf34:cb8b:b1be:12a4
3600:af53:10ad:f647
9527:dcc4:4926:51ba
76a2:410f:704b:8d9c' >> $HOME/ipv6-addresses.txt

Now create a bash file to do all the processing. You need to create a schedule to periodically check the IPv6 prefix for change. Change the interface name (ens18) to the name of your interface.

ipv6-add-delete.sh
#!/bin/bash

IPv6PrefixFile=$HOME/IPv6Prefix.txt
IPv6Prefix=$(cat $IPv6PrefixFile)

__rfc5952_expand () {
read addr mask < <(IFS=/; echo $1)
quads=$(grep -oE "[a-fA-F0-9]{1,4}" <<< ${addr/\/*} | wc -l)
grep -qs ":$" <<< $addr && { addr="${addr}0000"; (( quads++ )); }
grep -qs "^:" <<< $addr && { addr="0000${addr}"; (( quads++ )); }
[ $quads -lt 8 ] && addr=${addr/::/:$(for (( i=1; i<=$(( 8 - quads )) ; i++ )); do printf "0000:"; done)}
addr=$(for quad in $(IFS=:; echo ${addr}); do printf "${delim}%04x" "0x${quad}"; delim=":"; done)
[ ! -z $mask ] && echo $addr/$mask || echo $addr
}

IPv6Current=$(/sbin/ip -6 addr | grep inet6 | grep -vE 'host|temporary' | grep -F 'scope global dynamic' | sed -e 's/^.*inet6 \([^ ]*\)\/.*$/\1/;t;d' | grep '^2' | head -n1)
IPv6Current="$(__rfc5952_expand $IPv6Current)"

IPv6Current=${IPv6Current:0:19}

if [ $IPv6Current != $IPv6Prefix ]; then

for i in $(cat $HOME/ipv6-addresses.txt);
do
	ip -6 addr del ${IPv6Prefix}:${i} dev ens18
	ip -6 addr add ${IPv6Current}:${i} dev ens18
done

echo $IPv6Current > $IPv6PrefixFile
fi

exit 0

The final step is to reset the file IPv6Prefix.txt on your computer startup or reboot. Create a crontab entry to reset the file on each reboot.

crontab -e
@reboot sleep 60 && echo "0000:0000:0000:0000" > $HOME/IPv6Prefix.txt

Let me know if you have any comments or if there is any error in this guide.