反向代理

本文介绍如何利用ssh反向代理,实现跨网段访问内网。基于ubuntu 16.04 64bit系统。

功能:

利用ssh服务实现跨网段登陆。如公司内网访问家庭内网。

环境:

某牌子阿里云主机,ubuntu 16.04 64bit,文中以8.8.8.8作示例。
虚拟机,ubuntu 16.04 64bit

技术总结概述

外网开启转发,重启ssh。(一旦设置后,不用再改)。
内网生成 key,免密登陆。
内网用 autossh 设置反向代理。
访问:ssh <内网用户名>@<外网IP> -p <映射的端口>
完成。

经过一周测试,发现较稳定。

准备工作

所有机器都安装并启动了ssh服务,可正常连接。
云主机需要开放端口。

在云主机后台终端远程登陆,防止 ssh 出问题。

实验

配置

内网免密登陆外网机器,执行:

1
2
ssh-keygen
ssh-copy-id latelee@8.8.8.8

此步是为 autossh 作准备。

外网开启GatewayPorts。在/etc/ssh/sshd_config开启GatewayPorts,如无则添加:

1
GatewayPorts yes

重启 ssh服务:

1
/etc/init.d/ssh reload

内网IP

设置 ssh 反向代理:

1
ssh -fNR 9003:localhost:22 latelee@8.8.8.8

释义:9003为外网端口,最后是外网账号,如无密钥则需要输入外网密码。

外网

查看监听端口:

1
2
3
4
netstat -ntpl |grep sshd

tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 11009/sshd
tcp 0 0 0.0.0.0:9003 0.0.0.0:* LISTEN 11122/sshd: root

在外网机器进行测试,使用外网映射端口,内网用户、密码:

1
ssh -p 9003 latelee@localhost

作用及预期效果:在外网机器上可访问内网机器。

其它内网主机访问内网:

1
ssh latelee@8.8.8.8 -p 9003

监听重连

安装 autossh:

1
sudo apt install autossh

执行:

1
autossh -f -M 9004 -NR 9003:localhost:22 latelee@8.8.8.8

注:通过9004监听9003端口,如果9003断开,则重连。

将放到/etc/rc.local中,以便开机自启动。也可用 service 方式。

实验记录

1、
内网执行反向代理出现:

1
Warning: remote port forwarding failed for listen port 9003

方法:在外网删除占用该端口的进程,kill -9 11122 (11122为netstat查看到的端口)

设置后,起初可访问,过一段时间后无法访问,原因未知。

2、
云主机的端口,需要通过云主机控制台开放,否则无法连接。
通过 telnet <IP> <Port> 方式判断端口是否开放。

添加 autossh 后的端口:

1
2
3
4
5
6
7
8
9
10
11
12
13
外:
netstat -ntpl |grep sshd
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 11009/sshd
tcp 0 0 0.0.0.0:9004 0.0.0.0:* LISTEN 16307/sshd: root
tcp 0 0 0.0.0.0:9003 0.0.0.0:* LISTEN 16307/sshd: root

内:
netstat -ntpl |grep ssh
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1025/sshd
tcp 0 0 127.0.0.1:9004 0.0.0.0:* LISTEN 8232/ssh
tcp 0 0 127.0.0.1:9005 0.0.0.0:* LISTEN 7666/autossh
tcp6 0 0 :::22 :::* LISTEN 1025/sshd
tcp6 0 0 ::1:9004 :::* LISTEN 8232/ssh

释义:内网占用指定的端口P及P+1。外网占用端口P。即实现本功能,一个转发服务机器,外网占用2端口,内网占3个端口(不包括22端口)。

2、
非autossh情况下,内网正远程登陆,在云主机kill掉sshd进程,则内网自动断开。