Iptables: forward request on different interfaces

2020-05-24 06:33发布

问题:

I have a machine with 2 interfaces:

eth0      inet addr:1.1.1.1
eth1      inet addr:2.2.2.2

eth0 is a server, eth1 is the network on virtual machine.

I have ssh on server, so 1.1.1.1:22 is busy.

I need a rule for redirecting incoming connections on eth0 port 6000 to eth1, ip 2.2.2.100 on port 22 (virtual machine ip).

In this mode if I did, on an external machine,

ssh -p 6000 root@1.1.1.1

I would login on the virtual machine.

I tried this rule but it didn't work:

sudo iptables -P FORWARD ACCEPT
sudo iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 6000 -j DNAT --to 2.2.2.100:22

回答1:

Well there are like 1 million scripts/tutorials/things for this case, but if someone lands from google to here is something like this:

iptables -I FORWARD -d 2.2.2.2 -m comment --comment "Accept to forward ssh traffic" -m tcp -p tcp --dport 22 -j ACCEPT    
iptables -I FORWARD -m comment --comment "Accept to forward ssh return traffic" -s 2.2.2.2 -m tcp -p tcp --sport 22 -j ACCEPT    
iptables -t nat -I PREROUTING -m tcp -p tcp --dport 60000 -m comment --comment "redirect pkts to virtual machine" -j DNAT --to-destination 2.2.2.2:22   
iptables -t nat -I POSTROUTING -m comment --comment "NAT the src ip" -d 2.2.2.2 -o eth1 -j MASQUERADE