Windows 11 主机上建立反向隧道,实现服务端连接内网客户端主机
此时需要在 Windows 11 主机上建立反向隧道,将本地端口映射到公网服务器的固定端口。
推荐方法:使用 SSH 反向隧道(Reverse Tunnel)
前提:
- CentOS 7 开启 SSH 服务(sshd),允许 root 或普通用户登录。
- Windows 11 安装 OpenSSH 客户端(Win11 默认已含)或使用 PuTTY/plink。
步骤 1:在 CentOS 7 上配置 SSH 允许 GatewayPorts
编辑 /etc/ssh/sshd_config:
ini
编辑
GatewayPorts yes
AllowTcpForwarding yes
重启 SSH:
bash
编辑
systemctl restart sshd
这允许远程客户端通过 SSH 将端口绑定到公网 IP(而不仅是 127.0.0.1)。
步骤 2:从 Windows 11 主动建立反向隧道到 CentOS
在 Windows 11 上以管理员身份打开 PowerShell 或 CMD:
powershell
编辑
# 假设 CentOS 的 SSH 用户为 testuser,IP 为 220.228.253.101 ssh -R 0.0.0.0:502:127.0.0.1:502 \ -R 0.0.0.0:503:127.0.0.1:503 \ -R 0.0.0.0:504:127.0.0.1:504 \ testuser@220.228.253.101
注意:这里假设 Modbus 服务在 Windows 上监听
127.0.0.1或0.0.0.0。如果是192.168.3.20,则把127.0.0.1改成192.168.3.20。
这样,当连接成功后:
- 任何访问
220.228.253.101:502的流量都会被转发到 Windows 11 的 502 端口。 - 同理适用于 503、504。
方案二:纯 PowerShell + 任务计划程序(无 WSL)
适用于无法使用 WSL 的环境。
步骤 1:创建守护脚本(带重连逻辑)
创建文件:C:\Scripts\modbus_autossh.ps1
powershell
编辑
# modbus_autossh.ps1
$ErrorActionPreference = "Stop"
$CENTOS_USER = "testuser"
$CENTOS_HOST = "220.228.253.101"
$LOCAL_IP = "192.168.3.20"
$PORTS = @(502, 503, 504)
# 日志函数
function Write-Log {
param([string]$msg)
$log = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $msg"
Write-Host $log
Add-Content -Path "C:\Scripts\tunnel.log" -Value $log
}
# 构建 SSH 参数
$sshArgs = @(
"-o", "StrictHostKeyChecking=no",
"-o", "ServerAliveInterval=30",
"-o", "ServerAliveCountMax=3",
"-o", "ExitOnForwardFailure=yes",
"-N"
)
foreach ($port in $PORTs) {
$sshArgs += "-R", "0.0.0.0:${port}:${LOCAL_IP}:${port}"
}
$sshArgs += "${CENTOS_USER}@${CENTOS_HOST}"
while ($true) {
Write-Log "Starting SSH tunnel..."
# 启动 SSH 进程(前台阻塞)
$proc = Start-Process -FilePath "ssh" -ArgumentList $sshArgs -PassThru -Wait
# 如果退出,记录并等待重连
Write-Log "SSH process exited with code: $($proc.ExitCode)"
Write-Log "Reconnecting in 10 seconds..."
Start-Sleep -Seconds 10
}
⚠️ 注意:此脚本会前台运行 SSH(
-Wait),确保能捕获退出事件。
步骤 2:创建启动器(用于任务计划程序)
创建:C:\Scripts\start_tunnel.bat
bat
编辑
@echo off
cd /d C:\Scripts
powershell.exe -ExecutionPolicy Bypass -File "C:\Scripts\modbus_autossh.ps1"
步骤 3:配置任务计划程序
- 打开
taskschd.msc - 创建任务:
- 名称:
Modbus AutoSSH (PowerShell) - 勾选“不管用户是否登录都要运行”、“使用最高权限”
- 名称:
- 触发器:启动时
- 操作:启动程序
- 程序:
C:\Scripts\start_tunnel.bat
- 程序:
- 条件:取消电源限制
- 确定,输入密码
✅ 开机后,脚本将持续运行,断线自动重连。
javascript
posted on 2025-12-18 17:06 sunny_2016 阅读(23) 评论(0) 收藏 举报
浙公网安备 33010602011771号