0%

SSH端口转发

本地转发

1
2
3
4
ssh -L [bind_address:]port:host:hostport destination
ssh -L [bind_address:]port:remote_socket destination
ssh -L local_socket:host:hostport destination
ssh -L local_socket:remote_socket destination

将本地(客户端)主机上的给定 TCP 端口或 Unix Socket 转发到远程端的给定主机和端口或 Unix Socket.

例如, 服务器8080端口运行私有服务, 可以将本地8081端口转发给服务器8080端口:

1
ssh -N -L 8081:localhost:8080 user@host

即可通过访问localhost:8081来访问host:8080, 其中-N参数表示不进入交互式Shell.

假设有一内网服务器仅支持内外访问, 且没有运行ssh服务, 这时可以通过转发到另一台开启ssh服务的内网主机来访问:

1
ssh -N -L 8081:host1:8080 user@host2

即可通过访问localhost:8081来访问host1:8080, 其中host2为开启ssh服务的另一台主机.

以上命令皆省略了bind address, 默认绑定0.0.0.0, 也就是所有网络接口; 安全起见可以指明bind address明确访问范围:

1
2
3
ssh -N -L localhost:8080:host1:8080 user@host2    // 仅可通过localhost访问
ssh -N -L 192.168.1.1:8080:host1:8080 user@host2 // 监听当前内网ip, 仅可通过内网访问
...

远程转发

1
2
3
4
5
ssh -N -R [bind_address:]port:host:hostport destination
ssh -N -R [bind_address:]port:local_socket destination
ssh -N -R remote_socket:host:hostport destination
ssh -N -R remote_socket:local_socket destination
ssh -N -R [bind_address:]port destination

将远程(服务器)主机上的给定 TCP 端口或 Unix Socket 转发到本地.

假设本地8080端口运行私有服务, 将host上的8081端口转发给本地8080:

1
ssh -R 8081:localhost:8080 user@host

即可通过访问host:8081来访问localhost:8080, 这可以用来实现内网穿透.

类似地, 这里省略了bind address, 所以可以通过所以网络接口访问host该转发, 安全起见应指明bind address.

动态转发

1
ssh -N -D [bind_address:]port destination

这会启动一个SOCKS代理服务器, 例如

1
ssh -N -D 1080 user@host

启动SOCKS服务, 监听1080端口, 那么将SOCKS代理指定为localhost:1080, 会将流量转发到host, 由host发出, 例如

1
curl -x socks5://localhost:1080 https://www.google.com

该请求会被host代理.