IPTABLES NAT by using a simple shell script

IPTABLES NAT by using a simple shell script.

The simple shell script to write the NAT rule to allow internet access to the local network.

With this guide we are going to show you how to write shell script for iptables NAT.

In the guide we are using below configuration .

 

Operating System : Centos 6.4

eth0 : Public access, 192.168.1.246
Default GW : 192.168.1.253
DNS : 8.8.8.8

eth1 : private network(LAN) : 172.16.1.1
Default GW : N/A

 

The inside network (LAN) uses 172.16.1.1 as gateway. The local network range 172.16.1.0/24.

[root@Firewall ~]# ifconfig

eth0 Link encap:Ethernet HWaddr 08:00:27:7E:AD:1F
 inet addr:192.168.1.246 Bcast:192.168.1.255 Mask:255.255.254.0
 inet6 addr: fe80::a00:27ff:fe7e:ad1f/64 Scope:Link
 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
 RX packets:33883 errors:0 dropped:0 overruns:0 frame:0
 TX packets:15307 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:30952614 (29.5 MiB) TX bytes:1323308 (1.2 MiB)
eth1 Link encap:Ethernet HWaddr 08:00:27:9D:69:68
 inet addr:172.16.1.1 Bcast:172.16.1.255 Mask:255.255.255.0
 inet6 addr: fe80::a00:27ff:fe9d:6968/64 Scope:Link
 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
 RX packets:26317 errors:0 dropped:0 overruns:0 frame:0
 TX packets:25664 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:2323478 (2.2 MiB) TX bytes:30181897 (28.7 MiB)
lo Link encap:Local Loopback
 inet addr:127.0.0.1 Mask:255.0.0.0
 inet6 addr: ::1/128 Scope:Host
 UP LOOPBACK RUNNING MTU:16436 Metric:1
 RX packets:0 errors:0 dropped:0 overruns:0 frame:0
 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:0
 RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

Create a shell script to define IPTABLES NAT rules.

#vi /root/nat.sh

#Public IP provided by ISP.
publicip="192.168.1.246"
#Private IP from the local LAN series. 
privateip="172.168.1.1"
#LAN subnet
lan="172.16.1.0/24"
#Flush existing chains (input, output & forward) 
iptables -F
#Flush the NAT table 
iptables -F -t nat
#By default it's accepted , in case default policy set to drop #then 
iptables -P FORWARD ACCEPT
#Add this line to allow forwarding from eth1 to eth0 
echo "1" > /proc/sys/net/ipv4/ip_forward # enable IP forwarding
# inside to outside NAT.
iptables -t nat -A POSTROUTING -s $lan -j SNAT --to $publicip

Save & Exit!

Note:
$ = to print the value of variable assign on top of the script (Ex: publicip=”192.168.1.246″)

Make the script executable
#chmod 755 nat.sh

Run the script
#./nat.sh

or

#sh nat.sh

Set it to auto start at system reboot.
#vi /etc/rc.d/rc.local

/root/nat.sh

Save & Exit!
Go to Client PC and set the gateway IP to privateip=”172.168.1.1″.

Both comments and pings are currently closed.

Comments are closed.

Copyright ©Solutions@Experts.com
Copyright © NewWpThemes Techmark Solutions - www.techmarksolutions.co.uk