Connect usb devices linux

Detect and mount USB devices in Linux from console

Mount pendrives with commands in the Linux terminal

Overview

This is a small guide to detect a newly attached device to an USB port and mount it in Linux.

We will explore different strategies that will help when some of the tools isn’t available.

First of all, some definitions:

Understanding

What does exactly mount means?

All files accessible in a Unix system are arranged in one big tree, the file hierarchy, rooted at /. These files can be spread out over several devices. The mount command serves to attach the filesystem found on some device to the big file tree. Conversely, the umount(8) command will detach it again. The filesystem is used to control how data is stored on the device or provided in a virtual way by network or another services.

To attach these new devices filesystems we use the mount command in the form: mount -t type device dir .

In the above command, Devices (block special devices 1 ) can be indicated in one of the following three ways:

  1. Filename
    • using the filename that is associated with the device.
    • e.g.: /dev/sdb2
  2. Filesystem label
    • Using the label associated with the device.
    • e.g.: PENDRIVE
  3. UUID
    • Universally Unique IDentifier (UUID) Uniform Resource Namespace 2 .
    • e.g.: ba108o135-80bf-1cci-b2za-082eafd02y0g

Listing

To list the currently mounted devices/filesystems, findmnt (find a filesystem).

For example, in Ubuntu 18.10 it shows:

There is also the old way, maintained for compatibility only but widely used: mount -l or just mount .

Now we have just connected a pendrive (flash drive), how do we know which label or UUID it has to be able to mount the filesystem?

1. Identify the newly attached device

After we plug a pendrive, we need a method to locate the new device so we can get its label or UUID .

The following list shows the available alternatives to do it, any of them would be help you find the device information, listing most complete and easier to use first.

1.1 Using blk commands

The command lsblk prints all block devices (except RAM disks) in a tree-like format by default.

We can have a look at it to try to spot the new device with the filesystem parameter: —fs to print info of each filesystem, LABELs and UUID s on available block devices.

To directly find out the connected pendrive, save the above listing in a temporal folder and then look for the differences with the same command after plugging the pendrive:

1.2 Inspect Kernel ring buffer

Immediately after plugging the device, we can examine the kernel ring buffer with the command dmesg

There we can look for the string of type sda , or sdb , etc, that will belong to the most recent connected device.

In this case we can spot the sda: sda1 sda2 line that indicates it has two partitions: sda1 and sda2 .

Then we use the command blkid -p device to find out its UUID , label and more properties.

1.3 dev-by- directories

And a similar approach can be done to know which one was plugged in, saving the list before and after plugging the device:

Читайте также:  Отечественная операционная система astra linux

2. Mount the device

Which method should we use?

Device names depend on which (physical) slot you connect the device, and if there are other devices already attached or not, so the filename to refer to them may change over time.

Labels are more stable than filenames, but they may change or have the same name as other label.

We will mount it at /media/usb-stick .

For this, create the directory: sudo mkdir /media/usb-stick

And then mount it with one of these methods, preferably UUID :

3. Make it permanent

There is a special file /etc/fstab , in which each line describes:

  • what devices are usually mounted,
  • where,
  • using which options.

After reboot each line will be mounted automatically if the device is connected.

As we are working mostly with pendrives, we should use the special option: nofail. This avoids reporting any errors for the device if it does not exist at booting time when it tries to mount them and probably the device won’t be plugged..

3.1 Mount a pendrive just by specifying a directory

Personally, I like to have each pendrive or device identified like /media/kingstone-2gb so I can easily mount it with the directory name after plugging it.

4. Remove pendrive

sudo umount /media/usb-stick

Optional

Set pendrive label

To set create or rename the label of a pendrive there are several programs:

  • e2label — Change the label on an ext2/ext3/ext4 filesystem
  • tune2fs — adjust tunable filesystem parameters on ext2/ext3/ext4 filesystems
  • mke2fs — create an ext2/ext3/ext4 filesystem

To set a pendrive label as usb-stick

Or create filesystem:

And change the label

Summary

Summarizing the commands used above in a single list:

Resources

block special file: A block special file is normally distinguished from a character special file by providing access to the device in a manner such that the hardware characteristics of the device are not visible. http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_79 ↩︎

A Universally Unique IDentifier (UUID) URN Namespace https://tools.ietf.org/html/rfc4122 ↩︎

Marcelo Canina

Articles

  • Adding a swap memory to Linux from command line in 6 steps April 2, 2020
  • Free up space in Linux (Ubuntu) March 27, 2020
  • Switch between languages in Linux with xkb. Write in multiple languages with same keyboard. March 21, 2020
  • How to make Ubuntu display emojis February 12, 2020
  • Detect and mount USB devices in Linux from console
  • How to make screencasts in Ubuntu Linux January 21, 2019
  • Using i3 window manager in Linux January 7, 2019
  • Setting Up A Fresh Linux Server August 25, 2018
  • How To Download A Website With Wget The Right Way June 30, 2017
  • Replicate Installed Package Selections From One Ubuntu System To Another April 24, 2017
  • Using Clamav Antivirus In Ubuntu January 25, 2017
  • How to Type Spanish Characters, Accents and Symbols in Linux June 6, 2016

Subcategories

Ubuntu
  • How to activate tap to click touchpad’s feature in Ubuntu in 4 steps March 4, 2021
  • Difference between suspend and hibernate in Ubuntu and how to execute them from command line April 12, 2020
  • Solving Google Chrome’s gpu-process error message in Ubuntu Linux January 7, 2019
  • Solving Google Chrome’s secret service operation error message in Ubuntu Linux January 7, 2019
  • Start Emacs In Ubuntu The Right Way June 10, 2017
  • Unix Shell
    • Connect to a Bluetooth device from command line in Ubuntu Linux June 23, 2020
    • Add Infolinks Script To An Existing Website From Console With Sed Command April 4, 2017
    • How to change all files permissions to 644 and directories to 755 January 10, 2017
    • Shell Redirect Output And Errors To The Null Device In Bash December 9, 2016
    • Prevent Running Of Duplicate Cron Jobs December 8, 2016
    • Delete All Backup Files Recursively In Bash November 28, 2016
    • Bash Script to Find Out If MySQL Is Running Or Not November 9, 2016
    Читайте также:  1с сервер linux установка лицензии
  • A comprehensive guide to manually mount a USB pendrive in Linux.

    Источник

    List USB Devices Linux

    In the world of USB computer peripherals, almost everyone uses some sort of USB devices in their computer. These days there are USB webcams, USB hard drives, USB stick also known as PenDrive etc. Almost every device has a USB version of it. So if you’re using Linux, listing what USB device is connected to your system might be necessary at some point.

    There are many programs and many ways to list USB devices on Linux.

    In this article, I will show you how to list USB devices on Linux. I am using Ubuntu 18.04 Bionic Beaver for the demonstration, but these commands are available on every Linux distribution. So let’s get started.

    Listing USB Devices using lsusb Command

    The widely used lsusb command can be used to list all the connected USB devices in Linux.

    As you can see from the output of the lsusb command in the screenshot below, all the connected USB device is listed. The Bus ID, Device ID, USB ID, and a title is displayed in the output of lsusb command.

    As you can see in the marked section of the screenshot below, Realtek Semiconductor Corp. with ID 0bda:57cb, this is my USB Webcam.

    You can’t tell that it’s a Webcam by looking at the output of lsusb command, Can you? Nope! So how do I know this? It’s because I checked the output of the lsusb command before and after connecting the USB Webcam and once I compared the outputs, the newly added row is the USB device I connected. Plain! But there are ways to find out what the USB device is.

    You can use the dmesg command to find out more information about the connected USB devices. The last connected USB device is the easiest to find with dmesg command. It is more widely used for debugging purpose. You will shortly see why.

    You run dmesg command as follows:

    As you can see in the yellow marked box in the screenshot below, these are information about the USB device I connected last, which was my USB Webcam. You can see in one of the blue marked box, the USB device I connected is a HD UVC WebCam and its ID is 0bda:57cb.

    By now you may have found out that the output of dmesg command is system log messages. Well yes, it is.

    You can also search for a specific USB device by its ID in the dmesg system log.

    Run the following command to open the output of dmesg command with less text pager:

    You should see the following window:

    Now to search for a string, press / key on your keyboard. And you should the a / appear on the bottom of terminal window as marked in the screenshot below.

    Now type in the USB device ID. For example, earlier when I listed the connected USB devices with lsusb command, one of the USB device had ID 0bda:57cb

    Type in the USB Device ID and press . As you can see in the marked section of the screenshot below, the search string is marked white.

    You may press and arrow keys to navigate up and down and read through it. You should find a lot of information about that USB device as you can see in the marked section of the screenshot below.

    Listing USB devices with usb-devices Command

    You can run the following command to list all the connected USB devices of your system:

    As you can see in the screenshot below, all the connected USB devices are listed. we can find out pretty much the same information as before with usb-devices command.

    Listing Block USB Devices

    If you want to list all the USB block storage devices, that is all the USB storage devices, then you can use the lsblk or fdisk command to do so.

    Читайте также:  Root ����� ��� kali linux

    Listing USB block storage devices with lsblk:

    As you can see in the screenshot below, all the available block storage devices (including the USB block storage devices) are listed.

    You can get almost the same information as lsblk command with blkid command. But you have to run it as root as follows:

    You can also use fdisk command to list all the USB block storage devices as follows:

    As you can see in the screenshot below, the connected block storage devices (including the USB devices) are listed.

    That’s how you list all the USB devices on Linux. Thanks for reading this article.

    Источник

    Как в Linux посмотреть подключенные USB устройства

    В настоящее время многие компьютерные периферийные устройства, такие как веб-камеры, мыши, сканеры, принтеры, жесткие диски, USB (Pendrive) подключаются по USB. После того, как эти устройства подключены к рабочему столу или серверу, важно знать имя устройства или путь к нему. Это помогает идентифицировать USB устройства для таких задач, как форматирование или отключение.

    В Linux все файлы устройств хранятся в каталоге /dev и должны быть доступны во время загрузки системы.

    В этой статье я покажу вам различные способы как в ubuntu посмотреть usb устройства. Большинство команд, упомянутых здесь, должны работать практически на всех дистрибутивах Linux. Например Ubuntu, Debian, Mint.

    Просмотр списка имен USB устройств с помощью команды df

    Команда df — это полезная команда, которая может помочь составить список всех подключенных томов, включая USB-накопители.

    Как только USB-устройство подключается в систему Linux, это устройство автоматически монтируется в раздел /media и становится готовым к использованию.

    Из приведенного выше вывода следует, что у меня есть 1 USB-накопитель /dev/sdb с 2 разделами /dev/sdb1 и /dev/sdb2

    Список имен подключенных USB — устройств с помощью команды lsblk

    Команда Lsblk используется для перечисления всех блочных устройств в системе Linux. Из списка можно фильтровать USB-устройства с помощью команды grep.

    Чтобы получить дополнительную информацию, такую как UUID, производитель и тип файловой системы, используйте команду blkid, как показано на рисунке ниже.

    Список USB — устройств с помощью команды fdisk

    Вы можете использовать старую добрую команду fdisk, которая используется для разбиения томов на разделы, чтобы перечислить все разделы в системе Linux, включая USB-накопители.

    Запятая будет отображать подробную информацию о вашем USB-томе, включая разделы , размер тома, секторы и тип файловой системы.

    Список сведений о подключенных USB-устройствах с помощью команды lsusb

    Команда lsusb, также известная как команда “List USB”, используется в Linux для перечисления всех USB-устройств, подключенных к системе.

    На выводе выше отображается идентификатор шины, идентификатор устройства, идентификатор USB, а также поставщик или производитель USB-устройств

    Команда lsusb перечисляет подключенные устройства и не предоставляет дополнительной информации о USB-устройствах.

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

    Вы можете использовать команду dmesg и grep, чтобы сузиться до USB-устройств.

    Кроме того, вы можете передать вывод команды dmesg в less для облегчения прокрутки.

    На выходе вы можете найти определенную строку, нажав клавишу прямой косой черты ( / ) на клавиатуре, а затем имя или идентификатор устройства USB-устройства.

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

    Поиск USB-накопителя

    Список USB контроллеров и устройств, использующих USB устройства

    Команда usb-devices-это сценарий оболочки, который позволяет вам перечислить все USB-контроллеры и USB-устройства, подключенные к вашему компьютеру. Он печатает детали USB-устройства, такие как производитель, название продукта, серийный номер и многое другое. Вот вывод команды:

    Заключение

    В этой статье мы продемонстрировали различные способы просмотра USB-устройств, подключенных к системе Linux.

    Источник

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