Linux disable usb controller

Системное администрирование и мониторинг Linux/Windows серверов и видео CDN

Статьи по настройке и администрированию Windows/Linux систем

  • Полезное
    • Карта сайта
    • Мой сайт-визитка
  • Рубрики
    • Linux
      • VoIP
      • Безопасность
      • Видеопотоки
      • Системы виртуализации
      • Системы мониторинга
    • Windows
    • Интересное
    • Сеть и Интернет
  • Мета
    • Войти
    • RSS Feed

Включение/выключение питания USB устройств из консоли

Иногда бывают ситуации, когда нужно отключить USB флешку, сделать настройку какой-то программы и потом опять подключить для нормальной работы. Но что делать если эти действия нужно сделать на удаленном сервере, к которому у нас нет физического доступа. Можно обратиться в службу поддержки, но можно и сделать все своими силами «не отходя от кассы». Расскажу как это делается.

Допустим, наша флешка уже втыкнута в USB-порт. Первым делом нужно проверить так ли это.

Как видим, USB-флешка находиться на шине Bus 001. Следовательно нам нужно найти в /sys/bus/usb/devices/ соответствующее USB устройство и выключить питание.

Чтобы копаться в системных устройствах нужны права суперпользователя.

По скольку мы знаем, что наша USB флешка на физической шине с номером 1. Следовательно, нужно отключить питание устройства 1-6, так как именно оно отвечает за первую шину.

Приведенная выше команда, отключит питание устройства на лету. Проверим теперь, так ли это.

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

Источник

Is it possible to turn off a specific USB port so it doesn’t accept any device?

I have a lot of ports on my computer. I would like to turn off one of them, so when I connect my phone to that port, it only charges. I do want my phone to work with my computer in some occasions though, so I hope other ports are not affected.

I would just like to know how possible this is.

2 Answers 2

First, run lsusb .

The output should be like:

In the output, find the device number of the port to be disabled. For example, the Seagate drive in the example has Device 009 — that is its device number. Then the id will be usb[device number] — such as usb9

Then, disable USB wake-up (do this only once):

Be sure to replace X in usbX with the device number.

Then turn it off:

Undo this:

Here is a plug & play (literally) option:

It’s a good idea if you want to avoid pop-up messages and file browsers every time you plug your phone in for charging only.

This is also more fool-proof than the software approach because software that turns off the port for data can be reversed by software that turns it back on. Or it might be reinitialized during suspend/resume or some other process you didn’t foresee.

Источник

Как отключить порты USB, кроме клавиатуры и мыши?

Добрый день! Подскажите пожалуйста, как на компьютере с Linux отключить все USB порты, так, чтобы в них не было возможности вставлять съемные накопители и флешки, но можно было бы подключать клавиатуру и мышь?

Удалить все udev правила usb кроме мыши и клавиатуры. Но последний раз я копался в udev несколько лет назад и поэтому уже могло там многое поменяться.

Читайте также:  Mkinitcpio p linux failed to load preset linux preset

в ядре отключить USB Storage, не?

в ядре отключить USB Storage, не?

А если например отключить монтирование дисков, кроме сетевых и локальных, указанных с fstab? Нужно сделать так, чтобы пользователи на предприятии не могли подключать флешки и прочие накопители к компу, но клавиатура и мышь и возможно штрих-сканер работали бы.

blacklist usb_storage >/etc/modprobe.conf.d/666.conf

перекомпиливаешь ядро, Device Drivers -> USB -> USB Storage, USB Storage убрать галочку. либо тут написано http://www.cyberciti.biz/faq/linux-disable-modprobe-loading-of-usb-storage-dr.

или blacklist usb-storage или как там этот модуль зовётся

в иксах отключить определение клав и мышей по идентификатору с identifier keyboard и option ignore on, создав конфиг в /etc/X11/xorg.conf.d/

чорд, я всё перепутал, сорри

У меня есть: /etc/modprobe.d/fbdev-blacklist.conf

Просто добавить в него «blacklist usb-storage»?

можно создать новый файл /etc/modprobe.d/usb-blacklist.conf

в файл прописать blacklist usb_storage сохранить и ребут

В современных DE автомонтированием подключаемых накопителей заведует udisks и consolekit / polkit. Поэтому вам нужно отредактировать политики consolekit / polkit, разрешающие монтирование подключаемых съёмных накопителей. В таком случае автомонтирование средствами udisks происходить не будет, а в случае, если пользователь нажмёт на иконку накопителя в файловом менеджере будет выведен запрос пароля root.

Если же вы используете для автомонтирования правила udev, например набор правил uam, то удалите их.

Можете рассказать поподробнее, как это делается, похоже это именно то, что мне нужно.

В /etc/polkit-1/rules.d/10-disable-mount.rules помещаете:

Это что, жаваскрипт?

Это синтаксис правил polkit.

Сишный это синтаксис.

В данном случае это синтаксис правил polkit, если вы напишете правило без соответствия синтаксису, то оно не будет распознано, без разницы на что синтаксис похож.

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

Ну это проще. Всего то надо отредактировать /etc/group . Дело в том что обращаться к соответствующему демону для монтирования можно только если состоишь в определённой группе. Вроде как fuse, cdrom, floppy.

А нужные скрипты монтирования (сетевая шара или какой то специальный носитель) можно монтировать делегировав соответствующий скрипт через sudo

Отключение usb-storage, в общем случае не поможет.

Сканер-штрихкодов наверняка USB-COM и пользователь должен иметь доступ к этому порту, через COM-порт скачаю что угодно.

USB-HID (через который работают большинство клав и мышей) тоже довольно навороченный протокол.

Прочитать флешку можно и с помощью libusb (наверняка есть в системе).

В конце концов есть кнопка reset и загрузка с USB (во многих BIOS-ах выбор альтернативной загрузки не отключается).

Ещё /etc/group можно посмотреть на наличие юзера/группы в storage.

Что за дистр-то? А то тут долго голову можно ломать.

Debian 6. Но я уже сделал через /etc/modprobe.d/usb-blacklist.conf, как указал anonymous, и все вроде работает, во всяком случае я попробовал после этого подключить USB флешку и диск, и они не вызвали никакой видимой реакции системы, диски не подмонтировались.

Можно залить разъёмы эпоксидкой или повредить их. Можно в биосе отключить USB, а мышь и клаву использовать через ps/2. В случае hardened ядра в grsec есть возможность при сборке ведра включить опцию типа «не детектировать новые USB-устройства после старта ядра», т.е. с чем забутились, с тем и дальше работаем.

А если при апдейте ядра название модуля поменяется(usb_storage -> usb_mass_storage, например)? А если админ захочет флешку подключить(он, конечно, модуль ручками подгрузит, но голову поломает)? И вообще, слить инфу через USB можно и в обход USB Mass Storage(например, MTP).

Думаю, нужно рубить проблему на корню — не давать пользователю монтировать ФС и работать напрямую с блочными устройствами(dd if=

Читайте также:  Разрешить доступ teamviewer mac os

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

добавь в параметр ядра ‘nousb’. Хотя неуверен, что мышка с клавой будут работать.

Источник

Linux USB: turning the power on and off?

How can I programmatically enable and disable the power to a particular USB port on Linux? Is such a thing even possible? Mac answers appreciated as well!

I was trying for a BOC (don’t pretend you weren’t try to get one too!) and ended up with one of these, and would like to get some use out of the thing by hooking it up to our server monitor.

13 Answers 13

There is a sys entry for this in Linux. From Documentation/usb/power-management.txt:

Something like: echo on > /sys/bus/usb/devices/usb5/power/level

You may need to play with the autosuspend setting as well. Without telling the kernel to stop trying, it may suspend the port automatically.

The usbfs interaction seems to have changed a number of times since this question was originally answered. So, here’s how I cycle hub port power on Ubuntu Oneiric Ocelot from a Bash shell.

Search for the bus and device number:

Locate the device in the bus / hub port hierarchy using the bus and device number:

The syntax seems to be ‘bus-port.port.port.port.port. ‘ For example, my mouse is connected to an external hub which connects to my computer’s hub which internally connects to a root hub:

So, ‘2-1.1.1’ in the above case. Finally, cycle the port power:

I haven’t hooked up a protocol analyzer to see what’s actually happening on the bus, but I know my mouse light turns off when I unbind it. I’m guessing at a lower layer this is interacting with the EHCI host controller to actually shut power off on the port. This is particularly useful for embedded devices, such as a UVC webcams, which never seem to function properly and would otherwise require a system reboot to reset.

See also the udevadm command.

You could use my tool uhubctl — command line utility to control USB power per port for compatible USB hubs.

It works only on hubs that support per-port power switching, but note that many modern motherboards have USB hubs that support this feature. Also, last version of uhubctl supports USB 3.0 hubs, and good news is that quite a few new USB 3.0 hubs are supporting this feature.

To install system wide as /usr/sbin/uhubctl :

To list status of all hubs and ports that can be controlled by uhubctl:

To turn off power on port 5 of single compatible hub:

To toggle power off then on:

Digs through bookmarks

Seems like you need to connect it to a hub and control the hub’s power. None of the root hubs I have seen seems to be able to support power control.

This is an example with a Logitech USB wireless mouse under linux.

Read relevant paragraph of «/proc/bus/usb/devices» according to your devices «Vendor» (vendor id) and «ProdID» (product id) or «Manufacturer» and «Product» (all these values are constant per device).

(first paragraph with device powered on, second one with same device powered off but still pluged in)

You need two variables here. They are located in the «T:» line (first line of paragraph). These variables are : Bus (Bus=01 in this example) Cnt (Cnt=01 in this example)

You will need to add «1» (arithmetic one) to «Cnt» to get the rank Rank=Cnt+1 (this is a mathematical function, Rank=2 in this example)

Читайте также:  Adobe flash player windows 10 как запустить

So the device you are looking for is the following string : Bus-Rank (this is not a mathematical function, its a string, 1-2 in this example)

Mind also the «C:» line. It contains info regarding the power (current) of the device. If there is an asterisk in «C:» (like in our 1st example) then the device is powered. If not («C:») then the device is «more or less» powered off meaning there is always a tiny current when a device is pluged, otherwise we wouldn’t be able to read all this info.

Mind finaly the «I:» line. If the field «I:*» contains asterisk (like in our 1st example) then there is input, from or to the device, i am not sure, maybe both. The final line field contains the driver used («usbhid» in our 1st example)

We are ready to switch the power of our device :

The following is a simple bash script «USBMS» (USB Mouse Switch) that controls the power of the device in our example above. It is not very dynamical and it uses the «Product» and «Manufacturer» constants to locate the relevant paragraph of «/proc/bus/usb/devices» You should use the «Vendor» (vendor id) and «ProdID» (product id) instead. It also checks the power state of the device. Run as superuser.

Command : ./USBMS action

parameter : action = «off» or «0» to power off — action = «on» or «1» to power on (without the quotes)

@Kristian Typically you won’t find software controlled port power controlled advertised because users shouldn’t be conscious of this layer. I don’t think there’s many use cases for it other than to force misbehaving bus powered devices into a known state, and handle dumb as a post devices that only use USB for power. Perhaps Mark’s device falls into the latter category. It’s a crude, last resort mechanism.

As I mentioned, I haven’t looked into the implementation details for the unbinding hack and I’ve only tried it on the EHCI host controller embedded in my motherboard, an «Intel Corporation 6 Series/C200 Series Chipset Family USB Enhanced Host Controller (rev 05).» I would guess that this host controller has the PPC bit of HCSPARAMS set, indicating software control of port power switches, per EHCI spec.

If you’re interfacing with an external hub, «a hub indicates whether or not it supports power switching by the setting of the Logical Power Switching Mode field in wHubCharacteristics,» according to the USB 2.0 spec. I don’t rememeber if the compliance tests ensure this functionality or not, but if they do, you’d need only find a hub with the USB 2.0 logo. I speculate the hack would send a set port feature request, but it may cycle more than just the target port. Again, per USB 2.0 spec, «a hub with power switches can switch power to all ports as a group/ gang, to each port individually, or have an arbitrary number of gangs of one or more ports.» I’m not sure if there’s a nice command line tool to get wHubCharacteristics.

In short, there’s not a great generic way to handle this problem, as far as I know. However, it is possible to interrogate an internal or external hub to determine its level of support and then, if supported, use it. It’s just a question of how much time you want to spend doing so.

Источник

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