Skip to content

Instantly share code, notes, and snippets.

@Gowee
Last active April 4, 2022 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gowee/32c11085a88961310fee005c89201007 to your computer and use it in GitHub Desktop.
Save Gowee/32c11085a88961310fee005c89201007 to your computer and use it in GitHub Desktop.
Rotate Wireguard ports
#!/bin/sh
set -u
WGIF="winnie"
STEP=3600
PSTART=5500
PEND=5999
CONFFILE="/etc/wireguard/$WGIF.conf"
PLEN=$((PEND-PSTART+1))
timestamp=$(date +%s)
slot=$(((timestamp/STEP)*101))
port=$((slot%PLEN+PSTART))
ifstatus=$(wg show $WGIF 2> /dev/null)
if [ $? -ne 0 ]; then
echo "$WGIF not up, exiting"
exit
fi
activeport=$(echo $ifstatus | grep "endpoint:" | cut -d':' -f3)
if [ "$activeport" -eq "$port" ]; then
echo "Port unchanged, exiting"
exit
fi
echo "Rotating port for $WGIF: from $activeport to $port"
sed -i "s_\(Endpoint.\+:\)[[:digit:]]\+_\1${port}_" $CONFFILE
wg-quick down $WGIF > /dev/null 2>&1 && wg-quick up $WGIF > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Done"
else
echo "Failed to bring up interface"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment