[Troubleshooting] 将 WSL2 的 SSH 端口映射到公网
Categories Troubleshooting
Tags
目标
- WSL2 内 SSH 服务监听端口 22
- Windows 本地端口 1145 转发到 WSL2 的 22
- 公网访问 Windows 公网 IP 的 1145 端口即可 SSH 登录 WSL2
- 公网访问 eagle233.top:1145 即可 SSH 登录 WSL2
确保 WSL2 内 SSH 服务正常
- 安装 SSH 服务(以 Ubuntu 为例):
sudo apt update
sudo apt install openssh-server
- 启动 SSH:
sudo systemctl enable ssh
sudo systemctl start ssh
sudo systemctl status ssh
- 确认监听所有接口:
sudo ss -tlnp | grep ssh
输出应包含:
0.0.0.0:22 # IPv4 全接口监听
[::]:22 # IPv6 全接口监听
- 配置 SSH 允许密码登录或指定用户:
编辑/etc/ssh/sshd_config:
ListenAddress 0.0.0.0
AllowUsers eagle233
PasswordAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
AllowTcpForwarding yes
GatewayPorts clientspecified
Protocol 2
MaxAuthTries 3
然后重启:
sudo systemctl restart ssh
sudo systemctl status ssh
- 将密钥复制到 WSL
# 创建 .ssh 目录(如果不存在)
mkdir -p ~/.ssh
# 进入 WSL
cd ~/.ssh
# 直接追加到 authorized_keys
cat /mnt/c/Users/eagle/.ssh/id_ed25519.pub >> authorized_keys
# 设置权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
- 安装
fail2ban
sudo apt install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
在 Windows 上做端口转发
使用 netsh 将本地端口 1145 转发到 WSL2 的 22:
# 转发所有 IPv4 地址
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=1145 connectaddress=127.0.0.1 connectport=22
使用
127.0.0.1,避免 WSL2 动态 IP 变化问题。
查看规则:
netsh interface portproxy show all
放行防火墙
确保 Windows 防火墙允许外部 TCP 1145:
New-NetFirewallRule -DisplayName "WSL2 SSH Public" -Direction Inbound -LocalPort 1145 -Protocol TCP -Action Allow
检查防火墙是否生效:
Get-NetFirewallRule -DisplayName "WSL2 SSH Public"
开机自启 WSL2
在任务计划程序里创建两个任务:
第一个任务:
C:\Program Files\PowerShell\7\pwsh.exe Start-Process wsl -ArgumentList "-d Ubuntu -u eagle233 --exec sh -c 'service ssh start; sleep infinity'" -WindowStyle Hidden
第二个任务:
C:\Program Files\PowerShell\7\pwsh.exe Start-Process wsl -ArgumentList "-d Ubuntu-22.04 -u ruichen --exec sh -c 'service ssh start; sleep infinity'" -WindowStyle Hidden
两个任务都会在开机时启动各自的 WSL2 并启动 SSH 服务。
路由器公网端口映射
在 OpenWrt 里将公网的 1145 端口转发到本地 IP 的 1145 端口上,并使用 DDNS 将公网 IP 固定到 eagle233.top.
Page views: Loading... · Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号