Куда монтируется флешка в linux
Перейти к содержимому

Куда монтируется флешка в linux

  • автор:

Чем и куда монтируются флешки

До появления в линуксе автомонтирования флешек всё было понятно: идёшь в /mnt и монтируешь.

В современных дистрибутивах всё как-то постоянно меняется: то монтируют в /media, то в /media/username/, то в ~/media. я до 5 вариантов насчитал. Бывает так, что я флешку воткнул, система показала нечто, похожее на проводник, а чтобы понять, куда оно действительно смонтировалось и открыть в любимом двухпанельнике, надо смотреть /etc/mtab.

Ни к какому знаменателю это не пришло? Стандартов нет? И как вывести алгоритм, от чего это зависит? Демоны автомонтирования разные? Я читаю про всякие udev, udisks2, окончательно запутался, вроде ещё systemd добавил что-то своё.

Подопытные дистрибутивы — самые разные, от дебиана до опензюзи.

И я так понимаю, что KDE и Gnome подкладывают этим демонам свои события, а если у меня какой-то лёгкий WM? Что и кому подкладывать? Вообще, какой процесс в 2017 году отвечает за автомонтирование сменных носителей в линуксе (для определённости возьмём дистры с systemd), и как с ним разговаривать?

Извините за сумбур, но судя по разнообразию вариантов он, похоже, не только у меня в голове.

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:

dconf-editor

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

  • 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:

sudo fdisk -l

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:

sudo mkdir /media/external

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):

sudo mount -t vfat /dev/sdb1 /media/external -o uid=1000,gid=1000,utf8,dmask=027,fmask=137

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:

sudo mount -t ntfs-3g /dev/sdb1 /media/external

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:

sudo umount /dev/sdb1
sudo umount /media/external

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:

pmount [ label ]
pmount /dev/sdb1 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:

pumount

pumount /dev/sdb1

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:

lsusb

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

sudo fdisk -l

To see information about currently mounted systems, simply run:

mount

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:

$LogFile indicates unclean shutdown (0, 0) Failed to mount '/dev/sda1': Operation not supported Mount is denied because NTFS is marked to be in use. Choose one action: Choice 1: If you have Windows then disconnect the external devices by clicking on the 'Safely Remove Hardware' icon in the Windows taskbar then shutdown Windows cleanly. Choice 2: If you don't have Windows then you can use the 'force' option for your own responsibility. For example type on the command line: mount -t ntfs-3g /dev/sda1 /media/sda1/ -o force

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):

sudo umount

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

  • Navigate to System->Preferences->Removable Drives and Media
  • Verify that all «Mount removable drives when. » are checked.

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:

sudo rmmod ehci_hcd

before plugging in your device.

recent kernels workaround, from Karmic

    Determine your device id using

lsusb
pushd /sys/bus/pci/drivers/ehci_hcd > /dev/null for bus in 0000. ; do echo "ehci_hcd bus $bus" pushd $bus/usb1 > /dev/null for dev in ?-?; do idVendor=`cat $dev/idVendor` idProduct=`cat $dev/idProduct` echo "ehci_hcd bus $bus: device $dev = $idVendor:$idProduct" done popd > /dev/null done popd > /dev/null
sudo sh -c 'echo -n "0000:00:xx.x" > unbind'

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:

sudo sh -c "echo 120 > /sys/block/sda/queue/max_sectors_kb"

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:

UNUSUAL_DEV(0x03eb , 0x2002, 0x0100, 0x9999, "Generic", "MusicDrive", US_SC_DEVICE, US_PR_DEVICE, NULL, US_FL_IGNORE_RESIDUE),

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:

[17183798.908000] FAT: Filesystem panic (dev sda1) [17183798.908000] fat_get_cluster: invalid cluster chain (i_pos 0) [17183798.908000] File system has been set read-only

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 :

dmesg

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

  • RenameUSBDrive
  • BootFromUSB
  • UsbDriveDoSomethingHowto
  • http://en.wikipedia.org/wiki/USB_flash_drive
  • DebuggingUSBStorage

Mount/USB (последним исправлял пользователь CPE503955526a2d-CM503955526a2a 2015-06-02 00:24:50)

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

Переход на съёмный носитель в терминале

С помощью команды cd я могу переходить по каталогам и с помощью команды ls смотреть содержимое. А вот как перейти мне на съёмный носитель и посмотреть его содержимое в терминале?

Litrabol ★
25.01.15 10:22:23 MSK

Куда он примонтирован — туда и переходи.

Ceiling_QB ★★★★
( 25.01.15 10:25:46 MSK )
Последнее исправление: Ceiling_QB 25.01.15 10:27:43 MSK (всего исправлений: 1)

Ответ на: комментарий от Ceiling_QB 25.01.15 10:25:46 MSK

а с помощью какой команды?

Litrabol ★
( 25.01.15 10:27:46 MSK ) автор топика
Ответ на: комментарий от Litrabol 25.01.15 10:27:46 MSK
Ceiling_QB ★★★★
( 25.01.15 10:32:12 MSK )
anonymous
( 25.01.15 10:34:41 MSK )

флешки положено в /media/ монтировать, точнее создавать там новый каталог, и монтировать к нему. Имя каталога обычно берётся из volue lable, а если ты его не удосужился забить, то UUID.

Монтирование осуществляет файловый менеджер, часть DE.

Можно ручками смонтировать, но по умолчанию это может сделать только root. Имя самого устройства можно узнать командой dmesg.

emulek ★
( 25.01.15 10:42:18 MSK )
Ответ на: комментарий от anonymous 25.01.15 10:34:41 MSK

ну ты-то наверное как из ЖПП вылез, уже сразу начал правила к udev писать, и юниты к systemd.

emulek ★
( 25.01.15 10:43:54 MSK )
Ответ на: комментарий от emulek 25.01.15 10:42:18 MSK

флешки положено в /media/ монтировать

Есть тренд добавлять имя пользователя в качестве субдиректориии.

tlx ★★★★★
( 25.01.15 10:54:27 MSK )

Часто монтируется в /run/media//

Ake ★
( 25.01.15 10:55:26 MSK )

всем спасибо перешёл на флешку с помощью команды

cd /media/имя устройства

Litrabol ★
( 25.01.15 11:01:32 MSK ) автор топика
Ответ на: комментарий от emulek 25.01.15 10:43:54 MSK

oh stop it, you.jpg

anonymous
( 25.01.15 11:11:29 MSK )
Ответ на: комментарий от tlx 25.01.15 10:54:27 MSK

Есть тренд добавлять имя пользователя в качестве субдиректориии.

да, это логично, т.к. флешки принадлежат юзеру, а /media/ принадлежит системе.

emulek ★
( 25.01.15 12:36:25 MSK )

Вот к чему приводит дос головного мозга и полное незнание архитектуры GNU/Linux.

Zhbert ★★★★★
( 25.01.15 12:39:20 MSK )
Ответ на: комментарий от emulek 25.01.15 12:36:25 MSK

да, это логично, т.к. флешки принадлежат юзеру, а /media/ принадлежит системе.

Никогда не понимал, что в этом логичного. Ну вот вставил я флешку в комп, она же торчит в компе. Почему только один юзер, который был активным в момент вставки, имеет право ей пользоваться? Почему бы не смонтировать её в /media/$UUID и не дать права 770, root:plugdev на её точку монтирования?

gentoo_root ★★★★★
( 25.01.15 12:49:52 MSK )
Ответ на: комментарий от gentoo_root 25.01.15 12:49:52 MSK

потому что нельзя отличить, флешка конкретного пользователя это, с его голыми детьми, или публичная

anonymous
( 25.01.15 12:52:11 MSK )
Ответ на: комментарий от anonymous 25.01.15 12:52:11 MSK

Хм, довольно убедительно.

gentoo_root ★★★★★
( 25.01.15 12:58:11 MSK )
Ответ на: комментарий от gentoo_root 25.01.15 12:49:52 MSK

Почему бы не смонтировать её в /media/$UUID и не дать права 770, root:plugdev на её точку монтирования?

это вроде-бы можно сделать, но я полагаю, что это не нужно. У меня например есть «семейный» десктоп, которым пользуется вся семья. Если жена вставляет флешку, то она же её и вынимает. Просто непонятно, зачем мне вынимать флешку жены? А в случае, если жена накосячила, и забыла вынуть, и ушла, то тут вообще-говоря нужно вмешательство системного администратора, дети не имеют право вынимать, ибо может может мама туда что-то закачивает и т.п. Ежели вынуть, то жена будет недовольна, даже если я выну. Не, я могу конечно получить права рута, и посмотреть, что там флешку жены юзает, ежели уж так надо, но зачем? Дырок USB в нашем системнике полно, на всех хватает.

Короче, я не вижу пользы в твоём юз-кейсе на практике. И, очевидно, не только я, если такой дефолт.

emulek ★
( 25.01.15 13:44:11 MSK )
Ответ на: комментарий от anonymous 25.01.15 12:52:11 MSK

потому что нельзя отличить, флешка конкретного пользователя это, с его голыми детьми, или публичная

только дебилы хранят на флешках личную информацию в открытом виде.

How do I mount an SD card?

My computer has an SD card slot. When I put a working SD card into the slot, nothing happens. When I put a CD or DVD in, or plug in a USB drive, the medium is mounted and available. Is there something special I need to do for SD cards? Hardware specifics I am running 11.10 on a Dell XPS L502X. The card slot is marked «SDXC/MMC — MS/Pro» (which Wikipedia tells me are various SD card types).

lofidevops
asked Jan 14, 2012 at 14:07
lofidevops lofidevops
20.7k 30 30 gold badges 106 106 silver badges 168 168 bronze badges

Normally you don’t need to do anything special. Could you update the question to include the version of Ubuntu you’re using? Also, you can open a terminal (ctrl-alt-t), type «tail -f /var/log/syslog», insert an SD card, and see what messages pop up. If you don’t know what they mean you could paste the lines that appear when you insert the SD card in your question too. All this info is helpful to see what may be wrong with your card reader.

Jan 14, 2012 at 15:46

@roadmr I was going to post the results from syslog along with Huckle’s suggestions, but when I plugged the SD card in. nothing happened! I may be missing something, but based on the output from the commands below, I think it doesn’t even know the slot is there

Jan 20, 2012 at 15:54

Could you please update the question with your computer’s make/model, version of Ubuntu, as well as the output of running «sudo lspci -nn». We can then check if your card reader is supported by your Ubuntu version.

Jan 20, 2012 at 16:50
@roadmr updated, and included the briefer lspci output in gist.github.com/77efea8cb1e4ca6eae1a
Jan 20, 2012 at 17:13

thanks, I don’t see the card reader in lspci output, so maybe it’s connected to the USB bus, could you post output of lsusb? then again, it’s rare for USB card readers to not work at all..

Jan 20, 2012 at 21:17

7 Answers 7

I have the same laptop, the slot does work on Ubuntu 12.04, but the OS doesn’t seem to find the card when it is inserted. It appears you have 2 options in the short term:

  1. Reboot with the SDcard in the slot.
  2. Do a PCI re-scan

echo 1 | sudo tee /sys/bus/pci/rescan 

The bug with the workaround is listed here.

3,769 20 20 silver badges 33 33 bronze badges
answered Jun 14, 2012 at 16:43
Jim OLeary Jim OLeary
644 6 6 silver badges 4 4 bronze badges
In the second option, the redirection ( > ) should have been a pipe ( | ). Edited.
Jul 16, 2014 at 2:08
What should I do after the second point? BTW, I have 1 as an output.
Dec 23, 2017 at 7:26

There are a few things you can do to make sure everything is working as expected.

1) Verify that Ubuntu knows about your SD card slot and what to do with it
2) Verify that Ubuntu knows you inserted something
3) Verify that Ubuntu understands the filesystem on the thing you inserted.

1) Check the outputs of the commands sudo lspci -v -nn , sudo lsusb , and sudo lshw on the command line. Here is a good guide for understanding lshw which lists an example SD Card reader.

2) Then run the following command before inserting the SD card and a few seconds after inserting it: ls -la /dev/sd* . This command lists all of the hard drives, CDs, DVDs, floppies, SD cards, etc that Ubuntu knows about. (These are called Block Devices).

Ideally you will see a few entries on the second run that you don’t see on the first. For example:

$ls -la /dev/sd* brw-rw---- 1 root disk 8, 0 2012-01-14 11:27 /dev/sda brw-rw---- 1 root disk 8, 16 2012-01-14 11:27 /dev/sdb brw-rw---- 1 root disk 8, 32 2012-01-14 11:27 /dev/sdc brw-rw---- 1 root disk 8, 33 2012-01-14 11:27 /dev/sdc1 brw-rw---- 1 root disk 8, 34 2012-01-14 11:27 /dev/sdc2 brw-rw---- 1 root disk 8, 35 2012-01-14 11:27 /dev/sdc3 brw-rw---- 1 root disk 8, 36 2012-01-14 11:27 /dev/sdc4 brw-rw---- 1 root disk 8, 37 2012-01-14 11:27 /dev/sdc5 (Now insert the SD card) $ls -la /dev/sd* brw-rw---- 1 root disk 8, 0 2012-01-14 11:27 /dev/sda brw-rw---- 1 root disk 8, 16 2012-01-14 11:27 /dev/sdb brw-rw---- 1 root disk 8, 32 2012-01-14 11:27 /dev/sdc brw-rw---- 1 root disk 8, 33 2012-01-14 11:27 /dev/sdc1 brw-rw---- 1 root disk 8, 34 2012-01-14 11:27 /dev/sdc2 brw-rw---- 1 root disk 8, 35 2012-01-14 11:27 /dev/sdc3 brw-rw---- 1 root disk 8, 36 2012-01-14 11:27 /dev/sdc4 brw-rw---- 1 root disk 8, 37 2012-01-14 11:27 /dev/sdc5 brw-rw---- 1 root disk 8, 64 2012-01-14 11:28 /dev/sdd 

See that extra one at the end /dev/sdd that is the SD card.

3) Check that Ubuntu understands the filesystem on the drive. I would bet it is either Fat32 or NTFS. You can check if your copy of Ubuntu understands those filesystems (it should) by running this command: cat /proc/filesystems . In this list vfat is Fat32 and (for all intents and purposes) fuse is NTFS. **Note: this list is not extensive.

A better way is to simply try to mount the SD card manually. Run the following commands in order until one works (replace the X in /dev/sdX1 with the letter from step 2):

sudo mount /dev/sdX1 /mnt sudo mount -t vfat /dev/sdX1 /mnt sudo mount -t ntfs /dev/sdX1 /mnt sudo mount -t msdos /dev/sdX1 /mnt 

No output means it worked, and you should be able to navigate to your SD card with nautilus at /mnt . If none of them worked, try plugging your SD card into a windows machine and running chkdsk on it, or verify the filesystem type.

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

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