"WSL" 是 Windows Subsystem for Linux(Windows 的 Linux 子系统)的缩写,是微软在 Windows 上运行原生 Linux 二进制可执行文件的兼容层。
主要功能:
允许用户在 Windows 上直接运行 Linux 命令行工具(如 Bash、apt、grep 等)。
支持多个 Linux 发行版(如 Ubuntu、Debian、Kali Linux 等)。
两种版本:
WSL 2(基于轻量级虚拟机,性能更高,支持完整 Linux 内核)
常见用途:
- 运行 Linux 开发环境(如 Python、C/C++、Node.js)。
1. WSL 安装方法
1.1系统要求
- Windows 10(版本 2004 或更高) 或 Windows 11
- 支持 虚拟化技术(VT-x/AMD-V)(BIOS/UEFI 中需启用)
1.2安装步骤
方法 1:一键安装(推荐)
wsl --install
方法 2:手动安装
1)启用 WSL 功能(管理员 PowerShell):
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
2)启用虚拟机平台(WSL 2 需要):
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
3)重启电脑
4)设置 WSL 2 为默认版本:
wsl --set-default-version 2
5)安装 Linux 发行版(Microsoft Store 或命令行):
- 从 Microsoft Store 下载(如 Ubuntu、Debian、Kali Linux)
wsl --install -d <发行版名称>
# 例如:wsl --install -d Ubuntu-22.04
2. WSL 使用技巧
2.1基本命令
命令 | 说明 |
---|
wsl | |
wsl -d <发行版> | |
wsl --list --online | |
wsl --list --verbose | 查看已安装的发行版及版本(WSL 1/WSL 2) |
wsl --shutdown | |
wsl --terminate <发行版> | |
wsl --export <发行版> <文件名.tar> | |
wsl --import <新发行版> <安装路径> <备份文件> | |
2.2文件系统交互
\\wsl$\<发行版名称>\(如 \\wsl$\Ubuntu\home\user)
/mnt/c/(对应 C:\)
/mnt/d/(对应 D:\)
2.3配置默认用户
<发行版> config --default-user <用户名>
例如(Ubuntu):
ubuntu config --default-user root # 默认以 root 登录
2.4升级 WSL 2 内核
wsl --update
2.5运行 GUI 应用(WSLg)
- 支持 Linux GUI 程序(如 GIMP、VS Code)
gedit
或
firefox、nautilus 等
3. 高级用法
3.1 Docker + WSL 2
1)安装 Docker Desktop 并启用 WSL 2 后端
2)在 WSL 中直接使用 docker
命令
3.2 VS Code 远程开发
1)安装 VS Code 和 Remote - WSL 扩展
2)在 WSL 终端输入:
code .
即可在 Windows 的 VS Code 中编辑 Linux 文件
3.3 Zsh / Oh My Zsh 美化终端
sudo apt install zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
4. 常见问题
4.1 WSL 2 网络问题
Windows 访问 WSL 2 服务(如 localhost:3000
):
hostname -I # 查看 WSL 2 的 IP
WSL 2 访问 Windows 服务:
cat /etc/resolv.conf # 查看 Windows 的 IP(nameserver)
4.2性能优化
关闭 WSL 2 的虚拟机(节省资源):
wsl --shutdown
限制内存使用(在 %USERPROFILE%\.wslconfig
中配置):
[wsl2]
memory=4GB # 限制最大内存
processors=2 # 限制 CPU 核心数
5. 总结
✅ 适合人群:开发者、Linux 学习者、DevOps
✅ 优势:轻量级、高性能、与 Windows 无缝集成
✅ 推荐版本:WSL 2(支持完整 Linux 内核)
附:WSL 命令速查表
命令 | 描述 |
---|
wsl --list --online | |
wsl --install | |
wsl --install --distribution <dist_name> | |
wsl --list --verbose | |
wsl -d <dist_name> | |
wsl -d <dist_name> --user <username> | |
wsl ~ -d <dist_name> | |
wsl --set-default <dist_name> | |
wsl --terminate <dist_name> | |
wsl --shutdown | |
wsl --version | |
wsl --status | |
wsl --set-version <dist_name> <ver> | |
wsl --export <dist_name> <file.tar> | |
wsl --import <dist_name> <import location> <exported file> | |
wsl --unregister <DistributionName> | |
wsl --mount <diskpath> | |
wsl --update | |
wsl --help | |
注:
<dist_name>
表示发行版名称(如 Ubuntu、Debian 等)。<file.tar>
表示导出的 tar 文件名。
阅读原文:原文链接
该文章在 2025/7/21 10:58:58 编辑过