# ubuntu系统跳转或透明转发实现的几种方式

非常好的问题 👍  
你现在的需求可以理解为：

> 所有访问 **47.236.101.216:6011** 的流量，都透明地转发（或跳转）到 **47.241.11.4:6011**。

在 Ubuntu 14.04（内核 3.x 时代）下，可以有几种成熟的实现方式，取决于你希望“转发”的层次（L3/L4）与透明度。  
下面我给你推荐几种方案，按推荐优先级从高到低排列👇

---

## ✅ **方案一：使用 iptables DNAT（推荐）**

如果两台服务器在公网都可访问，最简洁、最稳定的方式就是 **iptables DNAT 转发**。

### 1️⃣ 编辑转发规则：

```bash
# 启用IP转发
echo 1 > /proc/sys/net/ipv4/ip_forward
sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

# 清空旧规则（可选）
iptables -t nat -F

# 设置DNAT转发规则：将所有访问本机6011端口的流量转发到另一台服务器
iptables -t nat -A PREROUTING -p tcp --dport 6011 -j DNAT --to-destination 47.241.11.4:6011

# SNAT确保返回流量走回原服务器
iptables -t nat -A POSTROUTING -p tcp -d 47.241.11.4 --dport 6011 -j SNAT --to-source 47.236.101.216

```

### 2️⃣ 保存规则

Ubuntu 14.04 默认没 `iptables-persistent`，可以手动保存：

```bash
apt-get install iptables-persistent -y
service netfilter-persistent save

```

或使用：

```bash
iptables-save > /etc/iptables.rules

```

然后在 `/etc/network/interfaces` 的 `post-up` 中添加：

```bash
post-up iptables-restore < /etc/iptables.rules

```

---

## ✅ **方案二：用 `socat` 实现 TCP 端口中继**

若不想修改系统防火墙（或仅临时转发），`socat` 是轻量好用的方案。

### 1️⃣ 安装

```bash
apt-get install socat -y

```

### 2️⃣ 启动转发

```bash
socat TCP-LISTEN:6011,fork TCP:47.241.11.4:6011

```

这会将所有到 `6011` 的连接直接中继到 `47.241.11.4:6011`。

### 3️⃣ 后台运行（长期服务）

可以写入 `/etc/rc.local`：

```bash
/usr/bin/socat TCP-LISTEN:6011,fork TCP:47.241.11.4:6011 &

```

或者用 `screen` / `nohup`：

```bash
nohup socat TCP-LISTEN:6011,fork TCP:47.241.11.4:6011 >/var/log/socat_6011.log 2>&1 &

```

---

## ✅ **方案三：使用 Nginx TCP 反向代理（更可控）**

如果你已有 Nginx，可以用它转发 TCP 流量。

1️⃣ 安装 stream 模块版本：

```bash
apt-get install nginx-extras -y

```

2️⃣ 编辑 `/etc/nginx/nginx.conf` 增加：

```nginx
stream {
    server {
        listen 6011;
        proxy_pass 47.241.11.4:6011;
    }
}

```

3️⃣ 重新加载配置：

```bash
nginx -t && service nginx restart

```

---

## ⚙️ 对比建议

<table id="bkmrk-%E6%96%B9%E6%A1%88-%E6%80%A7%E8%83%BD-%E6%8C%81%E4%B9%85%E6%80%A7-%E8%B0%83%E8%AF%95%E4%BE%BF%E5%88%A9%E6%80%A7-%E6%8E%A8%E8%8D%90%E5%9C%BA%E6%99%AF"><thead><tr><th>方案</th><th>性能</th><th>持久性</th><th>调试便利性</th><th>推荐场景</th></tr></thead><tbody><tr><td>**iptables DNAT**</td><td>⭐⭐⭐⭐</td><td>永久有效</td><td>略复杂</td><td>系统级透明转发（生产推荐）</td></tr><tr><td>**socat**</td><td>⭐⭐</td><td>临时转发方便</td><td>简单易改</td><td>测试或过渡用</td></tr><tr><td>**nginx stream**</td><td>⭐⭐⭐</td><td>稳定可控</td><td>日志支持好</td><td>若已有 Nginx 环境</td></tr></tbody></table>

---

## 🔍 验证

在另一主机上测试：

```bash
telnet 47.236.101.216 6011

```

或：

```bash
curl http://47.236.101.216:6011

```

然后查看 47.241.11.4 是否收到请求。

---

我建议你优先用 **iptables DNAT**，因为它在内核层转发，性能最好、透明度最高、适合生产服务器。  
如果你告诉我：

- 两台服务器是否在同一内网或仅公网互通，
- 是否需要保持源 IP（即被转发请求的真实来源 IP），

我可以进一步给出优化方案（比如保留原始客户端 IP 的 DNAT + SNAT 精细配置）。

是否希望我帮你写一版完整可执行、带日志与开机自启的 iptables 方案脚本？