参考:https://blog.youkuaiyun.com/beeworkshop/article/details/116838106
前提条件:需要中转服务器,比如租一个阿里云服务器。内网服务器能够联网。
作用机制(可以不看):利用Autossh,内网服务器建立对中转服务器2202的端口映射,即其它PC发往中转服务器2202端口的数据自动转发到内网服务器。
1:打开Server1(中转服务器)的2202端口,如果是阿里云服务器,安全组规则里面打开2202端口。
2:如果Server2(内网服务器)是新的,可能需要安装openssh-server,让别人可以远程连接你。
sudo apt-get install openssh-server
3:Server1(中转服务器)的配置步骤
[root@Server1 ~]# vim /etc/ssh/sshd_config
GatewayPorts yes
[root@Server1 ~]# systemctl restart sshd
4:Server2(内网服务器)的配置步骤
# 安装autossh
# CentOS
yum install -y autossh
# Ubuntu
apt install -y autossh
# 编译安装
官网:https://www.harding.motd.ca/autossh/
yum install -y autoconf make automake gcc gcc-c++
gunzip -c autossh-1.4g.tgz | tar xvf -
cd autossh-1.4g
./configure
make
make install
$ which autossh
/usr/local/bin/autossh
# 配置Server2 ssh到 Server1的免密登陆
ssh-keygen -t rsa
不给passphrase
ssh-copy-id root@192.168.74.132
# 使用autossh实现Server1到Server2的远程端口转发,192.168.74.132为中转服务器IP
autossh -p 22 -M 2212 -NfR '*:2202:127.0.0.1:22' root@192.168.74.132
5:验证配置
bee@Server2:~/.ssh$ netstat -ntpa | grep -w 22
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 192.168.74.154:49904 192.168.74.132:22 ESTABLISHED 15887/ssh
如果有3行或以上,可能是你进行了大量的autossh命令尝试,最好关闭它们,关闭方法在PS章节有说明。
[root@Server1 ~]# netstat -ntpa | grep -w 2202
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:2202 0.0.0.0:* LISTEN 13381/sshd: root
注意如果看到本地是127.0.0.1:2202说明代理服务器Server1的ssh服务GatewayPorts没有打开。
此时,Server1上只能ssh -p 2202 bee@127.0.0.1登上Server2(其中bee为Server2上的普通用户)。ssh -p 2202 bee@192.168.74.132结果是Connection refused。
正常情况
[root@Server1 ~]# netstat -ntpa | grep -w 2202
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:2202 0.0.0.0:* LISTEN 1546/sshd: root
注意到本地是0 0.0.0.0:2202,是侦听所有地址的2202端口。
PS:
(1)如果你进行大量地尝试autossh命令,可能会有多个autossh进程,最好关闭它们,关闭之后再重新进行autossh连接。关闭 autossh
#直接查找 autossh 的 PID:
pgrep autossh
#使用 kill 命令,12345是查找出来的PID:
sudo kill 12345
(2)如果没有成功建议检查一下中转服务器的2202端口和内网服务器的22端口是否打开,一般云服务器防火墙都是关闭状态,通过安全组规则来打开2202端口。内网服务器的22端口一般也是打开状态,所以没有说明。
值得一提的是,Linux系统有多个防火墙软件,比如ufw,firewalld,iptables,它们同时使用会导致端口打开冲突,所以排查一下你服务器的每个防火墙软件的状态。
(3)如果服务器关机后重启了,只需要再次运行下面代码:
# 使用autossh实现Server1到Server2的远程端口转发,192.168.74.132为中转服务器IP
autossh -p 22 -M 2212 -NfR '*:2202:127.0.0.1:22' root@192.168.74.132
你也可以设置成开机后自动启动。