- Безопасное извлечение (Safely remove) USB-носителей в современных дистрибутивах GNU/Linux
- Как вынимать USB device ?
- Re: Как вынимать USB device ?
- Re: Как вынимать USB device ?
- Re: Как вынимать USB device ?
- Re: Как вынимать USB device ?
- Re: Как вынимать USB device ?
- Re: Как вынимать USB device ?
- Linux Disable USB Devices (Disable loading of USB Storage Driver)
- usb-storage driver
- How to forbid to use USB-storage devices on using fake install method
- Blacklist usb-storage
- BIOS option
- Encrypt hard disk
- Grub option
- Как перезагрузить USB-устройство из командной строки?
- Ubuntu Documentation
- Introduction
- Automounting
- Mounting
- Configuring Automounting
- Configuring Program Autostart
- Unmounting/Ejecting
- Auto-mounting (Ubuntu Server)
- Manually Mounting
- Using Disks
- Using mount
- Get the Information
- Create the Mount Point
- Mount the Drive
- Unmounting the Drive
- Using pmount
- The Importance of Unmounting
- Other Useful Commands
- Troubleshooting
- Interfering services
- Unclean LogFile
- User Privileges
- Preferences
- USB 2 Issues
- old kernels workaround
- recent kernels workaround, from Karmic
- Buffer I/O Errors
- Device suddenly becomes read-only
- USB-Device is or becomes read-only without errors
- General tip
- Seeking Further Help
- Other Resources
Безопасное извлечение (Safely remove) USB-носителей в современных дистрибутивах GNU/Linux
Столкнулся с интересным поведением современных дистрибутивов GNU/Linux при работе с USB-flash и USB-HDD, касающимся пресловутого безопасного извлечения таких носителей.
В следующих системах после безопасного извлечения (из Nautilus) на USB-flash гасится светодиод, а на USB-HDD останавливается шпиндель и устройство исчезает из системы полностью (его нет в lsusb, fdisk -l, в файловой системе /dev):
- Gentoo stable (GNOME с Nautilus 2.32), стоит на USB-HDD
- Ubuntu 12.04.2 LTS (GNOME с Nautilus 3.4.2, Unity 5.18), стоит на ПК, ноутбуке и USB-flash
В этих системах функция безопасного извлечения отсутствует в Nautilus (заменена либо на Eject, либо на Unmount):
- Ubuntu 12.10
- Ubuntu 13.04 (скоро выйдет)
- OpenSuSe 12.3
- Fedora 18
- Sabayon 11 Gnome
— для этих систем единственный универсальный способ безопасного извлечения:
Многим не нравится такая ситуация с безопасным извлечением, существуют следующие баг-репорты:
Мне не нравится выдергивать крутящийся жесткий диск и флешку под напряжением. В случае с флешкой после отмонтирования с данными скорее всего ничего не произойдет, а с жестким диском остается надеяться на механизмы автоматической парковки головок при пропадании питания.
Если Вы тоже считаете, что было бы хорошо вернуть в современные версии дистрибутивов безопасное извлечение, каким оно было в Gnome 3.4 (например, в Ubuntu 12.04) и Gnome 2.3x (например, в Gentoo и наверное, в Debian, CentOs, RedHat, SLED, Alt), пожалуйста, отпишитесь в баг-трекерах. Если в Ваших системах из списка выше светодиод флешки гасится и шпиндель останавливается или проблема существует и в других актуальных дистрибутивах, которые у Вас стоят, отпишитесь. Системы с KDE я не тестировал.
Я поместил в общий доступ таблицу на Google Docs — можете добавлять свои результаты тестирования безопасного извлечения — кому интересно.
Источник
Как вынимать USB device ?
Есть USB фотик, работает 😉 Единственное сомнение — когда я его вынимаю . Т.е. я беру и вынимаю из него кабель.. тоже вроде бы ничего страшного . но что делает оффтоп. когда для вынимания USB девайса нужно нажать ‘стоп девайс’ ?
Re: Как вынимать USB device ?
>что делает оффтоп. когда для вынимания USB девайса нужно нажать ‘стоп девайс’ ?
имхо, то же что делает umount, то есть из буфера пишет на фотик.
Re: Как вынимать USB device ?
Не совсем. Чтобы linux вел себя как оффтоп нужно ядро 2.6, а флеш отключать командой eject /dev/sda1 или как он там видится.
Re: Как вынимать USB device ?
дело в том что там нчего не монтируется и свои драйвера не используется. Т.е. usbcore(uhci) и libusb, ядро 2.4 , и gphoto2.
Re: Как вынимать USB device ?
я так выдёргивал Canon A70 ещё минолту какую-то ещё кого-то. Ну разумеется после того как файлы скопируются через gphoto2. Ядро 2.6.11. В твоём случае можно для перестраховки сначала выключить камеру. Не, не знаю, не стану советовать.
Re: Как вынимать USB device ?
Разница толкьо в том, что как и уже было выше сказанно олжны файлы скопировоться на фотоапарат или обратно. Ядро не пишит файл на носитель в синхронном режими по умолянию, что бы не перегружать систему. Умоунт или что бы там ни было служат для того чтобы все процессы с файловой системой завершить корретно и более ничего. В ядре нет драйвера который бы мог управлять фотоапаратом и сказал «анука подпрыгние». Виндовс воспринимает любую камеру тоже как обычный носитель. Единственная загвотска может быть с кабелем : usb сконструирован так что бы включить сначала один канал а потм друго (кажеться сначало данные а потом питание), мини usb это с той стороны где фотоапарат просто втыкает все это дело одновременно, что теоритически может привести к ошибке в каком нибуть чипе.
Re: Как вынимать USB device ?
Интересно если ничего немонтируется то как ты видишь файлы на фотике напиши путь плиз !
Источник
Linux Disable USB Devices (Disable loading of USB Storage Driver)
usb-storage driver
The usb-storage.ko is the USB Mass Storage driver for Linux operating system. You can see the file typing the following command:
# ls -l /lib/modules/$(uname -r)/kernel/drivers/usb/storage/usb-storage.ko
All you have to do is disable or remove the usb-storage.ko driver to restrict to use USB devices on Linux such as:
- USB keyboards
- USB mice
- USB pen drive
- USB hard disk
- Other USB block storage
How to forbid to use USB-storage devices on using fake install method
Type the following command under CentOS or RHEL 5.x or older:
# echo ‘install usb-storage : ‘ >> /etc/modprobe.conf
Please note that you can use : a shell builtin or /bin/true .
Type the following command under CentOS or RHEL 6.x/7.x or newer (including the latest version of Fedora):
# echo ‘install usb-storage /bin/true’ >> disable-usb-storage.conf
Save and close the file. Now the driver will not load. You can also remove USB Storage driver without rebooting the system, enter:
# modprobe -r usb-storage
# mv -v /lib/modules/$(uname -r)/kernel/drivers/usb/storage/usb-storage.ko /root/
##################
#### verify it ###
##################
# modinfo usb-storage
# lsmod | grep -i usb-storage
# lsscsi -H
Sample outputs:
Fig.01: How to disable USB mass storage devices on physical Linux system?
Blacklist usb-storage
Edit /etc/modprobe.d/blacklist.conf, enter:
# vi /etc/modprobe.d/blacklist.conf
Edit or append as follows:
Save and close the file.
BIOS option
You can also disable USB from system BIOS configuration option. Make sure BIOS is password protected. This is recommended option so that nobody can boot it from USB.
Encrypt hard disk
Linux supports the various cryptographic techniques to protect a hard disk, directory, and partition. See «Linux Hard Disk Encryption With LUKS [ cryptsetup Command ]» for more info.
Grub option
You can get rid of all USB devices by disabling kernel support for USB via GRUB. Open grub.conf or menu.lst and append «nousb» to the kernel line as follows (taken from RHEL 5.x):
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Make sure you remove any other reference to usb-storage in the grub or grub2 config files. Save and close the file. Once done just reboot the system:
# reboot
For grub2 use /etc/default/grub config file under Fedora / Debian / Ubuntu / RHEL / CentOS Linux. I strongly suggest that you read RHEL/CentOS grub2 config and Ubuntu/Debian grub2 config help pages.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Как перезагрузить USB-устройство из командной строки?
Можно ли сбросить подключение USB-устройства без физического отключения / подключения от ПК?
В частности, мое устройство представляет собой цифровую камеру. Я использую gphoto2 , но в последнее время я получаю «ошибки чтения устройства», поэтому я хотел бы попытаться выполнить программный сброс соединения.
Из того, что я могу сказать, нет никаких модулей ядра, загружаемых для камеры. Единственный, который выглядит связанным, это usbhid .
Сохранить следующее как usbreset.c
Выполните следующие команды в терминале:
Получите идентификатор шины и устройства USB-устройства, которое вы хотите сбросить:
Сделайте нашу скомпилированную программу исполняемой:
Запустите программу с привилегией sudo; сделать необходимые замены и идентификаторы, найденные с помощью lsusb команды:
Я раньше не сталкивался с вашими конкретными обстоятельствами, поэтому я не уверен, что этого будет достаточно, но я нашел самый простой способ перезагрузить USB-устройство с помощью этой команды: (Внешние приложения не нужны)
Это именно то, что я использую для сброса моего Kinect, поскольку у libfreenect, похоже, нет API для возврата его в спящий режим. Он у меня на Gentoo box, но ядро должно быть достаточно новым, чтобы использовать ту же структуру пути для sysfs.
Ваш, очевидно, не будет, 1-4.6 но вы можете либо извлечь этот путь устройства из журнала ядра ( dmesg ), либо использовать что-то вроде lsusb получения идентификатора производителя и продукта, а затем использовать быструю команду, подобную этой, чтобы увидеть, как эти пути связаны с другим поставщиком. / пары идентификаторов продукта:
Это сбросит все подключенные порты USB1 / 2/3 [1]:
Я верю, что это решит вашу проблему. Если вы не хотите сбрасывать все конечные точки USB, вы можете использовать соответствующий идентификатор устройства из /sys/bus/pci/drivers/ehci_hcd
Примечания: [1]: *hci_hcd драйверы ядра обычно управляют портами USB. ohci_hcd и uhci_hcd для портов USB1.1, ehci_hcd для портов USB2 и xhci_hcd для портов USB3. (см. https://en.wikipedia.org/wiki/Host_controller_interface_(USB,_Firewire) )
Мне нужно было автоматизировать это в скрипте Python, поэтому я адаптировал чрезвычайно полезный ответ LiLo к следующему:
В моем случае это был драйвер cp210x (о котором я мог сказать lsmod | grep usbserial ), так что вы можете сохранить приведенный фрагмент как reset_usb.py, а затем сделать это:
Это также может быть полезно, если у вас еще нет настройки компилятора переменного тока в вашей системе, но у вас есть Python.
Я создал скрипт Python, который упрощает весь процесс на основе ответов здесь.
Сохраните приведенный ниже скрипт как reset_usb.py или клонируйте этот репозиторий .
Поскольку частный случай вопроса — это проблема связи gphoto2 с камерой по USB, в gphoto2 есть возможность сбросить USB-соединение:
Возможно, этот вариант не существовал в 2010 году, когда был задан вопрос.
Самым быстрым способом сброса будет сброс самого контроллера USB. Это заставит udev отменить регистрацию устройства при отключении, и регистрация вернется после того, как вы его включите.
Это должно работать для большинства компьютерных сред. Однако, если вы используете какое-то нестандартное оборудование, вы можете просто перебирать имена устройств. С помощью этого метода вам не нужно узнавать имя устройства по lsusb. Вы также можете включить в автоматизированный скрипт.
Я использую кувалду, перезагружая модули. Это мой скрипт usb_reset.sh:
И это мой файл службы systemd /usr/lib/systemd/system/usbreset.service, который запускает usb_reset.sh после запуска моего менеджера diplay:
Я сделал скрипт Python, который будет сбрасывать определенное устройство USB на основе номера устройства. Вы можете узнать номер устройства из команды lsusb.
В этой строке 004 номер устройства
Вот скрипт, который будет сбрасывать только соответствующий идентификатор продукта / поставщика.
Кто-нибудь заказывал кувалду? Это воедино из различных других ответов здесь.
Иногда я хочу выполнить эту операцию на определенном устройстве, как указано VID (идентификатор поставщика) и PID (идентификатор продукта). Это скрипт, который я нашел полезным для этой цели, который использует изящную библиотеку libusb.
Затем этот c ++ файл resetDeviceConnection должен выполнить эту задачу сброса подключения устройства, как указано в vid и pid.
Я сделал простой скрипт для перезагрузки определенного USB-устройства.
Возможно, это работает и для камеры:
После я восстановил голодный USB 3.0 HDD на 3.4.42 (kernel.org) Linux на моей стороне. dmesg сказал, что это было время ожидания команд после 360 секунд (извините, я не могу скопировать системный журнал здесь, не подключенные сети), и диск завис полностью. Процессы доступа к устройству были заблокированы в ядре и не могут быть уничтожены. NFS висел, ZFS висел, dd висел.
После этого все снова заработало. dmesg рассказал только одну строчку о USB найденном устройстве.
Я действительно понятия не имею, что делает следующее подробно. Но это сработало.
Следующий пример выводится из Debian Squeeze с 2.6.32-5-686 ядром, поэтому я думаю, что он работает для 2.6 и выше:
Если это не работает, возможно, кто-то еще может выяснить, как отправить реальный сброс на устройство.
Попробуйте, это отключение программного обеспечения (Eject).
Иногда не работает просто отсоединить устройство для некоторых устройств.
Я хочу удалить или извлечь мой «Genius NetScroll 120».
Тогда я сначала проверь мое подключенное USB-устройство
Хорошо, я нашел свою мышь, она имеет шину 002, устройство 009, idVendor 0458 и idProduct 003a, так что это справочная информация об устройстве мыши.
Это важно, номер шины — это начальный путь к устройству, и я проверю идентификатор продукта и поставщика, чтобы убедиться, что устройство удаляется.
Обратите внимание на папки, проверьте начало с папкой номер 2, я проверю эту, потому что мой Bus — 002, и одну за другой я проверяю каждую папку, содержащую правильные idVendor и idProduct, о моей информации о мыши.
В этом случае я получу информацию с помощью этой команды:
Хорошо, путь /sys/bus/usb/drivers/usb/2-1.3/ совпадает с моей информационной мышью! XDDD.
Пришло время удалить устройство!
Подключите снова USB-устройство, и оно снова работает!
Источник
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:
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
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:
Источник