ssh端口转发

缘由

社团里面采购了一台服务器,设备放在校园网内网里面,由于校园网对外网没有开放端口,所以无法从外网连接,所以我要做一个端口转发,将内网的端口映射到外网的服务器上,这里自然使用的是反向代理,要从内网向外网连接,建立端口映射。

ssh端口转发

ssh端口转发有本地转发、远程转发、动态转发等

1.本地转发

1
ssh -L <local port>:<remote host>:<remote port> <SSH hostname>

这条命令在ssh_client上运行

其中ssh_server = <.SSH hostname>

TCP连接方向 ssh_client:local_port –> ssh_client:22 –> ssh_server:22 –> remote_host:port

remote_host:remote_port 相对于 <.SSH hostname>

local port 相对于ssh_client

2.远程转发

1
ssh -R <remote port>:<remote host>:<local port> <SSH hostname>

执行命令的是ssh_client

ssh_server = <.SSH hostname>

remote_host:remote_port 相对于 <.SSH hostname>

local_port 相对于ssh_client

3.动态转发

1
ssh -D <local port> <SSH Server>

4.多主机转发

1
ssh -g -L 7001:<B>:389 <D>

本次实现

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/expect
spawn ssh -CfnNTq -D 12306 localhost
expect "password:"
send "toor\r"
expect eof
spawn ssh -CfnNTq -R *:1034:localhost:12306 user@123.206.211.64
expect "password:"
send "pwd\r"
expect eof

首先在内网建立一个动态转发,本地端口为12306;

然后内网服务器和外网之间建立一个远程转发,把内网的本地12306端口映射到远程服务器的1034端口,‘*:’表示任意地址可以访问外网服务器的1034端口。这个选项的使用要在外网服务器中的/etc/ssh/sshd_config中的GatewayPorts关键字设置为yes。

然后其他电脑把外网服务器的1034端口作为sock5代理即可连接内网。

参考
https://www.ibm.com/developerworks/cn/linux/l-cn-sshforward/index.html
http://lvii.github.io/system/2013/10/08/ssh-remote-port-forwarding/