Mount external hard drive linux

Ubuntu Documentation

Introduction

This page explains how to use USB drives, like external hard disks and USB flash drives (aka USB sticks, thumb drives, pen drives, etc). The material here also applies to flash cards (like in your digital camera).

USB storage devices have the enormous advantage that for the most part they use a standard set of protocols. Thus, instead of needing individual drivers, as does much computer hardware, a standard driver permits access to the devices, making them very portable and able to easily work on many platforms.

For help with internal hard drives, see Fstab and MountingWindowsPartitions.

Automounting

Mounting

By default, storage devices that are plugged into the system mount automatically in the /media/ directory, open a file browser window for each volume and place an icon on your desktop. The rationale for this slight change of behavior can be found here. If you plug in a usb hard disk with many partitions, all of the partitions will automatically mount. This behaviour may not be what you want; you can configure it as shown below.

If the volumes have labels the icons will be named accordingly. Otherwise, they will be named «disk», «disk-1» and so on.

To change the volume label see RenameUSBDrive.

Configuring Automounting

To enable or disable automount open a terminal and type:

Browse to org.gnome.desktop.media-handling.

The automount key controls whether to automatically mount media. If set to true, Nautilus will automatically mount media such as user-visible hard disks and removable media on start-up and media insertion.

Another key, org.gnome.desktop.media-handling.automount-open, controls whether to automatically open a folder for automounted media.

If set to true, Nautilus will automatically open a folder when media is automounted. This only applies to media where no known x-content type was detected; for media where a known x-content type is detected, the user configurable action will be taken instead. This can be configured as shown below.

Configuring Program Autostart

To control which programs automatically start when you plug in a device, go to System-Settings — Details — Removable Media.

For more complex scenarios, see UsbDriveDoSomethingHowto.

Unmounting/Ejecting

Before you disconnect the device, don’t forget to unmount it. This can be done in one of the following ways:

  • Right-click the desktop icon and select «Unmount» (or in some cases, «Eject»).
  • In the file manager window, click on the «eject» button next to the name of the mounted volume.
  • Right-click the icon in the launcher and select «Unmount».

Auto-mounting (Ubuntu Server)

By default, disk drives do not auto-mount in Ubuntu Server Edition. If you are looking for a lightweight solution that does not depend on HAL/DBUS, you can install «usbmount».

Manually Mounting

Using Disks

Disks (the GNOME disk utility) is an application for visually managing disk drives and media. When you run it, you will see a list of your drives, including USB drives. If you click a drive on the list, you can view its details, and you can click the triangle-shaped button (Play button) to mount the drive. (This method works even when the drive does not auto-mount.)

Using mount

Get the Information

Sometimes, devices don’t automount, in which case you should try to manually mount them. First, you must know what device you are dealing with and what filesystem it is formatted with. Most flash drives are FAT16 or FAT32 and most external hard disks are NTFS. Type the following:

Find your device in the list. It is probably something like /dev/sdb1. For more information about filesystems, see LinuxFilesystemsExplained.

Create the Mount Point

Now we need to create a mount point for the device. Let’s say we want to call it «external». You can call it whatever you want, but if you use spaces in the name it gets a little more complicated. Instead, use an underscore to separate words (like «my_external»). Create the mount point:

Читайте также:  Канон 440 картридж для принтера

Mount the Drive

We can now mount the drive. Let’s say the device is /dev/sdb1, the filesystem is FAT16 or FAT32 (like it is for most USB flash drives), and we want to mount it at /media/external (having already created the mount point):

The options following the «-o» give you ownership of the drive, and the masks allow for extra security for file system permissions. If you don’t use those extra options you may not be able to read and write the drive with your regular username.

Otherwise, if the device is formatted with NTFS, run:

Note: You must have the ntfs-3g driver installed. See MountingWindowsPartitions for more information.

Unmounting the Drive

When you are finished with the device, don’t forget to unmount the drive before disconnecting it. Assuming /dev/sdb1 is mounted at /media/external, you can either unmount using the device or the mount point:

You cannot unmount from the desktop by right-clicking the icon if the drive was manually mounted.

Using pmount

There is a program called pmount available in the repositories which allows unprivileged users to mount drives as if they were using sudo, even without an entry in /etc/fstab. This is perfect for computers that have users without RootSudo access, like public terminals or thin clients.

pmount can be used with the same syntax as mount (but without sudo), or quite simply as follows:

Example:

  • This will mount the device /dev/sdb1 at /media/flash_drive.

If you leave off the label option, it will mount by default at /media/device.

To unmount the device, use pumount, like so:

For more help, see the man pages for pmount and pumount.

The Importance of Unmounting

Before disconnecting devices, you must unmount them first. This is similar to «Safely Remove» in Windows in that the device won’t unmount until data is finished being written to the device, or until other programs are finished using it. This applies to all types of storage devices, including flash drives, flash cards, external hard drives, ipods and other media players, and even remote storage like Samba or NFS shares.

Failure to unmount before disconnecting the device can result in loss of data and/or a corrupted file system. There are no exceptions to this rule. Be safe — unmount your drives before disconnecting them!

Other Useful Commands

To see a list of your USB devices (the vendor and device ID’s), run:

To see all attached storage devices and their partitions, run:

To see information about currently mounted systems, simply run:

Troubleshooting

Presented here are some common problems users encounter.

Interfering services

Two services/programs responsible for automounting might interfere and thereby prevent a successful automount and permission setting.

Example: Activating the Automount function of Nautilus while using pmount will result in read-only permissions for normal users. Either disable Nautilus’ Automount function or deinstall pmount.

Unclean LogFile

If you are mounting drives formatted with NTFS (like most external USB hard disks are), you must first have the ntfs-3g driver installed. This is done automatically in newer versions of Ubuntu. You should also install ntfs-config and enable mounting, which is not done automatically. For ntfs-3g and ntfs-config, see MountingWindowsPartitions.

When a drive is not Safely Removed from a Windows machine (or a forced shutdown occurs from Windows), you may get an error like this when you plug in your drive:

The best option is Choice 1, but you can force the mount by running Choice 2 with sudo. You must then manually unmount it from the terminal (you can’t right click the desktop icon):

After that the drive should automount normally again.

User Privileges

If your usb device doesn’t appear on your desktop, you should check that your user has the correct privileges. Go to System->Administration->User and Groups, choose the user, click on «Properties», then go to the «User Privileges» tab. You should have the «Access external storage devices automatically» option checked.

Preferences

If your usb device doesn’t appear on your desktop, you should check that the automount action is enabled in the preferences:

Navigate to System->Preferences->Removable Drives and Media

  • Verify that all «Mount removable drives when. » are checked.
  • Читайте также:  Linux кто потребляет сеть

    NOTE: This does not seem to apply to Hardy Heron.

    USB 2 Issues

    old kernels workaround

    If you encounter problems using your USB device with USB 2 (i.e. ‘high speed’ mode), you can revert to the ‘full speed’ mode (slower) by unloading ehci_hcd. To do that, type in a terminal:

    before plugging in your device.

    recent kernels workaround, from Karmic

    ehci_hcd is now built into the kernel and cannot be load/unloaded using modprobe. To revert a connected device from (failing) high-speed to full-speed:

    • Determine your device id using
    • Find which bus it is connected to. The bus id can be found as a folder in /sys/bus/pci/drivers/ehci_hcd. The following script explores buses and connected devices: The information is also usually available in /var/log/kern.log
    • Unbind the bus (and all devices) from the ehci_hcd driver. Insert the bus id in the following command, using the format 0000:00:xx.x

    Buffer I/O Errors

    If you see errors related to Buffer I/O when attaching a USB storage device, there are two ways to work around it. First, try using varying max_sectors settings, as such:

    Try values of 120, 64 and 32.

    If this does not resolve the issue, then you may need an unusual_dev entry for your device. It would look something like this:

    The vendor and device IDs can be obtained from the output of «lsusb». The entry would be placed in drivers/usb/storage/unusual_devs.h. If you cannot compile your own kernel, please file a bug report, and we’ll attempt to compile a test module for you.

    Device suddenly becomes read-only

    If your device changes suddenly to read-only mode, and you see this kind of error:

    This might be the sign of an unclean device. You should check your device. Try TestingStorageMedia to do so. Or use «Disk Utility» (under System, Administration), find your device, unmount it, check the file system, then mount it again.

    USB-Device is or becomes read-only without errors

    If you see «Write Protect is off» and no errors in your logfiles, than you should set filesystem type specific mount options (FS_MOUNTOPTIONS) in /etc/usbmount/usbmount.conf. Wrong gid causes mounting read only.

    General tip

    When you encounter problems with USB devices, the first thing to do is to check the latest debug information generated from the kernel just after you plug in your device and/or just after you encounter the problem.
    To do that, open a terminal and type :

    Check the latest messages; they should be related to your problem.

    Seeking Further Help

    The best place to get help with almost any Ubuntu problem is on the Ubuntu Forums. The Absolute Beginner Talk section is best for beginners.

    Other Resources

    Some other related material:

    Источник

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

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

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

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

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

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

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

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

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

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

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

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

    Читайте также:  Касперский код ошибки 0x0007

    Опции задают различные дополнительные особенности работы утилиты. Опция -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 работает точно так же:

    Посмотреть список всех примонтированных устройств можно просто выполнив 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. Если у вас остались вопросы, спрашивайте в комментариях!

    Источник

    Поделиться с друзьями
    КомпСовет
    Adblock
    detector