WSL2 本身要持续保持 Running,这样你在 WSL 里启动的 SSH Server 才不会因为 WSL 实例退出而断掉。
你现在的状态大概是:
text
Windows
│
└─ WSL2
│
├─ sshd ← 你通过 SSH 连进来
│
└─ Shell
│
└─ Windows Terminal
关闭 Windows Terminal
↓
Shell 退出
↓
WSL 没有其它"活跃任务"
↓
WSL2 自动停止
↓
sshd 消失
↓
SSH 连接断开
你要的是
text
Windows
│
└─ WSL2 ─────────────── Running
│
├─ systemd
├─ sshd
└─ 你的开发环境
↑
Windows Terminal 只是入口
关闭 Windows Terminal
↓
Terminal 消失
↓
WSL2 仍然 Running
↓
SSH 继续可连接
最直接的解决方案
不要用 sleep infinity 这种临时保活。
如果你的 WSL 版本支持 systemd,推荐利用一个 systemd 服务 + WSL 启动机制 来做。
不过这里有一个关键点:
systemd ≠ WSL 永久 Running
很多教程会把这两个东西混在一起。
即使你:
ini
[boot]
systemd=true
也只是让 WSL 启动后拥有 systemd。
如果:
text
systemd
↓
没有需要运行的服务
↓
WSL 仍然可能被 WSL 自动终止
所以我们需要让 WSL 中始终存在一个后台服务。
我建议你现在这样做
先进入你的 WSL:
powershell
wsl
执行:
bash
ps -p 1 -o comm=
如果返回:
text
systemd
很好,直接进入下面的步骤。
如果返回:
text
init
那你找AI吧。
如果已经是 systemd
创建一个专门用于 WSL 保活的服务:
bash
sudo nano /etc/systemd/system/wsl-keepalive.service
填入:
ini
[Unit]
Description=Keep WSL instance alive
After=network.target
[Service]
Type=simple
ExecStart=/bin/sleep infinity
Restart=always
[Install]
WantedBy=multi-user.target
保存,然后:
bash
sudo systemctl daemon-reload
启用:
bash
sudo systemctl enable wsl-keepalive.service
启动:
bash
sudo systemctl start wsl-keepalive.service
检查:
bash
systemctl status wsl-keepalive.service
应该看到:
text
Active: active (running)
然后测试
非常重要,别急着认为成功。
先退出 WSL:
bash
exit
关闭 Windows Terminal。
然后重新打开 PowerShell:
powershell
wsl -l -v
看看:
text
NAME STATE VERSION
Ubuntu-24.04 Running 2
如果还是:
text
Stopped
那就说明你的 WSL 环境还有另外一个问题,我们再处理。
SSH 这边还要确认一件事情
你现在 SSH 应该是类似:
text
ssh user@你的Windows主机IP -p xxxx
或者:
text
ssh user@localhost -p xxxx
如果 SSH Server 是运行在 WSL 里面,那么我们还要确保 sshd 本身是开机自动启动的。
如果你已经启用了 systemd:
bash
sudo systemctl enable ssh
sudo systemctl start ssh
检查:
bash
systemctl status ssh
应该是:
text
Active: active (running)
这样最终就是:
text
WSL启动
↓
systemd
├── ssh.service
│ └── sshd
│
└── wsl-keepalive.service
└── sleep infinity
即使没有任何终端连接:
text
Windows Terminal
↓
关闭
↓
Shell退出
↓
WSL仍有 wsl-keepalive.service
↓
WSL保持 Running
↓
sshd继续运行
↓
SSH不会断