Linux монтирование usb дисков

Как смонтировать USB-HDD в Linux

В данной статье описано, как подключить USB-диск в системе Linux с помощью терминала и командной строки shell. Если вы пользуетесь менеджером рабочего стола, то, скорее всего, сможете использовать его для монтирования USB-диска.

Монтирование USB-диска ничем не отличается от монтирования флешки или даже обычного SATA-диска.

В этом руководстве вы узнаете, как:

1. Обнаружение USB-диска

После подключения USB-устройства к USB-порту система Linux добавляет новое блочное устройство в каталог /dev/. На данном этапе вы не можете использовать это устройство, так как файловая система устройства USB должна быть смонтирована, прежде чем вы сможете получить или сохранить какие-либо данные. Чтобы узнать, какое имя имеет файл блочного устройства, нужно выполнить команду fdisk -l.

Команда fdisk требует административных привилегий для доступа к необходимой информации, поэтому ее необходимо выполнять от имени пользователя root или с использованием префикса sudo.

После выполнения вышеуказанной команды вы получите результат, аналогичный приведенному ниже:

Disk /dev/sdc: 7.4 GiB, 7948206080 bytes, 15523840 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: dos Disk identifier: 0x00000000 Device Boot Start End Sectors Size Id Type /dev/sdc1 * 8192 15523839 15515648 7.4G b W95 FAT32

В приведенном выше отчете, скорее всего, будет перечислено несколько дисков, подключенных к вашей системе. Найдите свой USB-диск по его размеру и файловой системе. Когда все готово, запишите имя блочного устройства раздела, который вы собираетесь монтировать. Например, в нашем случае это будет /dev/sdc1 с файловой системой FAT32.

2. Создание точки монтирования

Прежде чем использовать команду mount для монтирования раздела USB-диска, необходимо создать точку монтирования. Точкой монтирования может быть любой новый или существующий каталог в файловой системе хоста. Используйте команду mkdir для создания нового каталога точки монтирования, в который вы хотите смонтировать USB-устройство. Например:

3. Монтирование USB-диска

На этом этапе можно монтировать раздел USB-диска /dev/sdc1 в точку монтирования /media/usb-drive:

# mount /dev/sdc1 /media/usb-drive/

Чтобы проверить, правильно ли смонтирован ваш USB-диск, снова выполните команду mount без каких-либо аргументов и используйте grep для поиска имени устройства USB-блока:

# mount | grep sdc1 /dev/sdc1 on /media/usb-drive type vfat (rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=utf8,shortname=mixed,errors=remount-ro

Если команда mount не выводит никаких данных, ваш USB-раздел не смонтирован. Кроме того, проверьте, правильно ли вы использовали имя устройства блока в приведенной выше команде.

Читайте также:  Выдать права sudo пользователю linux

4. Доступ к данным на USB-диске

Если все прошло успешно, мы можем получить доступ к нашим данным на накопителе USB, просто перейдя к ранее созданной точке монтирования /media/usb-drive:

Размонтирование USB-диска

Прежде чем размонтировать наш раздел расположенный на USB-диске, мы должны убедиться, что ни один процесс не использует каталог точки монтирования и не обращается к нему, иначе мы получим сообщение об ошибке, подобное приведенному ниже:

umount: /media/usb-drive: target is busy (In some cases useful info about processes that use the device is found by lsof(8) or fuser(1).)

Для размонтирования USB-диска, выполните следующую команду linux:

Постоянное монтирование USB-диска в Linux

Если у вас имеет место постоянное подключение USB-диска и чтобы после перезагрузки диск автоматически монтировался, добавьте следующую строку в конфигурационный файл /etc/fstab:

/dev/sdc1 /media/usb-drive vfat defaults 0 0

Обращение к USB-диску по имени блочного устройства из /etc/fstab может оказаться не лучшим решением. В зависимости от количества USB-накопителей, доступных в вашей системе Linux, имя блочного устройства может меняться. Хотя это может послужить хорошим временным решением, но лучше использовать исходное имя блочного устройства UUID, как описано ниже.

По этой причине рекомендуется использовать UUID раздела. Для этого сначала найдите UUID вашего USB-диска:

# ls -l /dev/disk/by-uuid/* lrwxrwxrwx 1 root root 10 Mar 27 23:38 /dev/disk/by-uuid/2016-08-30-11-31-31-00 -> ../../sdb1 lrwxrwxrwx 1 root root 10 Mar 27 23:38 /dev/disk/by-uuid/3eccfd4e-bd8b-4b5f-9fd8-4414a32ac289 -> ../../sda1 lrwxrwxrwx 1 root root 10 Mar 27 23:38 /dev/disk/by-uuid/4082248b-809d-4e63-93d2-56b5f13c875f -> ../../sda5 lrwxrwxrwx 1 root root 10 Mar 28 01:09 /dev/disk/by-uuid/8765-4321 -> ../../sdc1 lrwxrwxrwx 1 root root 10 Mar 27 23:38 /dev/disk/by-uuid/E6E3-F2A2 -> ../../sdb2

На основании вышеприведенного результата команды ls мы видим, что UUID, принадлежащий блочному устройству sdc1, имеет значение 8765-4321, поэтому наша строка монтирования в /etc/fstab будет иметь следующий вид:

/dev/disk/by-uuid/8765-4321 /media/usb-drive vfat 0 0

Теперь выполните команду mount -a, чтобы смонтировать все еще не смонтированные устройства, без перезагрузки системы

Заключение

В этой статье мы рассмотрели, как монтировать USB-диск в системе Linux, чтобы получить доступ к его данным и сохранить на нем новые данные. Linux позволяет либо временно монтировать USB-диск, который мы вставляем, либо сделать постоянное монтирование устройств хранения, которые мы не планируем извлекать. Независимо от того, есть ли у вас маленькая флешка или огромный внешний диск, приведенные здесь команды должны помочь смонтировать ваш USB-накопитель.

Если не указано иное, содержимое этой вики предоставляется на условиях следующей лицензии:
CC Attribution-Noncommercial-Share Alike 4.0 International

Источник

How to Mount a USB Drive in Debian 11

Removable USB drives allow you to easily transfer the files from one system to another. When you plug in a USB drive to your system’s USB port, it automatically mounts it. In Linux, it is mounted usually under the “/media” directory and can be accessed using the File Manager. However, in some scenarios, your system may not mount the USB drive automatically after you plug it in and you will be required to mount it manually in order to transfer the files between systems.

Читайте также:  Ps3 linux on usb

In this post, we will describe how you can mount a USB drive in a Debian OS in case it is not detected by the system automatically.

We use the Debian 11 OS to describe the procedure mentioned in this article. This procedure is also applicable to the previous Debian releases.

Mounting a USB drive

Step 1: Plug in the USB drive to any of the available USB ports in your computer.

Step 2: Once you plugged in the USB drive, check the USB drive name and the file system type drive used. To do this, launch the terminal application in your Debian 11 OS and issue the following command:

You will receive an output that is similar to that in the following screenshot. Scroll down the output and you will see your USB drive possibly at the end of the output labeled as sda, sdb, sdc, sdd, etc. Note down the name of your USB drive and the file system as you may need it later. In our scenario, the USB drive name is “/dev/sdb1” and the file system is “FAT32”.

https://linuxhint.com/wp-content/uploads/2019/11/1-40.png

Step 3: The next step is to create a directory that serves as the mount point for the USB drive. To create the mount point directory, issue the following command in the terminal:

Let’s create a mount point directory named USB under the /media directory:

https://linuxhint.com/wp-content/uploads/2019/11/2-36.png

Step 4: Then, to mount the USB drive to the mount point that you created, issue the following command in the terminal:

In our scenario, we will mount the USB drive /dev/sdb1 to the mount point that we created as /media/USB/. The command is as follows:

https://linuxhint.com/wp-content/uploads/2019/11/3-39.png

Step 5: To verify if the USB drive is mounted on the mount point successfully, issue the following command:

In our scenario, the command would be:

The output in the following screenshot shows that our USB drive /dev/sdb1 has been mounted on the mount point /media/USB. In case the command does not show any output, it means that the device is not mounted.

Читайте также:  Установка компас 3d linux

https://linuxhint.com/wp-content/uploads/2019/11/4-36.png

Step 6: To explore the mounted USB drive, move inside the mounted directory using the cd command:

Now, you can navigate the directories in the USB drive in the same way as you do with the other directories in your file system. To list the files in the USB, use the ls command.

https://linuxhint.com/wp-content/uploads/2019/11/5-35.png

You can also access and explore the USB drive through the File manager of your system.

https://linuxhint.com/wp-content/uploads/2019/11/6-35.png

Auto-Mount the USB Drive in Debian 11

You can also auto-mount the USB drive when it is plugged into the system. To do this, edit the /etc/fstab file in a text editor using the following command:

Add the following entry at the end of the file, replacing the /dev/sdb1 and vfat with your USB device name and filesystem:

Then, save and exit the text editor.

Now, run the following command to mount all the devices:

This command mounts all the USB drives that are added to the /etc/fstab file but have not yet been mounted. Also, the next time you restart your system with a USB drive plugged in, your USB drive will be automatically mounted.

Unmounting a USB Drive

If you no longer want to use the mounted USB drive, you can unmount or detach it. However, before attempting to unmount it, make sure that there are no other operations in progress on the mounted USB drive. Otherwise, the drive won’t detach and you’ll get an error message.

To unmount the USB drive, type umount followed by the mount point directory or the device name as follows:

In our scenario, it would be:

https://linuxhint.com/wp-content/uploads/2019/11/7-33.png

If you see no output, it means that all went well and your USB drive is unmounted from the system. You can also confirm it from your File Manager’s left sidebar.

https://linuxhint.com/wp-content/uploads/2019/11/8-28.png

To delete the mount point directory, issue the following command:

https://linuxhint.com/wp-content/uploads/2019/11/9-26.png

Conclusion

In this article, you learned how to mount a USB drive in a Debian OS and how to unmount it when you need to remove the drive. I hope it will be helpful whenever you need to mount/unmount a USB drive in your system.

About the author

Karim Buzdar

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.

Источник

Оцените статью
Adblock
detector