【教程】使用WSL在windows上安装Linux并迁移出C盘

先决条件

宿主机必须是 Windows 10 2004 及更高版本(内部版本 19041 及更高版本)或 Windows 11 。 如果使用的是更早的版本,请参阅手动安装页

安装

可以使用单个命令安装运行 WSL 所需的一切内容。 在管理员模式下打开 PowerShell 或 Windows 命令提示符,输入 wsl --install (指定版本:wsl --install -d Ubuntu-20.04)命令,然后重启计算机。

wsl --install
正在安装: 虚拟机平台
已安装 虚拟机平台。
正在安装: 适用于 Linux 的 Windows 子系统
已安装 适用于 Linux 的 Windows 子系统。
正在安装: 适用于 Linux 的 Windows 子系统
已安装 适用于 Linux 的 Windows 子系统。
正在安装: Ubuntu
已安装 Ubuntu。
请求的操作成功。直到重新启动系统前更改将不会生效。

重启完成后,会自动引导安装,并提示输入用户名及密码

Ubuntu 已安装。
正在启动 Ubuntu...
Installing, this may take a few minutes...
Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms/wslusers
Enter new UNIX username: 你的用户名
New password: 你的密码
Retype new password: 重复密码
passwd: password updated successfully
Installation successful!
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

Welcome to Ubuntu 22.04.2 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage


This message is shown once a day. To disable it please create the
/home/你的用户名/.hushlogin file.

如果在输入用户名之后提示:

Ubuntu 已安装。
正在启动 Ubuntu...
Installing, this may take a few minutes...
Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms/wslusers
Enter new UNIX username: 你的用户名
参考的对象类型不支持尝试的操作。

不要关闭此时的控制台,令以管理员身份启动PowerShell,输入:

netsh winsock reset

然后重新输入用户名即可。

迁移

自动安装虽然简单易上手,但是无法指定安装位置,在开发过程中造成C盘占用过高,因此这里顺便把迁移教程也总结一下。

查看当前需要迁移的虚拟机,这里以Ubuntu-20.04为例。

wsl -l -v
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2

关闭系统

wsl --shutdown

导出虚拟机

wsl --export Ubuntu-20.04 D:\File_wsl\ubuntu2004\ubuntu.tar
正在导出,这可能需要几分钟时间。
操作成功完成。

注销之前的虚拟机

wslconfig /u Ubuntu-20.04

正在注销。
操作成功完成。

重新导入

D:\File_wsl\ubuntu2004(安装位置) 
D:\File_wsl\ubuntu2004\ubuntu.tar(源文件位置)

wsl --import Ubuntu-20.04 D:\File_wsl\ubuntu2004 D:\File_wsl\ubuntu2004\ubuntu.tar --version 2
正在导入,这可能需要几分钟时间。
操作成功完成。

此时就迁移成功了,可以将导出的tar文件删除。

此时启动ubuntu默认用户是root,修改为之前设定的用户

ubuntu2004 config --default-user 刚刚建立的用户名 

妈妈再也不用担心C盘被wsl占满啦

配置Vscode

在windows vscode上安装以下扩展:

  • Remote - WSL
  • Remote - SSH
  • WSL

更新ubuntu软件源中的所有软件列表

sudo apt-get update

之后点击vscode左下角远程连接

选择连接至wsl

基本上不会出问题

如果出现下面这样的报错

需要启动PowerShell,检查当前默认运行的linux系统

wsl -l -v

  NAME      STATE           VERSION
* Ubuntu    Running         2

如果星号不在ubuntu前方,输入:

wslconfig /setdefault ubuntu

卸载

管理员身份启动PowerShell

查看当前已安装子系统

wsl -l -v

  NAME      STATE           VERSION
* Ubuntu    Running         2

卸载

wslconfig /u Ubuntu
正在注销。
操作成功完成。

关闭虚拟引擎

wsl --shutdown
posted @ 2023-09-03 00:50  小拳头呀  阅读(2806)  评论(0编辑  收藏  举报