Skip to content

Instantly share code, notes, and snippets.

@rikka0w0
Created January 22, 2020 18:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rikka0w0/13dd6e0e8916502c2a36c69d6735b43c to your computer and use it in GitHub Desktop.
Save rikka0w0/13dd6e0e8916502c2a36c69d6735b43c 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