3 SIMPLE SHELL FUNCTIONS TO MANAGE IPTABLES NAT RULES

Add port-forwarding NAT rule:
 


function nat-add() {
  sudo iptables-save > /tmp/iptables.rules

  echo
  read -p "Inbound port: " EXT_PORT
  read -p "Inbound interface: " EXT_INTERFACE
  read -p "IP address: " DST_ADDRESS
  read -p "Destination port: " DST_PORT
  read -p "Protocol (TCP/UDP): " PROTO

  LINE=$(expr $(sed -n '/\-A POSTROUTING \-o ${EXT_INTERFACE} \-j MASQUERADE/=' /tmp/iptables.rules) - 1)  
  sudo sed -i "${LINE}a \-A\ PREROUTING\ \-i\ ${EXT_INTERFACE}\ \-p\ ${PROTO}\ -m\ ${PROTO}\ \-\-dport ${EXT_PORT}\ \-j\ DNAT\ \-\-to\-destination\ ${DST_ADDRESS}\:${DST_PORT}" /tmp/iptables.rules
  
  sudo iptables-restore < /tmp/iptables.rules
  
  if [ $? -eq 0 ]; then
    echo OK
    sudo rm -f /tmp/iptables.rules
  fi
}

 
Delete port-forwarding NAT rule:
 


function nat-delete() {
  RULE=$(sudo iptables -t nat -L --lin |grep ${EXT_PORT} |grep ${PROTO} |tr -s " " |cut -d " " -f1)

  echo
  read -p "Inbound port: " EXT_PORT
  read -p "Protocol (TCP/UDP): " PROTO
  
  sudo iptables -t nat -D PREROUTING ${RULE}

  if [ $? -eq 0 ]; then
    sudo iptables-save > /tmp/iptables.rules
    sudo iptables-restore < /tmp/iptables.rules
    sudo rm -f /tmp/iptables.rules
    echo OK
  fi
}

 
Show current loaded iptables NAT rules:
 


function nat-show () { 
  echo -ne "-----------------------------------------------------------------\n"
  echo -ne "Protocol \t Inbound port \t Destination \t Destination port \n"
    
  sudo iptables -t nat -nL --lin | grep -Ev "Chain|num|^$|MASQUERADE" |tr -s " " |awk -F" " '!_[$1]++' | \
  tr -s " " | cut -d " " -f7,8,9 | tr : " " | cut -d" " -f1,3,5,6 | \
  awk '{ print "-----------------------------------------------------------------\n" $1 "\t\t " $2 "\t\t " $3 "\t " $4 }'
    
  echo -ne "-----------------------------------------------------------------\n"
}

 
Sample output of nat-show():
 


-----------------------------------------------------------------
Protocol         Inbound port    Destination     Destination port
-----------------------------------------------------------------
tcp              23456           10.8.1.20       22
-----------------------------------------------------------------
tcp              5115            176.12.0.221    5000
-----------------------------------------------------------------
udp              53              10.96.30.52     53
-----------------------------------------------------------------