Skip to content

Instantly share code, notes, and snippets.

@rikka0w0
Created May 21, 2020 16:12
Show Gist options
  • Save rikka0w0/0191880f32bacf0afe2348c1948dd3f1 to your computer and use it in GitHub Desktop.
Save rikka0w0/0191880f32bacf0afe2348c1948dd3f1 to your computer and use it in GitHub Desktop.
Add/Update iptable forwading rule with hostnames
#!/bin/bash
# Usage:
# Add/Update: ./update_iptables.sh <port_listen> (tcp|udp) <hostname>:<port>
# Delete: ./update_iptables.sh <port_listen> (tcp|udp) :<port>
PortListen=$1
Protocol=$2
HostName=${3%:*}
PortTarget=${3#*:}
echo $HostName
echo $PortTarget
if [ -n "$HostName" ]; then
IPv4=$(ping -c1 $HostName | grep "bytes of data" | cut -d "(" -f2 | cut -d ")" -f1)
echo $IPv4
fi
# Find the command use to add previous rules
REGEX1="\\-A PREROUTING -p $Protocol -m $Protocol --dport $PortListen"
REGEX2="\\-A POSTROUTING -p $Protocol -m $Protocol --dport $PortTarget"
RULE2DEL1=$(iptables -t nat -S | grep "$REGEX1" | head -n 1)
RULE2DEL2=$(iptables -t nat -S | grep "$REGEX2" | head -n 1)
if [ -n "$RULE2DEL1" ]; then
echo 'Found existing rules'
# Replace the -A with -D
RULE2DEL1=${RULE2DEL1/"-A"/"-D"}
RULE2DEL2=${RULE2DEL2/"-A"/"-D"}
# Delete them
iptables -t nat $RULE2DEL1
iptables -t nat $RULE2DEL2
fi
if [ -n "$HostName" ]; then
echo 'Adding new rules'
# Add new rules
iptables -t nat -A PREROUTING -p $Protocol -m $Protocol --dport $PortListen -j DNAT --to-destination $IPv4:$PortTarget
iptables -t nat -A POSTROUTING -p $Protocol -m $Protocol --dport $PortTarget -j MASQUERADE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment