Посмотреть содержимое флешки linux

Как посмотреть USB устройства Linux

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

Каждому новичку важно уметь идентифицировать подключенные устройства, будь то usb флешки, SD карты или жесткие диски чтобы не записать что-либо не туда или не отформатировать не тот диск. В этой статье мы рассмотрим несколько способов как посмотреть usb устройства Linux, подключенные к компьютеру.

Список подключенных устройств Linux

В операционной системе Linux используется особенная философия управления. Все объекты, в том числе и устройства считаются файлами. При подключении какого-либо устройства к системе для него создается файл в каталоге /dev/.

Обычно, после того, как вы подключили любую USB флешку или другой накопитель к системе с установленным окружением рабочего стола, устройство автоматически монтируется в папку /media/имя_пользователя/метка_устройства/, а затем вы можете получить доступ к файлам из устройства в этой папке. Тем не менее, бывают ситуации, когда вам нужно вручную монтировать USB и тогда такой вариант не поможет.

Файлы всех устройств находятся в каталоге /dev/. Здесь вы можете найти файлы sda, hda, которые представляют из себя жесткий диск, а также файлы sda1 или hda1, которые позволяют получить доступ к разделам диска. Мы уже подробно рассматривали это все в статье работа с устройствами Linux. Вы можете посмотреть список всех устройств в каталоге /dev/ с помощью команды:

usb0

Теперь осталось понять какие из этих файлов устройств принадлежат USB устройствам и каким устройствам именно.

Как посмотреть USB устройства Linux

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

usb

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

Команда lsblk отображает список всех блочных устройств, подключенных к вашему компьютеру. Утилита отображает не только их размер, но и тип (диск/раздел) а также старший и младший номер устройства. Тут уже немного проще найти флешку, мы видим два диска, и если первый с размером 698 гигабайт это жесткий диск, то второй, — точно флешка:

usb1

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

usb2

Также, узнать о подключенном USB устройстве можно посмотрев очередь сообщений ядра dmesg. Здесь хранится информация обо всех операциях, которые происходят в ядре. В том числе здесь будет отображено имя флешки, только что подключенной к компьютеру. Для просмотра сообщений ядра выполните:

usb3

Чтобы посмотреть какие из sd устройств относятся к USB используйте такую команду:

usb4

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

Читайте также:  Linux echo во все файлы

usb6

Выводы

В этой статье мы рассмотрели как посмотреть usb устройства linux, а также как узнать имя своей usb флешки в системе. Вы можете использовать любую из команд, которая вам понравилась, или же сразу несколько. Но теперь вы знаете как точно определить имя файла своей флешки.

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

Источник

How to access a usb flash drive from the terminal?

You’ll need to know what the drive is called to mount it. To do that fire off one of the following (ranked in order of my preference):

lsblk sudo blkid sudo fdisk -l 

You’re looking for a partition that should look something like: /dev/sdb1 . The more disks you have the higher the letter this is likely to be. Anyway, find it and remember what it’s called.

2. Create a mount point (optional)

This needs to be mounted into the filesystem somewhere. You can usually use /mnt/ if you’re being lazy and nothing else is mounted there but otherwise you’ll want to create a new directory:

3. Mount!

sudo mount /dev/sdb1 /media/usb 

When you’re done, just fire off:

This answer is almost 6 years old and while the core of it still works, things like fdisk -l aren’t the most user-friendly options. There are also new mechanisms in higher stacks for mounting devices in a sane and standard way which might not always be available.

So I’ve added some polish from the other answers. While you’re reading this footnote and you’re doing this on a desktop system, there definitely are arguments for using udisksctl , per wecac’s answer. This mounts in the same way the desktop does —creating your own /media/$USER/device directory— but I think there are still arguments for a static mountpoint, especially when you don’t want the path to change.

Udisks also relies on D-Bus, so might not be available everywhere.

the main disadvantage of this method is that it mounts the device as root. if the device is FAT formatted then the user won’t be able to write to it. the /media/$USER/device mountpoint will also always be the same

All answers assume that there magically appears a /dev/sdX after putting in the USB stick. What if it doesn’t? I see in the logs that it is detected, but no new /dev. lsusb show all the gory details too. Ie sudo lsusb -vs 15:2 | grep id gives idVendor 0x090c Silicon Motion, Inc. — Taiwan (formerly Feiya Technology Corp.) idProduct 0x1000 Flash Drive

@CarloWood I have faced a similar situation. In some logs, i think dmesg or something, I found that the drive was unable to power itself up. I just ended up using a different port for the drive. As far as i know there is not a way to mount a drive, whose device driver hasnt created a device file in /dev/

pmount / pumount

Install pmount . Mounts disks in /media/

pmount /dev/sdb1 pumount /dev/sdb1 

Replace «sdb1» with your specific device path. For more information see the manpage:

pmount ("policy mount") is a wrapper around the standard mount program which permits normal users to mount removable devices without a match- ing /etc/fstab entry. pmount is invoked like this: pmount device [ label ] This will mount device to a directory below /media if policy is met (see below). If label is given, the mount point will be /media/label, otherwise it will be /media/device. 

Thanks, I knew how to do the accepted answer but was looking for something a bit easier that didn’t leave me having to clear up empty folders myself.

Читайте также:  Установка ftp сервера linux

Use udisksctl from package= udisks2 (in both Ubuntu and Debian). Procedure is:

    Find the ID of the block device you want to mount, using lsblk :

user@machine:~$ lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 1.8T 0 disk ├─sda1 8:1 0 19.1M 0 part /boot/efi ├─sda2 8:2 0 1.8T 0 part └─sda3 8:3 0 16G 0 part [SWAP] sdb 8:16 0 931.5G 0 disk ├─sdb1 8:17 0 37M 0 part ├─sdb2 8:18 0 15.9G 0 part [SWAP] └─sdb3 8:19 0 915.7G 0 part / sdc 8:32 1 14.4G 0 disk └─sdc1 8:33 1 14.4G 0 part sdd 8:48 0 1.8T 0 disk └─sdd1 8:49 0 1.8T 0 part 
user@machine:~$ udisksctl mount --block-device /dev/sdc1 ==== AUTHENTICATING FOR org.freedesktop.udisks2.filesystem-mount === Authentication is required to mount Kingston DT microDuo 3C (/dev/sdc1) Multiple identities can be used for authentication: 1. XXXXX. (user) 2. . (YYYYY) Choose identity to authenticate as (1-2): 1 Password: ==== AUTHENTICATION COMPLETE === Mounted /dev/sdc1 at /media/user/USBDRIVELABEL. 

Addressing Hans Deragon’s comment below: you can also tell udisksctl to do —no-user-interaction . It does not attempt to authenticate the user, which usually «just works»:

user@machine:~$ udisksctl mount --block-device /dev/sdc1 --no-user-interaction # possibly some complaining here about I/O charset or need to run `fsck` Mounted /dev/sdc1 at /media/user/USBDRIVELABEL. 

In addition to using the standard mount command (which requires root) you can mount drives using udisks and dbus with your standard user.

To do this it is useful (but not required) to know a few things about the drive first:

Knowing these you can use a simple command to mount a drive from the command line.

gdbus call --system --dest org.freedesktop.UDisks --object-path /org/freedesktop/UDisks/devices/ --method org.freedesktop.UDisks.Device.FilesystemMount "" [] 

this call should echo the path it is mounted at if the mount succeeds.

To unmount drives mounted in this way you can run:

gdbus call --system --dest org.freedesktop.UDisks --object-path /org/freedesktop/UDisks/devices/ --method org.freedesktop.UDisks.Device.FilesystemUnmount [] 

N.B. the is simply the end of the path to it. So for example if what you want to mount is at /dev/sdb2 then you would put sdb2 in place of .

If you do not know which device it is or what filesystem it uses do not fear. You can easily print out all that information with this little command:

gdbus introspect --system --dest org.freedesktop.UDisks --object-path /org/freedesktop/UDisks/devices --recurse --only-properties | grep -E "(readonly .+ (IdLabel|IdType|Device(IsMounted|IsDrive|File) ).*|\>|.*\<)" 

This will print out something like this:

node /org/freedesktop/UDisks/devices < node /org/freedesktop/UDisks/devices/sda < interface org.freedesktop.UDisks.Device < readonly s IdLabel = ''; readonly s IdType = ''; readonly s IdUsage = ''; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sda'; >; >; node /org/freedesktop/UDisks/devices/sda1 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = 'SYSTEM'; readonly s IdType = 'ntfs'; readonly s IdUsage = 'filesystem'; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sda1'; >; >; node /org/freedesktop/UDisks/devices/sda2 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = 'Windows7'; readonly s IdType = 'ntfs'; readonly s IdUsage = 'filesystem'; readonly b DeviceIsMounted = true; readonly s DeviceFile = '/dev/sda2'; >; >; node /org/freedesktop/UDisks/devices/sda3 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = 'Recovery'; readonly s IdType = 'ntfs'; readonly s IdUsage = 'filesystem'; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sda3'; >; >; node /org/freedesktop/UDisks/devices/sda4 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = ''; readonly s IdType = ''; readonly s IdUsage = ''; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sda4'; >; >; node /org/freedesktop/UDisks/devices/sda5 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = ''; readonly s IdType = 'ext4'; readonly s IdUsage = 'filesystem'; readonly b DeviceIsMounted = true; readonly s DeviceFile = '/dev/sda5'; >; >; node /org/freedesktop/UDisks/devices/sda6 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = ''; readonly s IdType = 'swap'; readonly s IdUsage = 'other'; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sda6'; >; >; node /org/freedesktop/UDisks/devices/sda7 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = ''; readonly s IdType = 'ext4'; readonly s IdUsage = 'filesystem'; readonly b DeviceIsMounted = true; readonly s DeviceFile = '/dev/sda7'; >; >; node /org/freedesktop/UDisks/devices/sdb < interface org.freedesktop.UDisks.Device < readonly s IdLabel = ''; readonly s IdType = ''; readonly s IdUsage = ''; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sdb'; >; >; node /org/freedesktop/UDisks/devices/sdb1 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = 'USB DRIVE'; readonly s IdType = 'vfat'; readonly s IdUsage = 'filesystem'; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sdb1'; >; >; node /org/freedesktop/UDisks/devices/sr0 < interface org.freedesktop.UDisks.Device < readonly s IdLabel = ''; readonly s IdType = ''; readonly s IdUsage = ''; readonly b DeviceIsMounted = false; readonly s DeviceFile = '/dev/sr0'; >; >; >; 

Those that have IdUsage = 'filesystem' may be mounted using the above command.

Читайте также:  Linux vmx disabled by bios

This means that, for example, if i wanted to mount the device 'USB DRIVE' i would run the command

gdbus call --system --dest org.freedesktop.UDisks --object-path /org/freedesktop/UDisks/devices/sdb1 --method org.freedesktop.UDisks.Device.FilesystemMount "vfat" [] 

These commands all work using the dbus messaging system, the same way that Nautilus and other file managers auto-mount things. In these commands we are sending various objects (i.e. /org/freedesktop/. messages asking them to mount and unmount certain devices. They might or might not do this depending on the permissions one has been given in PolicyKit .

Using similar commands one can control almost every aspect of ones experience in Ubuntu and simulate most system programs and functions (i.e. shutdown, volume change, etc.).

Источник

Зайти на флешку в linux

Все привет. Нужно зайти на флешку в терминале путь:/dev/ttyUSB0 Подскажите, пожалуйста, как это можно сделать?

3 ответа 3

/dev/ttyUSB0 - это как бы более низкий уровень доступа к флешке. Устройство для флешки скорее всего будет выглядеть немного по другому. Самый простой способ найти - это вставить флешку и сразу в терминале запустит команду dmesg. Там в конце должно быть что то вида

new high-speed USB device number 7 using xhci_hcd 

это значит, что как минимум само устройство было распознано на низком уровне.

Чуть ниже будет где то такое

New USB device found, idVendor=1111, idProduct=1234, bcdDevice= 1.00 

и смотрим ещё ниже по тексту и там должно быть такое

[sde] 121438208 512-byte logical blocks: (62.2 GB/57.9 GiB) 

это значит, что флешка (диск) найдены, размер виден и известно имя - sde (у Вас, естественно, может быть другое). Но только sde - это название всей флешки, а конкретный раздел на флешке будет называться sde1 (или другие числа в конце, в зависимости от разбивки диска).

Проверяем наличие (флешка вставлена)

(вместо буквы e Вам нужно будет подставить свою. Если линукс совсем-совсем древний, то там будет /dev/hda* или подобное).

Ок, теперь имя уже известно. Можно пробовать монтировать. Для начала нужно создать для него каталог, можно даже в домашнем каталоге. Пусть это будет /home/Alexandr/usbstick Теперь монтируем

mkdir /home/Alexandr/usbstick sudo mount -t vfat /dev/sde1 /home/Alexandr/usbstick 

тут есть важный параметр - -t vfat - большинство флешек в fat, но бывают и в ntfs. (тогда нужно -t ntfs-3g )

В целом, очень странно, что флешка не подмонтировалась сама. Скорее всего она либо сломана, либо она на ntfs, а в системе не установлено под нее поддержка. Последние 10-20 строк с dmesg в момент вставки флешки могут прояснить ситуацию.

Источник

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