基本的 iptables NAT 端口转发

jet*_*boy 11 nat iptables port-forwarding

我有三台机器:一台本地 PC(公共 IP 1.2.3.4)、数据中心中的 Ubuntu 10 服务器盒(5.6.7.8 公共 IP 上的 eth0),以及托管我网络外部网站的第三方服务器(假设216.34.181.45 上的斜杠)。

  • 使用 iptables,如何使用 5.6.7.8:8080 从本地机器访问 Slashdot?
  • 如果 Slashdot 与我的 Ubuntu 机器在同一个 LAN 上,这个过程会有所不同吗?
  • 这可以通过 NAT PREROUTING/POSTROUTING 来完成,还是我需要 MASQUERADE?

qua*_*nta 23

   PC ----- Ubuntu 10 Server ----- Slashdot 
(1.2.3.4)      (5.6.7.8)        (216.34.181.45)
Run Code Online (Sandbox Code Playgroud)
  1. 在 Ubuntu 上启用 IP 转发:

    echo 1 > /proc/sys/net/ipv4/ip_forward
    
    Run Code Online (Sandbox Code Playgroud)

    并添加以下规则:

    iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 8080 -j DNAT \
                                           --to-destination 216.34.181.45:80 
    iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 5.6.7.8
    
    Run Code Online (Sandbox Code Playgroud)
  2. 不。

  3. 如果 Ubuntu 有动态 IP,你应该使用 MASQUERADE:

    iptables -t nat -A POSTROUTING -j MASQUERADE
    
    Run Code Online (Sandbox Code Playgroud)

在这种情况下,您还可以通过在 Ubuntu 上执行以下命令来使用 SSH 本地端口转发:

$ ssh -L 5.6.7.8:8080:216.34.181.45:80 -N user@216.34.181.45
Run Code Online (Sandbox Code Playgroud)

还有另一种(或更多)方法可以做到这一点。看看rinetd

Name       : rinetd
Arch       : i386
Version    : 0.62
Release    : 6.el5.art
Size       : 41 k
Repo       : installed
Summary    : TCP redirection server
URL        : http://www.boutell.com/rinetd
License    : GPL
Description: rinetd is a daemon which redirects TCP connections from one IP address
           : and port to another IP address and port. This daemon is often used to
           : access services behind a firewall.
Run Code Online (Sandbox Code Playgroud)

配置非常简单。将下面的行添加到/etc/rinetd.conf

5.6.7.8 8080 216.34.181.45 80
Run Code Online (Sandbox Code Playgroud)

并开始:

# /etc/init.d/rinetd start
Starting rinetd:                                           [  OK  ]
Run Code Online (Sandbox Code Playgroud)

它会为你做一切。