WSL-windows子系统

2023/6/15

以下操作基于ubuntu22.02演示

# 安装WSL

使用管理员权限打开powershell,执行以下命令

  • 开启windows子系统功能
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
1
  • WSL2

    • 检查系统版本

      如果只是安装WSL1此时可以重启电脑,如果需要安装WSL2,则需要检查版本,win10需要满足以下条件 For x64 systems: Version 1903 or later, with Build 18362.1049 or later. 对于 x64 系统:版本 1903 或更高版本,内部版本 18362.1049 或更高版本。 For ARM64 systems: Version 2004 or later, with Build 19041 or later. 对于 ARM64 系统:版本 2004 或更高版本,内部版本 19041 或更高版本。

    • 启用虚拟机功能,wsl2依赖虚拟机,和wsl1运行机制不同

    dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
    
    1
    • 下载linux内核更新包

    点击下载并双击安装 (opens new window)

    • 切换为wsl2

    wsl --set-default-version 2

  • 下载linux发行版

    ubuntu22.04 下载后安装 (opens new window)

# 升级WSL2

如果当时安装wsl安装的版本为1,则可升级为2

查看版本:

在CMD执行命令查看WSL子系统版本,如果不是2或为空则为1
>wsl -l -v
  NAME      STATE           VERSION
* Ubuntu    Running         2
1
2
3
4

升级WSL子系统到2

> 以下操作是从1升级到2的步骤
> 以管理员身份打开powershell或cmd执行以下命令
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
> 执行成功后重启电脑
> wsl -l -v 查看当前子系统对应的版本
> wsl --set-version <distribution name> <versionNumber>  修改为要升级的版本
1
2
3
4
5
6

#

# 开机启动

现在wsl会默认在一定的空闲时间后自动退出,所以需要做两件事,①要有一个保活也就是占用cpu的进程阻止被识别为空闲②要在clashx启动后在启动wsl,否则会需要重启才能识别代理,所以通过vbs脚本的形式来监听clash进程并通过tmux来进行保活,apt install tmux -y即可

Set ws = WScript.CreateObject("WScript.Shell")

' 等待Clash启动(静默模式)
maxWait = 180000
waitTime = 0
checkInterval = 5000

Do While waitTime < maxWait
    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    Set colProcesses = objWMIService.ExecQuery _
        ("Select * From Win32_Process Where Name = 'clash-win64.exe'")
    
    If colProcesses.Count > 0 Then
        WScript.Sleep 60000
        ws.Run "wsl -d Ubuntu -u root --exec /bin/bash -c ""systemctl start ssh.service && tmux""", 0
        WScript.Quit
    End If
    
    WScript.Sleep checkInterval
    waitTime = waitTime + checkInterval
Loop

' 超时后直接启动
ws.Run "wsl -d Ubuntu -u root --exec /bin/bash -c ""systemctl start ssh.service && tmux""", 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

将以上命令加入到windows计划任务中

右键此电脑-管理-计算机管理(本地)-系统工具-任务计划程序-任务计划程序库

  • 右侧创建任务,勾选使用最高权限运行;
  • 触发器:登陆时-当任何用户登陆时;
  • 操作
    • 程序或脚本:"C:\自己的目录\start_ubuntu.vbs"

# 代理

wsl2和wsl1不同,不能通过127.0.0.1localhost互联,采用虚拟机的方式出网,可在cmd中执行ipconfig 查看以太网适配器 vEthernet (WSL)的ip,作为共享ip使用。

vim ~/.bashrc
clash_proxy_host="172.29.0.1:8765"  #端口根据自己实际情况指定,要开启允许局域网访问
export https_proxy=http://${clash_proxy_host};
export http_proxy=http://${clash_proxy_host};
export all_proxy=socks5://${clash_proxy_host}
1
2
3
4
5

当然wsl有多种方式,以上方式采用的是nat出网,还有镜像模式,但这种方式需要配合clashx的tun模式,存在的问题是只有root用户可以使用,非root用户不行,所以还是采用上面的nat方式

# 参考

Last Updated: 2026/3/22
只爱西经
林一