Skip to content

Instantly share code, notes, and snippets.

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 yilmazdurmaz/cf0f05fc906296383be0e999d91b0d10 to your computer and use it in GitHub Desktop.
Save yilmazdurmaz/cf0f05fc906296383be0e999d91b0d10 to your computer and use it in GitHub Desktop.
Add/Update iptable NAT port forward rule based on hostname instead of ip address
#!/bin/bash

HostName=
PortListen=
PortTarget=

IPv4=$(ping -c1 $HostName | grep "bytes of data" | cut -d "(" -f2 | cut -d ")" -f1)
echo $IPv4

# Find the command use to add previous rules
RULE2DEL1=$(iptables -t nat -S | grep '\-A PREROUTING -p tcp -m tcp --dport '$PortListen)
RULE2DEL2=$(iptables -t nat -S | grep '\-A POSTROUTING -p tcp -m tcp --dport '$PortTarget)
# Replace the -A with -D
RULE2DEL1=${RULE2DEL1/"-A"/"-D"}
RULE2DEL2=${RULE2DEL2/"-A"/"-D"}
# Delete them
iptables -t nat $RULE2DEL1
iptables -t nat $RULE2DEL2
# Add new rules
iptables -t nat -A PREROUTING -p tcp -m tcp --dport $PortListen -j DNAT --to-destination $IPv4:$PortTarget
iptables -t nat -A POSTROUTING -p tcp -m tcp --dport $PortTarget -j MASQUERADE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment