Добрый день всем!
Проблема в том, что я скачал файлы и не могу понять где они хранятся, скачал я их через WSL
То есть надо понять где же корневой каталог его
В ВСЛ корень вот так прописан alejan@LAPTOP-IFFGH0V4:
А когда я набираю команду ls то я в консоли вижу необходимые мне файлы, но вот вытащить из самой директории (не через линукс) у меня не получается, так как я не могу найти корень и по поиску в винде не получается найти по наименованию файлов
Подскажите пожалуйста как идентифицировать где в винде создался корневой каталог ВСЛ?
-
Вопрос задан
-
17599 просмотров
Among its numerous advantages, one notable feature is the seamless accessibility of Linux files stored within WSL from the Windows operating system itself.
In this article, you’ll explore various methods of accessing WSL files. This will enable smooth file management and interoperability between Windows and Linux environments.
You will look at both graphical and command-line ways of accessing WSL files inside Windows.
Access WSL files using Windows Explorer
The most basic way of accessing a file on Windows is by launching the Windows File Explorer. The file manager is present on the taskbar, and you can just open it to browse files. Wait! That is for Windows files, but for Linux?
Yes. WSL indeed stores the file inside Windows because it is the host. If you have set up the WSL correctly on Windows, you will see a Penguin icon on your File Explorer.
Just click on it.
You will see the name of the WSL distributions you have installed currently as folders. I have two; an Ubuntu and an OpenSUSE Tumbleweeed.
Double-click on the one you need to access. Now, you are inside the root directory of that system.
Go inside the home → username folder, and there it is.
You are now accessing the home directory of the default user. Double-click on any file to open it on a Windows app. You can see in the screenshot below, I have opened the .bashrc
file on Notepad app.
.bashrc
file in NotepadUse the address bar of Explorer
You can use the address bar of Windows Explorer to go into the WSL folders. For this, click on the to address bar. When it is changed to editing, enter:
\\wsl$
This will bring you to the same folder, where all the WSL distributions are listed as folders. Click on any to enter into it.
💡 Tip: Open the current Linux directory location in Windows
Imagine that you are using Linux through the Windows terminal and you are in a specific directory location. Now, you think it would be better if you could access it in the file explorer.
This is possible and quite easy. Enter the following command on the WSL terminal.
explorer.exe .
Here, the .
refers to the current directory you are in. This means that your current directory will be opened in the Windows file explorer.
Similarly, while inside the WSL, you can specify a directory path to open that folder in Windows Explorer.
As you can see, the mentioned directory is opened in Windows Explorer and you can access the files.
Open a WSL text file in Notepad
While there are terminal-based text editors available in Linux, you may not be comfortable with the idea of editing files in the command line.
Thankfully, you can easily open those Linux text files using Windows’s Notepad.
notepad.exe /path/to/the/file/inside/wsl/distribution
Accessing files between WSL and Windows
As you can easily guess by now, it is possible to access files between WSL and the Windows host operating system.
Here are a few tips on accessing files between Windows and Linux inside WSL.
✋
If you are working on a project inside WSL, be sure to store the files inside the respective WSL system. Similarly, store all the files inside the Windows filesystem if you are working on a project using Windows, you can ensure maximum speed and performance.
Edit Windows files inside WSL
While inside WSL, you can open a file stored on the Windows filesystem using Linux tools like the Nano editor.
For this, we use the Mounted Drive concept.
nano /mnt/c/Users/username/Documents/filename
Here, the /mnt/c
represents the C drive mounted to the WSL. So, what the command actually does is, open the specified file on the location specified in nano editor.
You can use /mnt/d
, if you have a drive located with D:
in Windows.
Copy files between WSL and Windows
Inside the WSL, you can copy a file from WSL to a specified Windows folder. To do that, use the cp
command:
cp /home/$USER/filename /mnt/d/Documents/
This will copy the file called filename
from the home directory of the user to the Documents folder (if exists) on the D drive.
Similarly, if you want to transfer a file from a Windows folder into the WSL system, use:
cp /mnt/d/Documents/filename /home/$USER/
That’s it. You have copied the files.
🚧
Keep caution while managing files between the two operating systems. It can lead to file loses and corruption, if not handled properly.
Wrapping Up
Here, you learned about accessing files between Windows and Linux running inside WSL. The ability to access Linux files easily from Windows is super helpful for Windows users. Let me know if you have any questions.
WSL (Windows Subsystem for Linux) is a specially created software layer by Microsoft to run Linux binary executables natively on Windows 11 or 10. When you install a Linux distribution on WSL, it creates a Linux environment within Windows, with its own file system and home directory. However, how to find this directory using Graphical File Explorer of Windows? If you don’t know that then in this article, we learn about it.
The default home directory for the user account in WSL is located at /home/<username> which can be accessed using the Command line interface of WSL running bash.
For example, if your username is H2s, your home directory in WSL would be located at /home/h2s. By default, when we start the WSL Linux app, we are in our Home directory. You can switch to that using:
cd /home
The working of the home directory in WSL Linux is similar to the traditional Linux distros we are running on virtual machines, containers, or bare systems. It holds all files related user’s personal files and configuration settings. All the files of the home directory are only meant to use for your WSL instance and will not interfere with the Windows file system or vice versa…
Although we are showing this tutorial using for Ubuntu subsystem, the process will be the same for others too such as OpenSUSE, Kali, and Debian installed on WSL.
Steps to Find the WSL home directory using the GUI file explorer of Windows
- On your Windows 10 or 11, go to File Explorer or simply open MyPC to get it for finding the WSL Linux app home folder.
- After that from the left side panel scroll down to the end.
- Open WSL Linux File Explorer: There you will see the Linux Penguin icon, click that.
- Now, all the installed Linux apps such as Ubuntu, Debian, Kali, etc. on your WSL will show in the folder.
- For example, if we open the Ubuntu folder then inside that we will have a directory called ‘home‘. Open that and you will find the user of that WSL Linux app along with other files.
- After selecting the Linux WSL app, open the Home directory you want to explore manually using the GUI.
Additional tip:
To access all Windows 11 or 10 system drives under the Command Terminal of Ubuntu or another Linux environment installed on Windows WSL; we need to follow the mounting command of Linux.
Note: One thing to be mentioned is that the Bash Shell of the Linux environment should be launched under the Administrative right to access the system folders of Windows. To give administrative permission just right-click on the installed Linux environment such as Ubuntu and select “Run as Administrator”.
From your Linux Bash Shell type the following command to mount C: Drive:
cd /mnt/c ls
In the same way for D: drive type
cd /mnt/d ls
In this way, we can also mount both internal and external drives attached to our Windows 11 or 10 systems including the network drives.
Other Articles:
- Install Git LFS on WSL2 – Windows 11 or 10?
- How to install Anaconda on WSL Windows 10/11 using Ubuntu Linux App
- How to install Oracle Linux on Windows 10 or 11 WSL – Subsystem
- Install WSL- Windows Subsystem for Linux on Windows 11
Среда Windows Subsystem for Linux (WSL) позволяет запускать нативные приложения, писать скрипты, выполнять команды и скрипты Linux непосредственно из Windows без использования эмуляторов или развертывания выделенных виртуальных машин. Актуальной версией среды является WSL 2, в которой используется полноценное ядро Linux (версия ядра 5.15) и обеспечивает полную совместимость с системными вызовами. Образ ядра Linux в WSL представляет собой легкую виртуальную машину, для запуска которой не нужно устанавливать полноценную роль Hyper-V.
Содержание:
- Как установить Windows Subsystem for Linux (WSL2)?
- WSL: Установка дистрибутива Linux в Windows
- Команды для управления WSL в Windows
- Использование Linux в среде WSL
Вы можете запустить WSL 2:
- Во всех версиях Windows 10, начиная с 1903, а также в Windows 11 и Windows Server 2022;
- В настройка BIOS/UEFI компьютера должна быть включена поддержка аппаратной виртуализации: Intel VT (Intel Virtualization Technology) или AMD-V (SVM Mode).
Как установить Windows Subsystem for Linux (WSL2)?
Компонент WSL по умолчанию отключен в Windows. Современных дистрибутивах Windows 10 и Windows 11 для установки среды WSL достаточно выполнить команду:
wsl --install
Этак команда автоматически включит все необходимые компоненты Windows, необходимые для работы WSL, установить обновление ядра Linux для WSL2, загрузит дистрибутив Ubuntu (по-умолчанию) и установит его в WSL.
Осталось перезагрузить компьютер, и вы можете запускать среду WSL!
Вы можете установить для WSL другой дистрибутив Linux. Выведите список доступных дистрибутивов:
wsl --list --online
Укажите имя дистрибутива Linux, который установить в WSL. Например:
wsl --install -d kali-linux
Если в BIOS/UEFI компьютера не включена виртуализация, при установке WSL вы получите ошибку:
Installation failed with error 0x80070003 or error 0x80370102” it means that Bios Level Virtualization is not enabled on your computer.
Вы можете установить WSL2 в Windows вручную. Для этого придется вручную последовательно выполнить все этапы, который команда wsl —install запускала автоматически:
- Установить WSL
- Включить компонент виртуалзации VirtualMachinePlatform
- Установить ядро WSL 2
- Скачать и установить дистрибутив Linux для WSL
Сначала установите следующие компоненты Windows:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform
Перезагрузите компьютер.
Скачаем и установим обновление ядра Linux для WSL2 (WSL2 Linux kernel update package for x64 machines — https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi). Можете скачать пакет вручную или с помощью PowerShell:
Invoke-WebRequest -Uri https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi -OutFile "$($env:userprofile)\Downloads\wsl_update_x64.msi" -UseBasicParsing
Invoke-Item "$($env:userprofile)\Downloads\wsl_update_x64.msi"
rm "$($env:userprofile)\Downloads\wsl_update_x64.msi"
Еще раз перезагрузите компьютер и назначьте версию WSL 2 в качестве среды по-умолчанию:
wsl --set-default-version 2
WSL: Установка дистрибутива Linux в Windows
После того, как ядро WSL установлено в Windows, вы можете установить один или несколько дистрибутивов Linux на компьютер.
Можно установить пакет с дистрибутивом Linux через Microsoft Store. Доступны следующие дистрибутивы:
- Ubuntu
- Debian
- Kali Linux
- OpenSUSE
- Oracle Linux
- SUSE Linux Enterprise Server
- Fedora
Найдите нужную версию дистрибутива в Store и установите ее, нажав кнопку Получить (Get).
Если у вас отключен Windows Store, вы хотите установить дистрибутив WSL в Core редакции Windows Server или вам нужно установить WSL на Изолированном от интернета компьютере (оффлайн), вы можете скачать дистрибутив Ubuntu с помощью PowerShell командлета Invoke-WebRequest:
Invoke-WebRequest https://aka.ms/wslubuntu2204 -OutFile ubuntu-2204.appx –UseBasicParsing
Установите пакет для WSL с помощью:
Add-AppxPackage .\ubuntu-2204.appx
После окончания установки появится окно, в котором вам будет предложено указать имя пользователя и пароль для вашего дистрибутива.
После установки вы можете в меню Пуск появится отдельная программа для запуска Linux.
Также вы можете запустить ваш Linux из отдельной вкладки Windows Terminal или с помощью команды
wsl
.
Команды для управления WSL в Windows
Рассмотрим основные команды для управления ядром и дистрибутивами Linux в WSL.
Проверить текущую версию ядра WSL:
wsl --version
Обновить ядро WSL вручную:
wsl --update
Откатится к предыдущему ядру WSL:
wsl --update rollback
Вывести список установленных версий Linux:
wsl --list
Вывести дистрибутив Linux, который используется по-умолчанию:
wsl --status
Дистрибутив Linux по-умолчанию в WSL можно изменить:
wsl --setdefault Ubuntu
Запустить определенный дистрибутив в WSL:
wsl -d kali-linux
Завершить среду WSL:
wsl --shutdown
Можно войти в WSL Ubuntu под root и сбросить пароль:
ubuntu config --default-user root
Passwd
Вернуть пользователя по умолчанию
ubuntu config --default-user your_username
Для настройки параметров WSL и дистрибутивов Linux используются конфиг файлы:
- wsl.conf – файл с настройками конкретного дистрибутива Linux (находится в директории /etc)
- .wslconfig – глобальные настройки WSL, которые применяются ко всем дистрибутовам (находится в профиле пользователя в
%UserProfile%
)
Например, если вы хотите ограничить использование оперативной памяти и CPU компьютера дистрибутивами Linux в WSL, создайте такой файл
%UserProfile%\.wslconfig
:
[wsl2] memory=2GB processors=2
Использование Linux в среде WSL
Дистрибутив Linux, установленный в WSL является полноценной операционной системой. Поэтому после установки рекомендуется выполнить обновление пакетов. Для Ubuntu выполните команду:
$ sudo apt-get update && sudo apt-get upgrade -y
Файловая система вашего дистрибутива Linux хранится в профиле пользователя в виде VHDX файла. Например, виртуальный диск Ubuntu хранится в папке
%USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState
Файловая система Linux в WSL монтируется в виде сетевой папки прямо в проводник Windows.
Также для прямого доступа к файлам WSL из Windows можно использовать UNC путь. Например:
notepad \\wsl$\Ubuntu\sysops\home\1122.txt
В свою очередь локальные диски Windows монтируются в WSL в папку mnt. Вывести список файлов папок на диске C:
wsl
ls /mnt
ls/mnt/c
Другие примеры запуска Linux команд из Windows:
dir | wsl grep Sa
wsl ls ‑la > 123.txt
wsl ls ‑la /proc/cpuinfo
wsl ls ‑la “/mnt/c/Program Files”
Вы можете установить любые пакеты в Linux. Например, установите файловый менеджер Midnight Commander:
$ sudo apt-get install mc
В современной версии WSL 2 вы можете запускать из Windows любые приложения Linux с графическим интерфейсом (X11 и Wayland). Например, установите графический редактор:
$ sudo apt install gimp -y
Чтобы запустить его из Windows просто выполните команду:
wsl gimp
Sign in to your How-To Geek account
Quick Links
-
Open WSL Files from Terminal
-
Open the WSL Directory in File Explorer Directly
Summary
- Enter «\\wsl$» in the File Explorer address bar to view all of your Linux distributions.
- Run explorer.exe . from within your Linux distribution to open Windows File Explorer to view that Linux distribution’s files.
- You can directly interact with your Linux files from within Windows.
Windows 10’s May 2019 Update introduced an easy, safe, and officially supported way to access and work with your Linux files from within File Explorer and other applications. Here’s how to get at your Windows Subsystem for Linux (WSL) files.
Unlike previous methods, this is a safe way to work with Linux files! Windows does some magic in the background, making it possible to edit your Linux files from Windows applications without causing file permission issues. You still shouldn’t modify the underlying files at their real location on your system.
It doesn’t matter if you use WSL1 or WSL2. These commands all function exactly the same way.
Open WSL Files from Terminal
There are two ways to access your Linux files. First, the easy one. From within the Windows Subsystem for Linux environment you want to browse, run the following command:
explorer.exe .
This will launch File Explorer showing the current Linux directory—you can browse the Linux environment’s file system from there.
Open the WSL Directory in File Explorer Directly
You can also access them directly at the \\wsl$
path. In File Explorer or any other Windows application that can browse files, navigate to the following path:
\\wsl$
You’ll see the folders for all your installed Linux distributions, which are exposed as if they were network shares. For example, Ubuntu 22.04 is usually available at \\wsl$\Ubuntu-22.04
.
Feel free to create a shortcut to this folder—for example, you could drag it to the Quick Access section in File Explorer’s sidebar.
Again, you can modify these files normally as if they were any other type of file on your system. Modify files with Windows tools (Notepad even supports Unix line endings!), create new files in the Linux folders, delete files, or do anything else you like. Windows will ensure nothing goes wrong and the file’s permissions are updated properly.