掌上游戏新活动平台

使用 nginx 的 stream模块的TCP 转发实现内网SSH

2025-10-11 14:23:37

需求

一个外网服务器,带着若干内网服务器

内网服务器 WEB 网站通过 nginx 的 http 模块进行端口映射和转发,完美的实现

但是,

内网服务器的 ssh 登录总是需要一个外网服务器作为跳板, 总是很繁琐,并且很难管理

内网服务器的 rdp 登录 还需要跳板服务器上安装一个图形界面,这就很不舒服了!

当前环境

$ nginx -v

nginx version: nginx/1.14.0 (Ubuntu)

配置 tcp 转发

$ sudo vim /etc/nginx/nginx.conf

增加一个 stream 模块

stream {

log_format tcp_trans '$remote_addr [$time_local] '

'$protocol $status $bytes_sent $bytes_received '

'$session_time "$upstream_addr" '

'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

##

# Logging Settings

##

# below will place in /usr/share/nginx/logs/

# access_log logs/access.log tcp_trans;

# error_log logs/error.log;

# place in /var/log/nginx/

access_log /var/log/nginx/access.log tcp_trans;

error_log /var/log/nginx/error.log;

# place all tcp transfer config here

include /etc/nginx/trans.conf.d/*.conf;

}

注解:

配置文件 /etc/nginx/trans.conf.d/*.conf 不能放在 conf.d 目录,所以在这里新建了一个目录 trans.conf.d

$ sudo mkdir trans.conf.d

日志文件依然放在 nginx 惯例配置的目录: /var/log/nginx/

注意这一行

access_log /var/log/nginx/access.log tcp_trans;

最后一部分 tcp_trans 不要漏掉!

http 模块配置部分没有这个部分,使用的是缺省的日志格式

而我们 stream 模块自定义了日志格式,所以,必须加上!

测试

$ sudo nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

重启生效

$ systemctl reload nginx

错误时查看状态

$ systemctl status nginx.service

经常遇到的错误

Jul 14 10:15:22 ubuntu1804-69 systemd[1]: Reload failed for A high

performance web server and a reverse proxy se

一般首先排查 nginx 自身配置错误,保证 sudo nginx -t 正确其次排查端口占用是否冲突,例如: 还安装了 Appache 并配置了 网站,占用了 80 端口

创建配置文件

假设外网地址是 1.2.3.4, 2 个内网地址 192.168.0.123,192.168.0.234

SSH 转发

$ cd /etc/nginx/trans.conf.d

取一个一眼就明白的 文件名,例如:

转发网关服务器 22123 端口到内网地址 192.168.0.123 的SSH (22)端,文件名就叫 : ssh123.conf

也就是通过 SSH 到外网的 22123端口,实际会登录到内网 192.168.0.123 上

$ sudo vim ssh123.conf

# tranfer all 22123 to 192.168.0.123:22

server {

listen 22123;

proxy_connect_timeout 65s;

proxy_timeout 12h;

proxy_pass 192.168.0.123:22;

}

RDP 转发

转发网关服务器 33234 端口到内网地址 192.168.0.234 的RDP 远程桌面 (3389 端口),文件名: rdp234.conf

$ sudo vim rdp234conf

# tranfer all 22234 to 192.168.0.234:3389

server {

listen 22234;

proxy_connect_timeout 65s;

proxy_timeout 12h;

proxy_pass 192.168.0.234:3389;

}

测试

重启 nginx 生效

$ systemctl reload nginx

在自己的桌面电脑上输入 ssh 登录命令

$ ssh -p 22123 dhbm@1.2.3.4

或者 putty 配置 ip 和端口

在自己的桌面电脑上配置一个远程桌面,ip = 1.2.3.4 , port = 22234

如果拿不准防火墙设置,先关闭!完成之后,再去编写 ufw 规则!

sudo ufw allow 22123;

sudo ufw allow 22234

限制 IP 访问

假设外网地址 12.34.56.78 和 1.2.3.4 允许访问 192.168.0.123:443 上的 https 网站

其他外网地址不能访问

$ cat https123.conf

# add by wzh 20210810

# # tranfer all 4123 to 192.168.0.123:443

server {

listen 4123;

proxy_connect_timeout 65s;

proxy_timeout 12hs;

proxy_pass 192.168.0.123:443;

allow 192.168.0.0/24;

allow 12.34.56.78;

allow 1.2.3.4;

deny all;

}