Files
Hugo/content/blog/ssh-tunnel-guide.md
T

58 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "SSH 隧道实用指南"
date: 2026-05-09T14:00:00+08:00
draft: false
poet: |
山重水复疑无路,
柳暗花明又一村。
——陆游,中国,1125–1210
description: "本地端口转发、远程端口转发、动态端口转发三种模式的实际应用场景。从绕过防火墙访问内网服务,到把本地开发环境暴露给公网调试。"
tags:
- SSH
- 网络
- 教程
---
SSH 隧道是开发者的必备技能,但很多人只用过最基本的 `ssh user@host`。三种端口转发模式记清楚了,日常开发基本够用。
## 本地端口转发(-L)
把远程内网的服务映射到本机。
```bash
ssh -L 3306:db.internal:3306 jump-host
```
这条命令让本地的 `localhost:3306` 流量通过跳板机转发到内网的数据库服务器。典型场景:你在家开发,公司的数据库只在内网可访问。连上跳板机后,`mysql -h 127.0.0.1 -P 3306` 就能直接操作数据库。
## 远程端口转发(-R)
反过来,把本地端口暴露给远程服务器。
```bash
ssh -R 8080:localhost:3000 public-server
```
这个场景适合调试 webhook:你在本地起了服务,第三方服务需要回调你的端点。把本地的 3000 端口映射到公网服务器的 8080,webhook URL 填 `http://public-server:8080` 就能收到回调。
记得在 remote 服务器上设置 `GatewayPorts yes` 才能让外部访问。
## 动态端口转发(-D)
临时搭建 SOCKS 代理。
```bash
ssh -D 1080 jump-host
```
然后浏览器或系统代理设置为 `socks5://localhost:1080`,流量就全走跳板机出去了。配合 SwitchyOmega 这类浏览器扩展,按域名自动切换代理规则,体验更好。
## 实用技巧
- 加 `-N` 不执行远程命令,纯隧道。
- 加 `-f` 后台运行。
- 加 `-C` 压缩传输,慢网络下有用。
- 用 `~/.ssh/config` 给常用隧道起别名,避免每次敲长命令。
三种模式记清楚,SSH 隧道基本够用。