使用SSH 远程转发 访问内网香蕉派

in #ssh6 years ago

之前使用SSH 动态转发实现了SOCKS5代理功能让Telegram X可以正常使用(现在用不到了),使用SSH本地转发实现了我bitshares witness_node 在多个IP及端口提供服务

一般说到SSH转发,总是提到动态转发(-D)、本地转发(-L)以及远程转发(-R),既然已经用到了两个转发,不试试最后一个颇有些厚此薄彼的意味。

需求

但是要试试总得编造出来一个需求啊,不然文章显得多水,我想了想,我有时候需要在外网访问家里的香蕉派,这该算是一个说得过去的需求吧?

其实,外网访问内网我觉得最方便的方法还是DDNS+NAT,以往我放家里的MQTT服务器、Apache服务器都是这么搞的,方便快捷好用,用同样的方法访问SSH也没啥问题。但是如果我用DDNS+NAT不就没SSH转发啥事了嘛,所以我姑且装作不知道DDNS+NAT的方法。

如何转发

man 手册中关于-R选项的部分介绍如下:

-R [bind_address:]port:host:hostport

Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the local side. This works by allocating a socket to listen to port on the remote side, and whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the local machine.

那么按照这个说明,我们的指令应该是这个样子:
ssh -f -N -R vps_ip:7890:localhost:22 user@vps_ip

-f -N啥的说过好多次啦,就不浪费篇幅了。

这个指令大致意思就是建立起来vps_ip 7890端口到我内网机器(香蕉派) 22端口的转发。也就是说如果我用putty之类的工具登陆vps_ip 7890端口,登陆的是我内网香蕉派的SSH服务。

测试了一下,果断被拒:

ssh -p 7890 localhost
但是如果从vps_ip机器上直接登陆则一切正常,也就是说有那么一点点问题。

问题所在

虽然我们达成了之前的目的,可以从外网访问内网香蕉派了,但是有点点瑕疵。我们需要先登陆vps_ip的机器,在SSH到内网香蕉派,也就是多费了一遍劲

对于我这种懒人来讲,这是不可接受的,于是我就调查了一下问题在哪里?再来仔细看看-R选项的内容,第三段说明如下:

-R [bind_address:]port:host:hostport

By default, the listening socket on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address ‘*’, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)).

也就是说,远端机器上默认只监听 loopback interface,如果需要监听所有地址,那么需要指定 bind_address或者*啥的,同时需要开启远端机器上SSHD的GatewayPorts 选项

解决方法

好吧,开启GatewayPorts 选项应该能解决问题,但是呢,我不喜欢去动服务程序的配置,除非我非常了解对应选项。那除此之外有没有其它方法呢?

还记得我们之前学习的本地转发吗?做一下转发不就OK了吗?
ssh -f -N -L vps_ip:1234:localhost:7890 user@localhost
也就是说访问vps_ip 1234端口的数据,会自动转发的localhost的7890端口

完整的数据链条如下:
vps_ip:1234<==>localhost(vps):7890<==>内网香蕉派:22


成功登陆!

总结 & 其它

尽管我通过转发实现了外网访问内网SSH,但是我觉得还是NAT+DDNS更好,为啥呢?方便、快捷、好用嘛!另外我也不知道SSH建立的转发会不会被踢掉线啊?不过不用担忧过多,反正我就是为了测试远程转发嘛。

不过SSH转发还真好玩啊,转来转去的,嗯,我已经被转迷糊了。

相关文章

Sort:  

我去年捣鼓过一个树莓派,是将树莓派转发到一个VPS上,然后再远程访问这个VPS上,好像是配合autossh 一块使用的

其实我就是试一下转发
实际用DDNS+NAT,超好用,超稳定
😄

高科技 high-tech,难搞

Excellent post........thanks for sharing

wow great post nice writting. i like this sir.........../////////

Well what is this peace of hardware ??

The machine what it is

学习了。很棒的高科技。

NAT+DDNS方法是不是搭建一个Ngrok服务?
期待你介绍一下方便、快捷、好用的NAT+DDNS方法。

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 69824.27
ETH 3761.57
USDT 1.00
SBD 3.81