linux实现内网穿透8

内网机上执行:
ssh -o ServerAliveInterval=60 -f -N -R 9090:192.168.0.154:22 [email protected]
这句代码的意思是让公网机的9090端口能够监听到内网机的22端口,这样我们就能通过访问公网机的9090端口直接登录内网机器。
ServerAliveInterval=60 防止连接不稳定,这里设置每60秒发送一次数据包
这样我们就能连接通过外网机登录内网机器了

ssh -o ServerAliveInterval=60 -f -N -R 9090:192.168.1.98:22 [email protected]

ssh -o ServerAliveInterval=60 -f -N -R 9090:192.168.1.158:22 [email protected]

公网机上输入 curl http://127.0.0.1:9090, 看到下面这串回复说明ssh已经通了:
root@111-230-245-63:~# curl http://127.0.0.1:9090
SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.4
Protocol mismatch.

公网机上输入: ssh [email protected] -p9090 在键入密码就可以登录到内网机

但是这里还有个问题就是ssh只能连接到外网机的本机回路地址127.0.0.1上,
我们还无法通过外网ip 1.1.1.1来连接内网机。所以这里还要做如下配置:
外网机输入:iptables -t nat -A PREROUTING -p tcp --dport 9090 -j DNAT --to-destination 127.0.0.1:9090
这句代码的意思是访问9090端口的请求都转发到回路地址127.0.0.1:9090这个地址上.
iptables -t nat -A PREROUTING -p tcp --dport 9090 -j DNAT --to-destination 127.0.0.1:9090

Linux系统出于安全考虑,是不允许将请求转发至127.0.0.1这个回环地址上的,所以我们还需要修改内核参数。
sysctl -w net.ipv4.conf.eth0.route_localnet=1
到此我们所有配置完成.

输入: curl http://1.1.1.1:9090
出如下,就成功了:
SSH-2.0-OpenSSH_7.4
Protocol mismatch.

在做最终的测试,任意选择一台机器(ssh 正常使用)
命令行输入:·ssh [email protected] -p9090
[email protected]'s password: 注意这里是内网机的密码,不是外网机的密码。