Как примонтировать диск в linux
Перейти к содержимому

Как примонтировать диск в linux

  • автор:

A. Partitioning (for >2GB Harddisk) (New) (Updated on 18 Jan 2020)

Sik-Ho Tsang

2. But we cannot mount it right now, if we mount it now, errors will come out. We need to partition it first, we use parted to partition:

3. Within the parted, type the following to have gpt partition, gpt can allow partition larger than 2GB:

4. Set the size for partition, I here partition from 0GB to 4GB:

5. Then quit the parted:

B. Formatting

  1. Format the newly partitioned harddisk:

C. Mounting (including auto mount after reboot)

  1. Usually drive is mounted in /mnt/. Create a new directory in /mnt/ first.

2. Then we can mount it by:

3. But we need to mount it for every time we reboot. To mount it automatically after each reboot, I use nano to modify the file /etc/fstab:

4. Enter following at the end of file:

The first item is the path for the hard drive. The second one is the destination for the mounted drive, where we want to mount. The third one is the format type. The forth to sixth one I just kept as defaults, 0 and 0.

D. Checking whether the hard drive is mounted

To check if the drive sdb, is mounted? Use mount command:

  • mount

E. Unmounting (Updated on 05 May 2020)

To unmount, simply using the umount command:

But sometimes, the mounted harddisk maybe still in use which makes you cannot unmount. To unmount under this condition, there is a lazy mode:

F. Partitioning Using fdisk (for <2GB Harddisk) (Old)

  1. First, after connecting the harddisk to the computer by SATA and power cables, we can check the new 4-TB harddisk by:

2. But we cannot mount it right now, if we mount it now, errors will come out. We need to partition it first:

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

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

Существуют совершенно разные методы монтирования дисков в Linux, однако начинающим пользователям проще всего будет взаимодействовать с программами, в которых присутствует графический интерфейс. Одним из таких решений является GParted, по умолчанию установленное во многих популярных дистрибутивах. Предлагаем начать именно с него.

  1. Запустите операционную систему и отыщите GParted через меню приложений. Запуск осуществляется стандартным кликом по соответствующему значку. Запуск утилиты GParted в Linux через меню приложений
  2. Для открытия подобных приложений всегда требуется подтверждение подлинности, поэтому придется ввести пароль от root, чтобы запустить окно. Подтверждение запуска утилиты GParted в Linux через меню приложений
  3. Здесь отыщите необходимый раздел или физический накопитель, ориентируясь по его названию, файловой системе или размеру. Щелкните по выбранной строке правой кнопкой мыши. Выбор раздела или диска в утилите GParted в Linux для монтирования

Точно таким же образом осуществляется подключение любых съемных носителей, встроенных жестких дисков или отдельных логических разделов. В большинстве случаев эта операция проходит успешно, но если какая-то ошибка и появится, вы получите соответствующее уведомление с инструкциями по ее решению.

Способ 2: Стандартная утилита «Диски»

В большинстве популярных дистрибутивов имеется стандартная утилита под названием «Диски». Именно она и отвечает за управление накопителями. Если приведенного выше решения на ПК не оказалось или оно вам не подходит, выполните такие действия:

  1. Воспользуйтесь меню приложений, чтобы отыскать соответствующую утилиту. Запустите ее, нажав по значку. Запуск утилиты Диски в Linux для монтирования раздела
  2. Здесь просмотрите существующие разделы. Можно назвать на кнопку в виде шестеренки, чтобы изучить дополнительные параметры и выбрать необходимый логический том для монтирования. Выбор раздела в утилите Диски в Linux для монтирования
  3. После выбора остается только нажать на значок в форме треугольника, который и отвечает за подключение. Кнопка для монтирования раздела или носителя в утилите Диски в Linux

Как видите, ничего сложного в использовании упомянутой утилиты нет. Юзеру необходимо только определиться с накопителем и нажать на специально отведенную кнопку, чтобы монтирование прошло успешно.

Способ 3: Терминальная команда

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

  1. Запустите «Терминал» удобным для вас образом, например, горячей клавишей Ctrl + Alt + T или через меню приложений. Переход к терминалу для использования стандартной команды монтирования в Linux
  2. Введите команду sudo mount -v /dev/sda2 /mnt/ , где /dev/sda2 — название необходимого диска, а /mnt/ — точка монтирования. Использование команды для монтирования диска в Linux
  3. Подтвердите данное действие, введя пароль суперпользователя. Это требуется, поскольку для активации команды был использован аргумент sudo. Подтверждение монтирования диска через терминал Linux
  4. Вы будете уведомлены о том, что данная операция завершена успешно. Успешное монтирование диска через терминал в Linux

Если вы не знаете точное название диска или логического тома, чтобы вписать его в строку, понадобится заранее уточнить эту информацию. Осуществляется поставленная задача тоже при помощи стандартных терминальных команд. Ориентироваться в выводах можно по размеру тома или его заполненности. Более детально о данной теме написано в отдельной статье на нашем сайте по следующей ссылке.

Дополнительно отметим, что у команды mount есть множество полезных опций, позволяющих установить параметры монтирования. Рекомендуем ознакомиться с основными из них:

Опции Описание
-r Подключение в формате только для чтения
-w Монтирование с возможностью чтения и записи
-c Использование абсолютных путей
-t ext4 Монтирование файловой системы. Здесь ext4 следует заменить на необходимую ФС
-a Монтирование всех разделов и носителей, указанных в fstab

Теперь вы знакомы с одной из основных команд в Linux под названием mount и знаете, что она отвечает за подключение дисков. В следующем способе мы тоже будем задействовать эту утилиту, но в немного необычной и более сложной ситуации.

Способ 4: Монтирование окружения в режиме LiveCD

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

    Загрузите компьютер с LiveCD версией дистрибутива. Более детально об этом читайте в официальной документации по приведенной далее ссылке.

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

В этой статье вы узнали о принципах монтирования дисков в Linux. После этого можно смело переходить к их использованию. На нашем сайте имеются отдельные темы, посвященные этому процессу. Предлагаем прочитать их, перейдя по указанным ниже ссылкам.

Linux mount Command with Examples

The Linux file system hierarchy is arranged in a tree, with the file system starting from the root directory ( / ). All other child file systems branch out from the root directory.

The mount command allows users to mount, i.e., attach additional child file systems to a particular mount point on the currently accessible file system. The command passes the mount instructions to the kernel, which completes the operation.

This tutorial will teach you the basics of attaching file systems in Linux using the mount command.

Linux mount command with examples.

  • A system running Linux.
  • Access to the terminal (Ctrl + Alt + T).
  • A user account with administrator privileges.

Linux mount Command Syntax

The standard mount command syntax is:

The command instructs the kernel to attach the file system found on [device] at the [dir] directory. The -t [type] option is optional, and it describes the file system type (EXT3, EXT4, BTRFS, XFS, HPFS, VFAT, etc.).

If the destination directory is omitted, it mounts the file systems listed in the /etc/fstab file.

While the file system is mounted, the previous contents, owner, and mode of the [dir] directory are invisible, and the [dir] pathname refers to the file system root.

Exit Status

The mount command returns one of the following values that indicate the process completion status:

  • 0 . Success.
  • 1 . Incorrect command invocation or insufficient permissions.
  • 2 . System error.
  • 4 . Internal mount bug.
  • 8 . Operation interrupted by user.
  • 16 . Issues with writing or locking the /etc/mtab file.
  • 32 . Mount failure.
  • 64 . At least one mount operation succeeded, but not all.

mount Command Options

The mount command options further specify file system types, mount location, and type. The following table shows the most common mount options:

Listing mounted file systems using the mount command.

List Specific File Systems

The -t option allows users to specify which file systems to display when running the mount command. For example, to show only ext4 file systems, run the following command:

Listing only specific file systems using mount.

Mount a File System

Mounting a file system requires the user to specify the directory or mount point to which the file system will be attached. For example, to mount the /dev/sdb1 file system to the /mnt/media directory, run:

To specify additional file system-specific mount options, pass the -o flag followed by the options before the device name. Use the following syntax:

See the man page or help file for a complete list of available options.

Mount File System with /etc/fstab

The /etc/fstab file contains lines describing the mount location of system devices and the options they are using. Generally, fstab is used for internal devices, such as CD/DVD devices, and network shares (samba/nfs/sshfs). Removable devices are typically mounted by the gnome-volume-manager .

Providing only one parameter (either [dir] or [device] ) causes mount to read the contents of the /etc/fstab configuration file to check if the specified file system is listed in it. If the given file system is listed, mount uses the value for the missing parameter and the mount options specified in the /etc/fstab file.

The defined structure in /etc/fstab is:

The following screenshot shows the contents of the /etc/fstab file:

Showing the contents of the /etc/fstab configuration file.

To mount a file system specified in the /etc/fstab file, use one of the following syntaxes:

  • For [dir] , specify the mount point.
  • For [device] , specify the device identifier.

See the mount command man page or run man mount for a comprehensive list of file system-specific and file system-independent options.

Mount USB Drive

Modern Linux distributions automatically mount removable drives after insertion. However, if the automatic mount fails, follow the steps below to mount the USB drive manually:

1. Create a mount point using the mkdir command:

2. Find the USB device and file system type. Run:

Listing partitions using fdisk in Linux.

3. Using the device identifier from fdisk output, mount the USB drive using the following syntax:

For example, if the device is listed as /dev/sdb1 , run:

Mount a CD-ROM

Being a removable device, Linux automatically mounts CD-ROMs as well. However, if mounting fails, mount a CD-ROM manually by running:

Make sure that the /mnt mount point exists for the command to work. If it doesn’t, create one using the mkdir command.

iso9660 is the standard file system for CD-ROMs, while the -o ro options cause mount to treat it as a read-only file system.

Mount ISO Files

Mounting an ISO file requires mapping its data to a loop device. Attach an ISO file to a mount point using a loop device by passing the -o loop option:

Mount an NFS

A Network File System (NFS) is a distributed file system protocol for sharing remote directories over a network. Mounting an NFS allows you to work with remote files as if they were stored locally.

Follow the steps below to mount a remote NFS directory on your system:

Important: Mounting an NFS requires having the NFS client package installed. See how to install the NFS server on Ubuntu.

1. Create a mount point using the mkdir command:

2. Mount the NFS share by running:

3. To automatically mount the remote NFS share at boot, edit the /etc/fstab file using a text editor of your choice:

Add the following line to the file and replace remote.server:/dir with the NFS server IP address or hostname and the exported directory:

Non-Superuser Mounting

Although only a superuser can mount file systems, file systems in the /etc/fstab file containing the user option can be mounted by any system user.

Edit the /etc/fstab file using a text editor and under the <options> field specify the user option. For example:

Adding the line above to /etc/fstab allows any system user to mount the iso9660 file system from a CD-ROM device.

Specifying the users option instead of user allows any user to unmount the file system, not only the user that mounted it.

Move a Mount

If you decide to move a mounted file system to another mount point, use the -M option. The syntax is:

For [olddir] , specify the current mount point. For [newdir] , specify the mount point to which you want to move the file system.

Moving the mounted file system to another mount point causes its contents to appear in the [newdir] directory but doesn’t change the physical location of the files.

How to Unmount a File System

To unmount, i.e., detach an attached file system from the system tree, use the umount command. Detach the file system by passing either its mount point or the device name.

For example, to detach a USB device listed as /dev/sdb1 , run:

While busy with open files or ongoing processes, a file system cannot be detached, and the process fails. If you aren’t sure what’s using the file system, run the fuser command to find out:

For [dir] , specify the file system mount point. For example:

Listing processes currently using a device.

The output lists the PIDs of processes currently accessing the device. Stop the processes and unmount the file system.

Lazy Unmount

If you don’t want to stop the processes manually, use the lazy unmount, which instructs the unmount command to detach the file system as soon as its activities stop. The syntax is:

Forced Unmount

The -f ( —force ) option allows users to force an unmount. However, be cautious when force unmounting a file system as the process may corrupt the data on it.

This tutorial showed how to use the mount command to attach various file systems to the directory tree and provided other practical examples. The tutorial also showed how to use the umount command to detach a file system.

Next, we recommend you to read about the fsck command for checking and repairing file systems, or see how to check disk space in Linux.

Способы монтирования

Способ 1: монтирование через универсально уникальный идентификатор (UUID)

UUID — это атрибут конкретной файловой системы, а не произвольное число, зависящее от физического порядка подключения дисков или случайностей инициализации дисковой подсистемы ядром.

Узнаем UUID разделов, для этого

Предположим, мы хотим подключить раздел «Shared» (NTFS-раздел, находящийся на основном диске компьютера) и «TRENDNET8GB» (флэшка, отформатированная в FAT32).

Способ 2: монтирование через имена устройств

Считается устаревшим и строго не рекомендуется к постоянному использованию.

Единственным заметным плюсом является небольшая длина имён устройств, что удобно при прямой работе с консолью. Например, во время реанимации умершей системы.

Разделы, оканчивающиеся цифрой — файловые системы. Разделы без цифры на конце — реальные физические устройства. В данном примере участвуют два физических диска (/dev/sda и /dev/sdb) и два рейд-массива (по сути — две файловые системы, не привязанные напрямую к какому-то одному физическому носителю).

Пример вывода команды fdisk (вывод parted отличается очень незначительно):

Попробуем достучаться до массива md0.

Дополнительная информация

Я не стал загружать основной текст статьи расшифровкой опций монтирования, но несколько слов пояснения сказать необходимо.

Донастройка системы

Теперь диски стали подключаться автоматически, но так как это делается от имени root, у нас пропала возможность на подключенных дисках давать права на общий доступ, чтобы восстановить эту возможность добавим настройку в Samba:

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

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