IPTABLES ip forward and port forward dynamic script nat rules By ElectroMech Nilesh Vaghela
This will forward the port which satisfy following conditions.
1. The incomming address is fix
2. Incomming and outgoing port is fixed.
#-- start up the script
#!/bin/bash
#To forward the port 9666 from LIVE_IP to lan ip PLC_IP with security.
#If you made any changes please inform electromech@electromech.info
start ()
{
LIVE_IP_LOCAL="20.18.228.77"
LOCAL_IP_PLC1="200.0.0.158"
LIVE_IP_GUEST="22.24.97.11"
PORT_TO_FORWARD="9600"
PORT_AT_FIREWALL="10001"
IPT=/sbin/iptables
echo " Applying firewall forwarding rule .........."
#First need to accept packets for fixed port at firewall
$IPT -A INPUT -s $LIVE_IP_GUEST -d $LIVE_IP_LOCAL -p tcp --dport $PORT_AT_FIREWALL -m state --state NEW -j ACCEPT
$IPT -A INPUT -s $LIVE_IP_GUEST -d $LIVE_IP_LOCAL -p udp --dport $PORT_AT_FIREWALL -m state --state NEW -j ACCEPT
# This is actual rule to forward the port hence established the connection.
$IPT -t nat -A PREROUTING -s $LIVE_IP_GUEST -d $LIVE_IP_LOCAL -p tcp --dport $PORT_AT_FIREWALL -j DNAT --to-destination $LOCAL_IP_PLC1:$PORT_TO_FORWARD
$IPT -t nat -A PREROUTING -s $LIVE_IP_GUEST -d $LIVE_IP_LOCAL -p udp --dport $PORT_AT_FIREWALL -j DNAT --to-destination $LOCAL_IP_PLC1:$PORT_TO_FORWARD
echo " "
echo " "
echo "Rule applied ."
}
stop ()
{
RULENUM=$(iptables -t nat -vL -n --line-number | awk -F" " '/10001/ {print $1}' |tail -n 1)
#echo "$RULENUM"
echo "The rule is going to stop and number in iptables is $RULENUM"
iptables -t nat -D PREROUTING $RULENUM
}
case $1 in
start) start
;;
stop) stop
;;
*) echo "Please use plc.sh start/stop "
esac
#---------end of the script
By ElectroMech Nilesh J. Vaghela