ssh tunnel

通过 SSH 建立加密隧道进行端口转发,安全访问远程网络中的服务

语法

ssh -L|-R|-D [bind_address:]port:host:hostport [user@]hostname

参数

参数说明示例级别
-L 本地端口转发(本地→远程) ssh -L 8080:localhost:80 user@host 常用
-R 远程端口转发(远程→本地) ssh -R 9090:localhost:3000 user@host 常用
-D 动态端口转发(SOCKS 代理) ssh -D 1080 user@host 常用
-N 不执行远程命令,仅建立隧道 ssh -N -L 8080:localhost:80 user@host 常用
-f 后台运行 ssh -fN -L 8080:localhost:80 user@host 进阶
-g 允许其他主机连接转发端口 ssh -g -L 8080:localhost:80 user@host 进阶

示例

本地转发访问远程数据库

ssh -N -L 3307:localhost:3306 user@db-server
本地 3307 端口映射到远程 MySQL 3306,用 mysql -h 127.0.0.1 -P 3307 连接

动态转发作为 SOCKS 代理

ssh -D 1080 -N user@proxy-server
浏览器设置 SOCKS5 代理 127.0.0.1:1080 即可通过远程服务器上网

远程转发暴露本地服务

ssh -R 8080:localhost:3000 user@public-server
外网通过 public-server:8080 访问你本地的 3000 端口服务

后台建立隧道

ssh -fN -L 5433:db-internal:5432 user@bastion
-f 后台运行,-N 不开 shell,适合长期隧道

常见错误

bind: Address already in use 本地端口已被占用,换一个端口或用 lsof -i :端口 查看占用进程
channel 0: open failed: connect failed: Connection refused 隧道远端的目标服务未运行,检查目标主机和端口是否正确

技巧

相关命令