# SSH Tunneling 简明教程：本地调试及多场景下的应用


![linux-ssh-tunneling.png](https://img.lixueduan.com/linux/cover/linux-ssh-tunneling.png)

本章主要介绍了什么是 SSH Tunneling 以及如何使用 SSH Tunneling，包括本地、远程、动态端口转发三种类型，通过原理阐述、参数解读及大量实战命令示例，分享 SSH Tunneling 技术在不同场景下的运用 。

<!--more-->

## TL;DR

常用命令如下：

**本地端口转发 (Local Port Forwarding)：将本地端口映射到远程服务器，用于在本地访问远程服务。**

```bash
# Usage: ssh -N  -L [bind_address:]port:host:hostport user@ssh_server
# 基本使用
ssh -N  -L localhost:8080:localhost:8080 root@192.168.95.145
# 网关模式
ssh -N -g -L 8080:localhost:8080 root@192.168.95.145
# 多级跳转
ssh -N  -L localhost:8080:192.168.10.227:8080 root@172.20.150.0
```

**远程端口转发 (Remote Port Forwarding)：将远程端口映射到本地，用于在远程访问本地服务。**

```bash
# Usage: ssh -N  -R [bind_address:]port:host:hostport user@ssh_server

# 基本使用
ssh -N  -R localhost:9443:localhost:9443 root@192.168.95.145
# 多级跳转
ssh -N  -R 0.0.0.0:9443:localhost:9443 root@172.20.150.0
# 自动端口分配
ssh -N -R :0:localhost:8080 user@remote_server
```



**动态端口转发(SOCKS 代理)**：将远程服务器作为代理服务。

```bash
# Usage: ssh -N -D 10080 user@ssh_server
ssh -N -D 10080 root@172.20.150.0
# 使用代理
curl --socks5 127.0.0.1:1080 www.google.com
```



## 1. 什么是 SSH Tunneling

**SSH Tunneling 是 SSH 中的一种机制**，它能够将其他 TCP 端口的网络数据通过 SSH 连接来转发，并且自动提供了相应的加密及解密服务。因为 SSH 为其他 TCP 链接提供了一个安全的通道来进行传输，因此这一过程也被叫做“隧道”（tunneling）。



&#x20;SSH 隧道能够提供两大功能：&#x20;

* 1）加密 SSH Client 端至 SSH Server 端之间的通讯数据。

* 2）突破防火墙的限制完成一些之前无法建立的 TCP 连接。



SSH 隧道的三种类型：

1. **本地端口转发（Local Port Forwarding）**: 将本地端口的流量通过 SSH 隧道转发到 SSH 服务器，再由 SSH 服务器转发到目标位置。

2. **远程端口转发（Remote Port Forwarding）**: 将 SSH 服务器端口的流量通过 SSH 隧道转发到本地 SSH 服务，再由本地 SSH 服务转发到目标位置。

3. **动态端口转发（Dynamic Port Forwarding）**: 创建一个本地 SOCKS 代理服务器，应用程序通过配置使用这个SOCKS 代理，流量通过 SSH 隧道转发到远程 SSH 服务器，最终从 SSH 服务器发出去。

相关参数：

* “-L选项”：local，表示使用本地端口转发创建 ssh 隧道

* “-R选项”：remote，表示使用远程端口转发创建 ssh 隧道

* “-D选项”：dynamic，表示使用动态端口转发创建 ssh 隧道

* “-N选项”： 表示创建隧道以后不连接到 sshServer端，通常与”-f”选项连用

* “-f选项”：表示在后台运行ssh隧道，通常与”-N”选项连用

* “-g选项”：表示 ssh 隧道对应的转发端口将监听在主机的所有IP中，不使用”-g选项”时，转发端口默认只监听在主机的本地回环地址中，”-g” 表示开启网关模式，远程端口转发中，无法开启网关功能



## 2. 本地端口转发 (Local Port Forwarding)

**本地端口转发 (Local Port Forwarding) 是一种通过 SSH 隧道将本地特定端口映射到远程服务器特定端口，从而实现本地访问远程服务的技术。**



比如这个需求：远程服务器上存在某个服务，并未对外开放端口，但本地服务需要连接该远程服务进行调试。

环境：

* 远程服务器：192.168.95.145

* 本地：无 IP



### 基础用法

![ssh-local-port-forwarding.png](https://img.lixueduan.com/linux/ssh/ssh-local-port-forwarding.png)

在本地执行以下命令，构建 SSH 隧道，开启本地端口转发

```bash
ssh -N  -L localhost:8080:localhost:8080 root@192.168.95.145
```

该命令使用 SSH 创建一个隧道，并将 **本地端口 8080&#x20;**&#x6620;射到远程主机 `192.168.95.145` 的 808&#x30;**&#x20;端口。**

sshd 进程在本地监听 8080 端口，ssh client 会将本地 8080 端口流量通过 ssh 隧道流入 ssh server(192.168.95.145)，最后 ssh server 根据配置，将流量转发到 localhost:8080(相对 192.168.95.145)

> 即：访问**本地 8080 端口**的流量都会被转发到**远程主机 `192.168.95.145` 的 8080 端口**，从而实现本地访问到远程主机上的服务。



比如可以将本地 6443 端口映射到远程服务器 6443 端口，实现在本地通过 127.0.0.1:6443 即可访问远程集群。



#### 参数含义

* **`-N`**

  * 表示不执行任何远程命令，仅建立隧道。适合只做端口转发的场景。

* **`-L localhost:8080:localhost:8080`**

  * **隧道参数**，格式为：`-L [bind_address:]port:host:hostport`

  * `localhost:8080`: 前者为**本地**监听的地址和端口，对应 bind\_address

  * `localhost:8080`: 后者为**流量转发的目标地址和端口**,对应 `host:hostport`

* **`root@192.168.95.145`**

  * 建立 ssh 隧道的 server

  * `root`：远程服务器的用户名。

  * `192.168.95.145`：远程服务器的 IP 地址。



#### Demo

手动本地执行 ssh 命令，启动隧道

```bash
ssh -N  -L localhost:8080:localhost:8080 root@192.168.95.145
# 部分参数可以省略，下面命令效果一致
# ssh -N  -L 8080:localhost:8080 root@192.168.95.145
```

该命令效果是创建 正向隧道或者说**本地端口转发 (Local Port Forwarding)**，通过 `ssh` 将本地机器的 `8080` 端口与远程机器 `192.168.95.145` 的 `8080` 端口相连。

> ps：本地访问 `http://localhost:8080` 的请求会通过 SSH 隧道转发到远程机器 `192.168.95.145` 的 `localhost:8080`



执行后查看本地端口情况

```bash
❯ lsof -i :8080
COMMAND     PID      USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME             
ssh        4651 lixueduan    5u  IPv6 0xc9fa470eb5906a19      0t0  TCP localhost:http-alt (LISTEN)
```

可以看到，8080 端口被 ssh 进程占用了，开始监听。



到远程主机启动服务，监听 8080 端口

```bash
python3 -m http.server 8080
```

本地访问

```bash
❯ curl localhost:8080
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>
```

至此，说明 SSH 隧道可以正常使用了。



### 网关模式

建立 SSH 隧道，开启本地端口转发时，我们执行以下命令，根据 `bind_address` 参数不同，会监听不同地址。

例如：不指定，或者指定 localhost 则只会监听 127.0.0.1。

```bash
ssh -N  -L 8080:localhost:8080 root@192.168.95.145
ssh -N  -L localhost:8080:localhost:8080 root@192.168.95.145
```

&#x20;就像这样：

```bash
$ ss -tunlp|grep 8088
tcp    LISTEN     0      128    127.0.0.1:8088                  *:*                   users:(("ssh",pid=28082,fd=5))
tcp    LISTEN     0      128       [::1]:8088               [::]:*                   users:(("ssh",pid=28082,fd=4))
```

当然也可以指定 IP

```bash
ssh -N  -L 192.168.95.145:8080:localhost:8080 root@192.168.95.145
```

这样会监听指定IP

```bash
$ ss -tunlp|grep 8080
tcp    LISTEN     0      128    192.168.95.145:8080                  *:*                   users:(("ssh",pid=28097,fd=4))
```

或者直接开启网关模式

```bash
ssh -N -g -L 8080:localhost:8080 root@192.168.95.145
```

这样会监听 0.0.0.0

```bash
[root@kc-test-1 ~]# ss -tunlp|grep 8088
tcp    LISTEN     0      128       *:8088                  *:*                   users:(("ssh",pid=28112,fd=4))
tcp    LISTEN     0      128    [::]:8088               [::]:*                   users:(("ssh",pid=28112,fd=5))
```



### 多级跳转

**本地端口转发，除了直连之外还有多级跳转方式，当目标服务器处于内网且无法直接访问时，可通过跳板机实现转发。**

![ssh-local-port-forwarding-jump.png](https://img.lixueduan.com/linux/ssh/ssh-local-port-forwarding-jump.png)



之前基础用法中，ssh server 和 target server 是同一节点，例如：

```bash
# 本地监听 localhost:8080(前者)，通过 192.168.95.145 转发到 localhost:8080(后者)
ssh -N  -L localhost:8080:localhost:8080 root@192.168.95.145
```

但实际上二者可以是不同节点，例如：

```bash
# 本地监听 localhost:8080(前者)，172.20.150.0 转发到 192.168.95.145:8080
ssh -N  -L localhost:8080:192.168.10.227:8080 root@172.20.150.0
```

通过和 jump server(172.20.150.0) 建立 SSH 隧道，将流量转发到 target server(192.168.95.145) 节点。



也就是，只要和 ssh server 建立 ssh 隧道后，可以将流量转发到任意 ssh server 可以访问的地方。



#### Demo

本地开启 ssh 隧道

```bash
ssh -N  -L localhost:8080:192.168.95.145:8080 root@172.20.150.0
```

执行后查看本地端口情况

```bash
❯ lsof -i :8080
COMMAND     PID      USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME             
ssh        4651 lixueduan    5u  IPv6 0xc9fa470eb5906a19      0t0  TCP localhost:http-alt (LISTEN)
```

可以看到，8080 端口被 ssh 进程占用了，开始监听。



到远程主机()启动服务，监听 8080 端口

```bash
python3 -m http.server 8080
```

本地访问

```bash
❯ curl localhost:8080
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>
```

至此，说明 SSH 隧道可以正常使用了。



## 3. 远程端口转发 (Remote Port Forwarding)

**远程端口转发 (Remote Port Forwarding) 是一种通过 SSH 隧道将远程主机上的特定端口映射到本地主机的端口的技术。**



### 基础用法

比如这个需求：远程服务器上存在某个组件，希望能够访问本地环境的服务，以实现本地调试。

![ssh-remote-port-forwarding.png](https://img.lixueduan.com/linux/ssh/ssh-remote-port-forwarding.png)



环境：

* 远程服务器：192.168.95.145

* 本地：无 IP



在本地执行以下命令，构建 SSH 隧道，开启远程端口转发

```bash
ssh -N  -R localhost:9443:localhost:9443 root@192.168.95.145
```

该命令使用 SSH 创建隧道，将 远程主机 **`192.168.95.145` 9443 端口**映射到**本地 9443 端口。**

> 即：任何在 `192.168.95.145` 上访问 `localhost:9443` 的流量都会被转发到本地 9443，最终访问到本地服务，实现本地调试。



比如将 Webhook 在本地启动，通过远程端口转发，让远程服务器上的 kube-apiserver 访问到本地启动的 Webhook 服务。



#### 参数含义

* **`-N`**

  * 告诉 SSH 不执行远程命令，仅用于端口转发。

  * 此选项适用于创建隧道的情况，而无需打开远程 Shell。

* `-R localhost:9443:localhost:9443`

  * **反向隧道参数**，格式为 `[bind_address:]port:host:hostport`

  * `localhost:9443`：前者表示远程主机监听的 IP 和端口，对应 `bind_address`, 这部分配置是相对于 ssh server 来说的。

  * `localhost:9443`：后者表示流量转发的目的地址和端口，对应 `host:hostport`，这部分配置是相对于 ssh client 来说的。

* **`root@192.168.95.145`**

  * 表示连接的远程主机地址和使用的用户名。

    * **root**：用于登录远程主机的用户名。

    * **192.168.95.145**：远程主机的 IP 地址。



#### Demo

本地执行 ssh 创建隧道

```bash
ssh -N  -R localhost:9443:localhost:9443 root@192.168.95.145
```

到远程节点查看，sshd 进程已经监听了 9443 端口，如下：

```bash
tcp   LISTEN 0      128         127.0.0.1:9443       0.0.0.0:*    users:(("sshd",pid=679656,fd=5))
tcp   LISTEN 0      128             [::1]:9443          [::]:*    users:(("sshd",pid=679656,fd=3))
```

本地启动 http 服务监听 9443 端口

```bash
python3 -m http.server 9443
```

到远程服务器请求

```bash
$ curl localhost:9443
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
```

能够正常访问，说明 SSH 反向隧道一切正常。



### 多级跳转

同样的，远程端口转发也可以类似操作，当我们无法直连 Target Server 时，也可以借助 Jump Server 进行多级跳转。

![ssh-remote-port-forwarding-jump.png](https://img.lixueduan.com/linux/ssh/ssh-remote-port-forwarding-jump.png)

之前基础用法中，ssh server 和 target server 是同一节点，例如：

```bash
# 远程监听 localhost:8080(前者)，通过 ssh 隧道转发到本地 localhost:8080(后者)
ssh -N  -R localhost:9443:localhost:9443 root@192.168.95.145
```

但实际上二者可以是不同节点，例如：

```bash
# jump server 监听 0.0.0.0:8080,target server 访问 jump server:9443 端口，流量通过 ssh 隧道转发到本地 localhost:9443
ssh -N  -R 0.0.0.0:9443:localhost:9443 root@172.20.150.0
```

通过和 jump server(172.20.150.0) 建立 SSH 隧道，将流量转发到 target server(192.168.95.145) 节点。



可以看到，jump Server 上 sshd 进程已经在监听 9443 端口了，如下：

```bash
[root@jump-server ~]# ss -tunlp|grep 9443
tcp    LISTEN     0      128    127.0.0.1:9443                  *:*                   users:(("sshd",pid=27992,fd=9))
tcp    LISTEN     0      128       [::1]:9443               [::]:*                   users:(("sshd",pid=27992,fd=8))
```

不过是监听的 127.0.0.1:9443,我们希望的是监听 0.0.0.0:9443,这样 target server 才能访问。

为了让 sshd 监听`监听 0.0.0.0:9443`,需要修改 ssh 中的 `GatewayPorts` 配置。



#### GatewayPorts 配置

`GatewayPorts` 控制反向隧道绑定的地址范围：

* **`GatewayPorts no`（默认值）**

  * 反向隧道只绑定到远程主机的 `localhost`（127.0.0.1）。

  * 无法通过远程主机的外网 IP 或其他接口访问。

* **`GatewayPorts yes`**

  * 允许反向隧道绑定到远程主机的所有可用接口（包括外网 IP）。

  * 结果：可以通过远程主机的指定 IP（如 `192.168.95.145`）或 `0.0.0.0` 访问反向隧道。



编辑 SSH 配置文件：

```bash
vi /etc/ssh/sshd_config
```

确保以下配置项设置为 `yes`：

```bash
GatewayPorts yes
```

重启 SSH 服务以应用更改：

```bash
systemctl restart sshd
```



#### Demo

本地开启 ssh 隧道

> Jump Server 以修改 `GatewayPorts` 配置为 yes

```bash
ssh -N  -R 0.0.0.0:9443:localhost:9443 root@172.20.150.0
```

到 jump server 查看端口监听情况：

```bash
[root@jump-server ~]# ss -tunlp|grep 9443
tcp    LISTEN     0      128       *:9443                  *:*                   users:(("sshd",pid=28030,fd=8))
tcp    LISTEN     0      128    [::]:9443               [::]:*                   users:(("sshd",pid=28030,fd=9))
```

Sshd 进程已经在监听 0.0.0.0:9443 了。



本地启动服务

```bash
python3 -m http.server 9443
```

到 target server 尝试访问

```bash
[root@target-server ~]# curl 172.20.150.0:9443
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Directory listing for /</title>
</head>
[root@target-server ~]# curl 192.168.95.144:9443
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Directory listing for /</title>
</head>
```

可以看到，不论通过 jump server 的公网 IP 或者内网 IP 都可以正常访问到本地的服务。





### 自动端口分配

当不确定远程服务器上的可用端口时，可以让 SSH 自动选择一个随机端口,并在连接建立时返回该端口号。

```bash
ssh -N -R :0:localhost:8080 user@remote_server
```

例如：

```bash
$ ssh -N -R :0:localhost:8080 root@192.168.10.227
Allocated port 36077 for remote forward to localhost:8080
```

SSH 自动选择了 36077 端口。



## 4. 动态端口转发(SOCKS 代理)

将本地端口转发为一个 SOCKS 代理，通过它访问目标服务,也就是将 remote\_server 作为代理服务器在使用了。

```bash
# Usage: ssh -N -D 10080 user@ssh_server
ssh -N -D 10080 root@172.20.150.0
```

* **`-N`**

  * 表示不执行任何远程命令，仅建立隧道。适合只做端口转发的场景。

* **`-D 1080`**:

  * 开启动态端口转发。

  * 本地监听 `1080` 端口，作为一个 SOCKS 代理服务。

  * 客户端（例如浏览器或其他应用程序）可以配置使用 `127.0.0.1:1080` 作为 SOCKS 代理，将流量通过该代理转发。

* **`user@remote_server`**:

  * 指定 SSH 登录到的远程服务器。

  * SSH 会加密代理流量，并通过 `remote_server` 发出。



测试一下：

```bash
curl --socks5 127.0.0.1:1080 www.google.com
```



## 5. 小结

常见的 SSH 隧道使用场景：

* 本地端口转发

  * 将本地 6443 端口映射到远程 6443 以实现，在本地通过 127.0.0.1:6443 访问远程 k8s 集群

  * 远程服务器 MySQL 端口未开发，也可以通过本地端口转发方式实现本地连接数据库

* 远程端口转发：

  * 在调试 K8s Operator 时，我们将远程 9443 端口转发到本地 9443，从而实现本地调试 Webhook。

  * 也可以用于将本地服务对外提供访问

* 动态转发：将远程服务器作为 SOCKS 代理服务器使用。



&#x20;常用命令如下：

**本地端口转发 (Local Port Forwarding)：将本地端口映射到远程服务器，用于在本地访问远程服务。**

```bash
# Usage: ssh -N  -L [bind_address:]port:host:hostport user@ssh_server
# 基本使用
ssh -N  -L localhost:8080:localhost:8080 root@192.168.95.145
# 网关模式
ssh -N -g -L 8080:localhost:8080 root@192.168.95.145
# 多级跳转
ssh -N  -L localhost:8080:192.168.10.227:8080 root@172.20.150.0
```

**远程端口转发 (Remote Port Forwarding)：将远程端口映射到本地，用于在远程访问本地服务。**

```bash
# Usage: ssh -N  -R [bind_address:]port:host:hostport user@ssh_server

# 基本使用
ssh -N  -R localhost:9443:localhost:9443 root@192.168.95.145
# 多级跳转
ssh -N  -R 0.0.0.0:9443:localhost:9443 root@172.20.150.0
# 自动端口分配
ssh -N -R :0:localhost:8080 user@remote_server
```

**动态端口转发(SOCKS 代理)**：将远程服务器作为代理服务。

```bash
# Usage: ssh -N -D 10080 user@ssh_server
ssh -N -D 10080 root@172.20.150.0
# 使用代理
curl --socks5 127.0.0.1:1080 www.google.com
```



## 6. 参考

[SSH Tunneling: Examples, Command, Server Config](https://www.ssh.com/academy/ssh/tunneling-example)

[ssh端口转发：ssh隧道](https://www.zsythink.net/archives/2450)





---

> 作者: [意琦行](https://github.com/lixd)  
> URL: https://www.lixueduan.com/posts/linux/07-ssh-tunnel/  

