外网ssh到内网

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/crazyman2010/article/details/79837118

很多时候我们需要从外网ssh连接到内网服务器,进行一些操作,ssh可以很方便地实现这一点,我遇到了几个问题,写此文记录之。
首先在网上查找到转发命令是这样的:

ssh -gR <remote_port>:<local_host>:<local_port> <remote_host>

这条命令的作用是把远程机器上某个端口的流量转发到本地端口。

知道这一点之后,开始实战,公司的服务器是阿里云,内网服务器在公司。
1.在内网服务器上创建一个用户:

useradd test001 -s /bin/bash
echo test001:123456 | chpasswd 

2.将外网服务器Rserver上端口11122的流量转发到本地22端口

ssh -gR 11122:localhost:22 Ruser@Rserver

执行成功,在远程服务器sever上查看端口监听情况:netstat -tln, 可以看到端口正在监听。

3.测试:

# 注意,这里我们用内网用户test001登录
ssh -p 11122 test001@Rserver

然后。。。就卡在那里了 :(
哪里出问题了呢?
因为是阿里云,所以我首先检查了阿里云的安全规则,在公网入方向增加任意地址可访问11122端口规则,然后再试。。。结果还是卡在那里,没有任何结果返回。
然后检查服务器上防火墙ufw status,结果显示inactive,没开,排除防火墙。
还有什么会拦截端口访问又不回应消息呢,嗯,还有iptables。
使用iptables -L查看规则,默认INPUT策略是DROP,OUTPUT策略是ACCEPT,所以需要增加一条规则

iptables -A INPUT -p tcp --dport 11122 -j ACCEPT
iptables-save

再次测试,终于有反应,nice!

$ ssh test001@Rserver -p 11122 -v
OpenSSH_5.9p1 Debian-5ubuntu1.10, OpenSSL 1.0.1 14 Mar 2012
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to Rserver [x.x.x.x] port 11122.
debug1: connect to address x.x.x.x port 11122: Connection refused
ssh: connect to host Rserver port 11122: Connection refused

好吧,虽然有反应了,但还是不行,看信息是被拒绝了。
有点郁闷啊,慢慢检查,首先看一下sshd_config,没有什么问题,然后在内网另外一台服务器上测试了一次,没有任何问题,说明问题还是在外网这台服务器上。
折腾折腾,发现一个现像:

# 在Rserver上执行
ssh -p 11122 test001@Rserver  # 被拒绝
ssh -p 11122 test001@localhost # 登录成功

说明外部地址被拒绝了,内部地址被放行。
仔细检查端口的监听情况,对比内网另外一台没问题的服务器,发现netstat -tln结果中Local Address有区别:
内网服务器: :::11122
外网服务器: localhost:11122
也就是在外网服务器,11122只在localhost上监听,难怪拒绝外部请求了。
接下来就是怎么让ssh绑定11122到任意地址了,百度之google之,man之:

#这条转发命令的选项是这样的
-R [bind_address:]port:host:hostport

By default, TCP listening sockets 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)).

默认情况下,tcp监听仅被绑定到loopback网口。这个行为会被bind_address参数修改,给bind_address设置空或者*,会将tcp监听绑定到所有网口。注意只有服务器ssh_config中GatewayPorts打开时,bind_address才有效。

根据上面的描述,在服务端增加配置

vi /etc/sshd_config
#在最后台增加
GatewayPorts yes

修改ssh脚本

ssh -gR :11122:localhost:22 Ruser@Rserver
#或者
ssh -gR \*:11122:localhost:22 Ruser@Rserver

然后再次测试,终于登录上了!

综合保持连接等修改,最终反向连接脚本如下:

autossh -M 0  -fNR \*:11122:localhost:22 Ruser@Rserver

猜你喜欢

转载自blog.csdn.net/crazyman2010/article/details/79837118