📅  最后修改于: 2023-12-03 15:01:26.597000             🧑  作者: Mango
IP tables is a powerful tool to manipulate and filter network traffic on a Linux system. One of the most common uses of IP tables is Destination-NAT, which allows rewriting the destination IP address of incoming packets. This is useful for load balancing or redirecting traffic to a different server.
In this article, we will explore how to set up Destination-NAT using IP tables in Shell-Bash.
Before making any changes, it is advisable to backup the current IP tables rules in case something goes wrong. You can do this by running the following command:
iptables-save > /root/iptables-backup
This will save the current IP tables rules to a file called iptables-backup
in the root directory.
IP forwarding needs to be enabled on the server to allow packets to be forwarded from one network interface to another. You can do this by running the following command:
echo 1 > /proc/sys/net/ipv4/ip_forward
This will enable IP forwarding for the current session. To make it permanent, add the following line to /etc/sysctl.conf
:
net.ipv4.ip_forward = 1
To create a Destination-NAT rule, we need to specify a target IP address and port for the incoming packets. For example, let's say we want to redirect all incoming SSH traffic to a different server with IP address 10.0.0.2
:
iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination 10.0.0.2:22
This command adds a rule to the NAT table (-t nat
) of IP tables, which matches incoming TCP packets with destination port 22
(-p tcp --dport 22
) and redirects them to IP address 10.0.0.2
with port 22
(-j DNAT --to-destination 10.0.0.2:22
).
To make the IP tables rules persistent, you need to save them. You can do this by running the following command:
iptables-save > /etc/iptables.up.rules
This will save the current IP tables rules to a file called iptables.up.rules
in the /etc
directory. To load the rules on boot, add the following line to /etc/rc.local
:
/sbin/iptables-restore < /etc/iptables.up.rules
Destination-NAT is a powerful feature of IP tables that allows redirecting traffic to a different server. In this article, we have explored how to set up Destination-NAT using IP tables in Shell-Bash. Remember to backup the IP tables rules before making any changes, and make the rules persistent by saving them to a file.