Ubuntu Documentation

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

Разделы дисков в Linux подключаются к системе совсем не так, как в Windows. Здесь есть корневая файловая система, куда подключаются все другие разделы и устройства, которые вы будете использовать. Системные разделы монтируются автоматически при старте системы. Но если вам нужно подключить дополнительные разделы, в некоторых случаях, может понадобиться это делать вручную.

В этой статье мы рассмотрим как выполняется монтирование диска в Linux, поговорим о том, как правильно использовать утилиту mount, umount и посмотреть какие разделы куда примонтированы.

Что такое монтирование?

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

Фактически смонтированный раздел становится частью корневой файловой системы и система старается сделать работу со всеми разделами, независимо от их файловых систем, прозрачной. Это значит, что если вы примонтируете участок оперативной памяти или удаленную сетевую папку, то сможете работать с ней в файловом менеджере точно так же, как и с локальным диском.

Например, вы хотите примонтировать флешку. Вы даете системе команду подключить ее в папку /run/media/имя_пользователя/UUID_флешки/. Система определяет файловую систему устройства, а затем, используя драйвера ядра подключает ее к указанной папке. Дальше вам остается работать с той папкой, как с любой другой. Больше ни о чем думать не нужно. Когда надумаете извлечь флешку, ее нужно отмонтировать.

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

Обычно, монтированием занимаются специальные сервисы оболочки, но не всегда они доступны. А иногда нужно сделать все вручную, чтобы задать дополнительные опции монтирования или другие параметры. Для монтирования в Linux используется команда mount. Рассмотрим ее параметры:

$ mount файл_устройства папка_назначения

Или расширенный вариант:

$ mount опции -t файловая_система -o опции_монтирования файл_устройства папка_назначения

Опции задают различные дополнительные особенности работы утилиты. Опция -t необязательна, но она позволяет задать файловую систему, которая будет использована и иногда это очень полезно. С помощью опции -o вы можете задать различные параметры монтирования, например, монтировать только для чтения и т д. Последних два параметра — это файл устройства, например, /dev/sda1 и папка назначения, например, /mnt.

Перед тем как перейти к рассмотрению примеров работы утилитой, давайте рассмотрим ее основные опции:

  • -V — вывести версию утилиты;
  • -h — вывести справку;
  • -v — подробный режим;
  • -a, —all — примонтировать все устройства, описанные в fstab;
  • -F, —fork — создавать отдельный экземпляр mount для каждого отдельного раздела;
  • -f, —fake — не выполнять никаких действий, а только посмотреть что собирается делать утилита;
  • -n, —no-mtab — не записывать данные о монтировании в /etc/mtab;
  • -l, —show-labels — добавить метку диска к точке монтирования;
  • -c — использовать только абсолютные пути;
  • -r, —read-only — монтировать раздел только для чтения;
  • -w, —rw — монтировать для чтения и записи;
  • -L, —label — монтировать раздел по метке;
  • -U, —uuid — монтировать раздел по UUID;
  • -T, —fstab — использовать альтернативный fstab;
  • -B, —bind — монтировать локальную папку;
  • -R, —rbind — перемонтировать локальную папку.

Это не все, но основные опции, которые вам понадобятся во время работы с утилитой. Также, возможно, вы захотите знать список опций монтирования, которые могут быть полезными. Они все перечислены в статье автоматическое монтирование в fstab и писать их еще и здесь нет смысла. А теперь перейдем к примерам и рассмотрим как монтировать диск в linux.

Монтирование разделов с помощью mount

Монтирование разделов с помощью mount выполняется очень просто. Фактически в большинстве случаев будет достаточно упрощенной версии команды. Например, смонтируем раздел /dev/sdb6 в папку /mnt:

sudo mount /dev/sdb6 /mnt/

В большинстве случаев вы будете вынуждены выполнять команду mount с правами суперпользователя, если обратное не указано в fstab (опция монтирования users). Вы можете посмотреть информацию о процессе монтирования добавив опцию -v:

Читать статью  Проверка скорости работы жесткого диска

sudo mount -v /dev/sdb6 /mnt/

Если нужно, вы можете указать файловую систему с помощью опции -t:

sudo mount -v -t ext4 /dev/sdb6 /mnt

Если необходимо примонтировать файловую систему только для чтения, то вы можете использовать опцию -r или опцию монтирования -o ro, результат будет одинаковым:

sudo mount -t ext4 -r /dev/sdb6 /mnt
$ sudo mount -t ext4 -o ro /dev/sdb6 /mnt

Вы можете использовать и другие опции чтобы выполнить монтирование разделов linux, например, указать, что на этом разделе нельзя выполнять программы:

sudo mount -t ext4 -o noexec /dev/sdb6 /mnt

Обратите внимание, что вы не можете использовать опции uid, gid, fmask для файловых систем ext. Они поддерживаются только в FAT, vFAT, exFAT.

Вы можете использовать не только имена устройств чтобы выполнить монтирование диска в linux. Для этого можно применять UUID или метки, например, монтирование с помощью UUID:

sudo mount —uuid=»b386d309-05c1-42c8-8364-8d37270b69e0″ /mnt

Посмотреть uuid для ваших разделов можно с помощью команды:

Точно так же вы можете использовать метки. Команда монтирования диска linux будет выглядеть так:

sudo mount —label=»home» /mnt/

Вы можете примонтировать одну папку в другую, для этого используйте опцию —bind

sudo mount —bind /mnt/ /media/

Возможно, не только монтирование разделов linux, но и монтирование файлов, если они содержат файловую систему, например, образов дисков. Монтирование образа диска linux работает точно так же:

sudo mount ~/file.iso /mnt

Посмотреть список всех примонтированных устройств можно просто выполнив mount без параметров:

Размонтирование устройств в Linux

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

sudo umount /mnt

Теперь ваше устройство не смонтировано. Но иногда может возникнуть ошибка размонтирования. Система сообщит, что устройство занято: umount: /mnt: target is busy.

Проблему можно решить закрыв все программы, которые могут использовать любой файл в этой папке. Какие именно это программы вы можете узнать с помощью команды lsof:

lsof -w /mnt
$ lsof -w /dev/sdb6

Здесь вы видите всю необходимую информацию, чтобы понять что происходит и что с этим делать. Утилита вывела название программы, ее PID, и даже файл, с которым она работает. Вы можете завершить все программы, а потом снова повторить попытку или используйте опцию -l, файловая система будет отключена немедленно, несмотря на то, что она занята:

sudo umount -l /mnt

Выводы

В этой статье мы рассмотрели как выполняется монтирование жестких дисков linux, а также разделов и даже образов. Вы знаете как правильно использовать опции mount и umount. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Introduction

This guide goes over procedures for a single partition drive install only. Multiple partition drive installations are not very hard, and you may very well figure it out by using this guide; however, make sure you add an entry in /etc/fstab for each partition, not just the drive.

A Note about File Systems:

Drives that are going to be used only under Ubuntu should be formatted using the ext3/ext4 file system (depending on which version of Ubuntu you use and whether you need Linux backwards compatibility). For sharing between Ubuntu and Windows, FAT32 is often the recommended file system, although NTFS works quite well too. If you are new to file systems and partitioning, please do some preliminary research on the two before you attempt this procedure.

Determine Drive Information

We assume that the hard drive is physically installed and detected by the BIOS.

To determine the path that your system has assigned to the new hard drive, open a terminal and run:

sudo lshw -C disk

IconsPage/example.png

This should produce output similar to this sample:

*-disk description: ATA Disk product: IC25N040ATCS04-0 vendor: Hitachi physical id: 0 bus info: ide@0.0 logical name: /dev/sdb version: CA4OA71A serial: CSH405DCLSHK6B size: 37GB capacity: 37GB

Be sure to note the «logical name» entry, as it will be used several times throughout this guide.

Partition The Disk

If you have already formatted the drive and it contains data, skip this step and move on to «Mount Point.» If the drive is still blank and unformatted, then you have two options: formatting the drive using the command line, or installing GParted for a graphical approach. Decide whether you want the drive to contain one single partition, or if you want to divide the space up between two or more partitions.

Читать статью  Проверка S. M. A. R. T. жёсткого диска

Partitioning Using GParted

If System > Administration > GNOME Partition Editor (or ‘Partition Editor’) is not available, install «GParted» using «sudo apt-get install gparted» from the command line, «Add/Remove Software» (or «Add/Remove. «) from the Applications menu, or «Synaptic Package Manager» from the System > Administration menu. Open GParted and let’s get started.

gksudo gparted

IconsPage/note.png

Always use gksu or gksudo for graphical applications like gparted and sudo for command line applications, like apt-get.

In the top-right corner of the window, choose your new hard drive from the drop-down list, referring back to the «logical name» from earlier. The window should refresh and show you a representation of the new drive. Assuming that the drive has yet to have been used, a white bar will run across the window. Use these steps to partition the drive with a single partition.

1) Right-click on the white bar and choose «New.»

2) For «New Size» the number should be the maximum allowable, to fill the entire disk.

3) Choose «Primary Partition»

4) Now decide on a filesystem. Use «ext3» if the drive will only be used with Ubuntu. For file-sharing between Ubuntu and Windows, you should use «fat32.» If you are unsure, search around the wiki and forums for advice.

5) Now click Add to compute the partition. The graphical display should update to show a new partition covering the entire disk.

6) To finish, click «Apply,» or Edit > Apply. The disk will then be partitioned and formatted. You may now close GParted.

Command Line Partitioning

There are two commands that can be used in the command line to partition a new drive: fdisk and parted. fdisk is an older program, and its main downside is that it can only create MBR partitions. parted allows you to create MBR or GPT partitions.

GPT vs MBR

MBR (Master Boot Record) has two main limitations: you cannot have a partition larger than 2 TB and you cannot have more than 4 primary partitions. GPT (GUID Partition Table) can do both of these things, but it is part of the EFI standard. This means your kernel must support EFI. The latest version of the kernel supports EFI, and almost all the latest distros do too.

parted

Refer back to the logical name you noted from earlier. For illustration, I’ll use /dev/sdb, and assume that you want a single partition on the disk, occupying all the free space.

1) Start parted as follows:

sudo parted /dev/sdb

2) Create a new GPT disklabel (aka partition table):

(parted) mklabel gpt

3) Set the default unit to TB:

(parted) unit TB

4) Create one partition occupying all the space on the drive. For a 4TB drive:

(parted) mkpart Partition name? []? primary File system type? [ext2]? ext4 Start? 0 End? 4

Alternatively, you can set the partition size as a percentage of the disk. To create a partition occupying all the space on the drive:

(parted) mkpart Partition name? []? primary File system type? [ext2]? ext4 Start? 0% End? 100%

5) Check that the results are correct:

(parted) print

There should be one partition occupying the entire drive.

6) Save and quit «parted»:

(parted) quit

fdisk

Refer back to the logical name you noted from earlier. For illustration, I’ll use /dev/sdb, and assume that you want a single partition on the disk, occupying all the free space.

  1. software that runs at boot time (e.g., old versions of LILO)
  2. booting and partitioning software from other OSs (e.g., DOS FDISK, OS/2 FDISK)

Otherwise, this will not negatively affect you.

sudo fdisk /dev/sdb
Command (m for help): m Command action a toggle a bootable flag b edit bsd disklabel c toggle the dos compatibility flag d delete a partition l list known partition types m print this menu n add a new partition o create a new empty DOS partition table p print the partition table q quit without saving changes s create a new empty Sun disklabel t change a partition's system id u change display/entry units v verify the partition table w write table to disk and exit x extra functionality (experts only) Command (m for help):

3) We want to add a new partition. Type «n» and press enter.

Command action e extended p primary partition (1-4)

4) We want a primary partition. Enter «p» and enter.

Partition number (1-4):

5) Since this will be the only partition on the drive, number 1. Enter «1» and enter.

Command (m for help):

If it asks about the first cylinder, just type «1» and enter. (We are making 1 partition to use the whole disk, so it should start at the beginning.)

Читать статью  Проверка диска Chkdsk – как запустить в Windows 10

6) Now that the partition is entered, choose option «w» to write the partition table to the disk. Type «w» and enter.

The partition table has been altered!

7) If all went well, you now have a properly partitioned hard drive that’s ready to be formatted. Since this is the first partition, Linux will recognize it as /dev/sdb1, while the disk that the partition is on is still /dev/sdb.

Command Line Formatting

sudo mkfs -t ext4 /dev/sdb1
sudo mkfs -t fat32 /dev/sdb1

As always, substitute «/dev/sdb1» with your own partition’s path.

Modify Reserved Space (Optional)

When formatting the drive as ext2/ext3, 5% of the drive’s total space is reserved for the super-user (root) so that the operating system can still write to the disk even if it is full. However, for disks that only contain data, this is not necessary.

NOTE: You may run this command on a fat32 file system, but it will do nothing; therefore, I highly recommend not running it.

You can adjust the percentage of reserved space with the «tune2fs» command, like this:

sudo tune2fs -m 1 /dev/sdb1

This example reserves 1% of space — change this number if you wish.

  • Using this command does not change any existing data on the drive. You can use it on a drive which already contains data.

Create A Mount Point

sudo mkdir /media/mynewdrive

Now we are ready to mount the drive to the mount point.

Mount The Drive

You can choose to have the drive mounted automatically each time you boot the computer, or manually only when you need to use it.

Automatic Mount At Boot

Note: Ubuntu now recommends to use UUID instead, see the instructions here:https://help.ubuntu.com/community/UsingUUID

gksu gedit /etc/fstab
sudo nano -Bw /etc/fstab
/dev/sdb1 /media/mynewdrive ext3 defaults 0 2
/dev/sdb1 /media/mynewdrive vfat defaults 0 2

The defaults part may allow you to read, but not write. To write other partition and FAT specific options must be used. If gnome nautilus is being used, use the right-click, mount method, from computer folder. Then launch the mount command from terminal, no options. The last entry should be the FAT drive and and look something like:

/dev/sda5 on /media/mynewdrive type vfat (rw,nosuid,nodev,uhelper=hal,shortname=mixed,uid=1000,utf8,umask=077,flush)

You can now run «sudo mount -a» (or reboot the computer) to have the changes take effect.

sudo chown -R USERNAME:USERNAME /media/mynewdrive
sudo chgrp plugdev /media/mynewdrive sudo chmod g+w /media/mynewdrive sudo chmod +t /media/mynewdrive

The last «chmod +t» adds the sticky bit, so that people can only delete their own files and sub-directories in a directory, even if they have write permissions to it (see man chmod).

Manually Mount

Alternatively, you may want to manually mount the drive every time you need it.

For manual mounting, use the following command:

sudo mount /dev/sdb1 /media/mynewdrive

When you are finished with the drive, you can unmount it using:

sudo umount /media/mynewdrive

That’s it

Need Additional Help?

IconsPage/question.png

  • If you run into problems or need more help, search the wiki or forums at http://ubuntuforums.org. If you cannot find what you are looking for, simply ask for help.

InstallingANewHardDrive (последним исправлял пользователь caconym 2023-06-12 18:45:04)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Источник https://losst.pro/montirovanie-diska-v-linux

Источник https://help.ubuntu.com/community/InstallingANewHardDrive

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *