Created
November 8, 2020 02:22
-
-
Save cmer/4f33f29f15a58e30b8f22e5366b8b5b1 to your computer and use it in GitHub Desktop.
Script to port-forward to a dynamic IP address. Run in CRON.
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
#!/bin/bash | |
HOST=myhost.example.com | |
IP=`dig +short $HOST | sed -e '1d'` | |
LAST_IP_FILE=/tmp/LAST_IP | |
LAST_IP=`cat $LAST_IP_FILE 2> /dev/null` | |
tcpPorts=(8080 8880 8843 8443) | |
udpPorts=(3478 10001) | |
if [ ! "$IP" = "$LAST_IP" ] ; then | |
echo "IP changed. Updating iptables..." | |
# Clear previous rules | |
iptables -t nat --flush POSTROUTING | |
iptables -t nat --flush PREROUTING | |
# Enable IP forwarding | |
sysctl net.ipv4.ip_forward=1 | |
echo $IP > $LAST_IP_FILE | |
for p in ${tcpPorts[@]}; do | |
echo "TCP:$p" | |
iptables -t nat -A PREROUTING -p tcp --dport $p -j DNAT --to-destination $IP:$p | |
done | |
for p in ${udpPorts[@]}; do | |
echo "UDP:$p" | |
iptables -t nat -A PREROUTING -p udp --dport $p -j DNAT --to-destination $IP:$p | |
done | |
iptables -t nat -A POSTROUTING -j MASQUERADE | |
echo "Done!" | |
else | |
echo "IP hasn't changed. Skip." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment