Перезагрузить usb устройство linux

How do you reset a USB device from the command line?

Is it possible to reset the connection of a USB device, without physically disconnecting/connecting from the PC? Specifically, my device is a digital camera. I’m using gphoto2 , but lately I get «device read errors», so I’d like to try to do a software-reset of the connection. From what I can tell, there are no kernel modules being loaded for the camera. The only one that looks related is usbhid .

i tried both solutions by Li Lo and ssokolow, all i get is permission denied, nomatter if i use the usbreset code or the command line «echo 0 > . » i use sudo, also my usb devices are owned by root but i can use them without admin rights(cameras..)

If you are getting read errors, you might have some data corruption. If your camera uses an external memory card (such as MicroSD), it might be wise to connect it to the computer and run fsck.

20 Answers 20

Save the following as usbreset.c

/* usbreset -- send a USB port reset to a USB device */ #include #include #include #include #include #include int main(int argc, char **argv) < const char *filename; int fd; int rc; if (argc != 2) < fprintf(stderr, "Usage: usbreset device-filename\n"); return 1; >filename = argv[1]; fd = open(filename, O_WRONLY); if (fd < 0) < perror("Error opening output file"); return 1; >printf("Resetting USB device %s\n", filename); rc = ioctl(fd, USBDEVFS_RESET, 0); if (rc < 0) < perror("Error in ioctl"); return 1; >printf("Reset successful\n"); close(fd); return 0; > 

The run the following commands in terminal:

$ lsusb Bus 002 Device 003: ID 0fe9:9010 DVICO 
$ sudo ./usbreset /dev/bus/usb/002/003 

This works with ubuntu 13.10. The device ID can vary. TO get it for the mouse I have wrapped above code in few shell commands echo $(lsusb | grep Mouse) mouse=$( lsusb | grep Mouse | perl -nE «/\D+(\d+)\D+(\d+).+/; print qq(\$1/\$2)») sudo /path/to/c-program/usbreset /dev/bus/usb/$mouse

my external drive seems to become undetectable (I have to hard reconnect the usb cable); it is a usb2.0 connected on a usb3.0 desktop PC port; when I run usbreset /dev/bus/usb/011/001 that is one of the 2 usb 3.0 root hubs at lsusb , it errors: «Error in ioctl: Is a directory», any ideia? I tried on both usb 3.0 hubs

If anyone reading this have a (usb) mouse freeze after logging in on Ubuntu 16.04 (with dmesg filled by «input irq status -75») , i can confirm that this is the only solution that worked for me. Thank you

At least in Debian 10 and Ubuntu 20.04 there is no need to self-compile — /usr/bin/usbreset is part of the package usbutils. Note that this one uses device ID’s instead Bus/Dev-number — simply call ‘usbreset 0fe9:9010’ in the above case.

I haven’t found myself in your specific circumstances before, so I’m not sure if it’ll do enough, but the simplest way I’ve found to reset a USB device is this command: (No external apps necessary)

sudo sh -c "echo 0 > /sys/bus/usb/devices/1-4.6/authorized" sudo sh -c "echo 1 > /sys/bus/usb/devices/1-4.6/authorized" 

That’s the actual one I use to reset my Kinect since libfreenect seems to have no API for putting it back to sleep. It’s on my Gentoo box, but the kernel should be new enough to use the same path structure for sysfs.

Yours obviously wouldn’t be 1-4.6 but you can either pull that device path from your kernel log ( dmesg ) or you can use something like lsusb to get the vendor and product IDs and then use a quick command like this to list how the paths relate to different vendor/product ID pairs:

for X in /sys/bus/usb/devices/*; do echo "$X" cat "$X/idVendor" 2>/dev/null cat "$X/idProduct" 2>/dev/null echo done 

Thank you worked great! Maybe you should also mention to perform a echo 1 > /sys/bus/usb/devices/whatever/authorized inside a script to re-enable the device as soon as it has been disabled. I did it on both my mouse and usb keyboard and I ended up with a completely deaf system 🙂

It’s extremely strange if it automatically re-set the value to 1 as setting it to 0 is telling the system you don’t want the device to be «authorized» and therefore inaccessible.

Читайте также:  Postgresql конфигурационный файл linux

A note for anyone who tries to switch to the | sudo tee . approach to privileged /sys writes: That breaks badly if you don’t already have your sudo credentials cached. sudo sh -c «. » works as expected when sudo needs to prompt for a password.

find /sys/bus/usb/devices/*/authorized -exec sh -c ‘echo 0 > $<0>; echo 1 > $<0>‘ <> \; worked like charm for me. ty for pointing at the authorized files.

@MarcH no this certainly doesn’t power-cycle a USB device. Even the USBDEVFS_RESET ioctl() does not have that power. I have yet to see some hardware (a motherboard) that supports power-cycling a USB port. But moreover, this /sys/bus/usb/devices/*/authorized thing does not even seem to bring the port into the «reset requested» state (data+/- both low for a fraction of a second). But, it does make my custom CDC ACM device show all signs of an actual reset. is this possibly a mere reload of the SW stack, on the host PC and on the slave, for the USB port indicated?

This will reset all of USB1/2/3 attached ports[1]:

for i in /sys/bus/pci/drivers/[uoex]hci_hcd/*:*; do [ -e "$i" ] || continue echo "$" > "$/unbind" echo "$" > "$/bind" done 

I believe this will solve your problem. If you do not want to reset all of the USB endpoints, you can use appropriate device ID from /sys/bus/pci/drivers/ehci_hcd

Notes: [1]: the *hci_hcd kernel drivers typically control the USB ports. ohci_hcd and uhci_hcd are for USB1.1 ports, ehci_hcd is for USB2 ports and xhci_hcd is for USB3 ports. (see https://en.wikipedia.org/wiki/Host_controller_interface_(USB,_Firewire))

Although I’ve received the following message: ls: cannot access /sys/bus/pci/drivers/ehci_hcd/: No such file or directory this has resolved the issue, the mouse has started working immediately. +1

@Otheus OHCI and UHCI are the USB 1.1 host standards, EHCI is the USB 2.0 host standard, and XHCI is the USB 3.0 host standard.

This is a beautiful solution. However, on some later Kernels and other *nix distributions, you will find that you need to substitute *hci_hcd with *hci-pci , as the hci_hcd driver is already compiled into the Kernel.

On a Banana Pi, there apparently is no PCI bus, I had to use the following: for i in /sys/bus/usb/drivers/*/*:*; do

I’ve created a Python script that simplifies the whole process based on answers here.

Save the script below as reset_usb.py or clone this repo.

python reset_usb.py help # Show this help sudo python reset_usb.py list # List all USB devices sudo python reset_usb.py path /dev/bus/usb/XXX/YYY # Reset USB device using path /dev/bus/usb/XXX/YYY sudo python reset_usb.py search "search terms" # Search for USB device using the search terms within the search string returned by list and reset matching device sudo python reset_usb.py listpci # List all PCI USB devices sudo python reset_usb.py pathpci /sys/bus/pci/drivers/. /XXXX:XX:XX.X # Reset PCI USB device using path /sys/bus/pci/drivers/. /XXXX:XX:XX.X sudo python reset_usb.py searchpci "search terms" # Search for PCI USB device using the search terms within the search string returned by listpci and reset matching device 
#!/usr/bin/env python import os import sys from subprocess import Popen, PIPE import fcntl instructions = ''' Usage: python reset_usb.py help : Show this help sudo python reset_usb.py list : List all USB devices sudo python reset_usb.py path /dev/bus/usb/XXX/YYY : Reset USB device using path /dev/bus/usb/XXX/YYY sudo python reset_usb.py search "search terms" : Search for USB device using the search terms within the search string returned by list and reset matching device sudo python reset_usb.py listpci : List all PCI USB devices sudo python reset_usb.py pathpci /sys/bus/pci/drivers/. /XXXX:XX:XX.X : Reset PCI USB device using path sudo python reset_usb.py searchpci "search terms" : Search for PCI USB device using the search terms within the search string returned by listpci and reset matching device ''' if len(sys.argv) < 2: print(instructions) sys.exit(0) option = sys.argv[1].lower() if 'help' in option: print(instructions) sys.exit(0) def create_pci_list(): pci_usb_list = list() try: lspci_out = Popen('lspci -Dvmm', shell=True, bufsize=64, stdin=PIPE, stdout=PIPE, close_fds=True).stdout.read().strip().decode('utf-8') pci_devices = lspci_out.split('%s%s' % (os.linesep, os.linesep)) for pci_device in pci_devices: device_dict = dict() categories = pci_device.split(os.linesep) for category in categories: key, value = category.split('\t') device_dictПерезагрузить usb устройство linux] = value.strip() if 'USB' not in device_dict['Class']: continue for root, dirs, files in os.walk('/sys/bus/pci/drivers/'): slot = device_dict['Slot'] if slot in dirs: device_dict['path'] = os.path.join(root, slot) break pci_usb_list.append(device_dict) except Exception as ex: print('Failed to list pci devices! Error: %s' % ex) sys.exit(-1) return pci_usb_list def create_usb_list(): device_list = list() try: lsusb_out = Popen('lsusb -v', shell=True, bufsize=64, stdin=PIPE, stdout=PIPE, close_fds=True).stdout.read().strip().decode('utf-8') usb_devices = lsusb_out.split('%s%s' % (os.linesep, os.linesep)) for device_categories in usb_devices: if not device_categories: continue categories = device_categories.split(os.linesep) device_stuff = categories[0].strip().split() bus = device_stuff[1] device = device_stuff[3][:-1] device_dict = device_info = ' '.join(device_stuff[6:]) device_dict['description'] = device_info for category in categories: if not category: continue categoryinfo = category.strip().split() if categoryinfo[0] == 'iManufacturer': manufacturer_info = ' '.join(categoryinfo[2:]) device_dict['manufacturer'] = manufacturer_info if categoryinfo[0] == 'iProduct': device_info = ' '.join(categoryinfo[2:]) device_dict['device'] = device_info path = '/dev/bus/usb/%s/%s' % (bus, device) device_dict['path'] = path device_list.append(device_dict) except Exception as ex: print('Failed to list usb devices! Error: %s' % ex) sys.exit(-1) return device_list if 'listpci' in option: pci_usb_list = create_pci_list() for device in pci_usb_list: print('path=%s' % device['path']) print(' manufacturer=%s' % device['SVendor']) print(' device=%s' % device['SDevice']) print(' search string=%s %s' % (device['SVendor'], device['SDevice'])) sys.exit(0) if 'list' in option: usb_list = create_usb_list() for device in usb_list: print('path=%s' % device['path']) print(' description=%s' % device['description']) print(' manufacturer=%s' % device['manufacturer']) print(' device=%s' % device['device']) print(' search string=%s %s %s' % (device['description'], device['manufacturer'], device['device'])) sys.exit(0) if len(sys.argv) < 3: print(instructions) sys.exit(0) option2 = sys.argv[2] print('Resetting device: %s' % option2) # echo -n "0000:39:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/unbind;echo -n "0000:39:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/bind def reset_pci_usb_device(dev_path): folder, slot = os.path.split(dev_path) try: fp = open(os.path.join(folder, 'unbind'), 'wt') fp.write(slot) fp.close() fp = open(os.path.join(folder, 'bind'), 'wt') fp.write(slot) fp.close() print('Successfully reset %s' % dev_path) sys.exit(0) except Exception as ex: print('Failed to reset device! Error: %s' % ex) sys.exit(-1) if 'pathpci' in option: reset_pci_usb_device(option2) if 'searchpci' in option: pci_usb_list = create_pci_list() for device in pci_usb_list: text = '%s %s' % (device['SVendor'], device['SDevice']) if option2 in text: reset_pci_usb_device(device['path']) print('Failed to find device!') sys.exit(-1) def reset_usb_device(dev_path): USBDEVFS_RESET = 21780 try: f = open(dev_path, 'w', os.O_WRONLY) fcntl.ioctl(f, USBDEVFS_RESET, 0) print('Successfully reset %s' % dev_path) sys.exit(0) except Exception as ex: print('Failed to reset device! Error: %s' % ex) sys.exit(-1) if 'path' in option: reset_usb_device(option2) if 'search' in option: usb_list = create_usb_list() for device in usb_list: text = '%s %s %s' % (device['description'], device['manufacturer'], device['device']) if option2 in text: reset_usb_device(device['path']) print('Failed to find device!') sys.exit(-1) 

Источник

Читайте также:  Kali linux команды для хакеров

How do I reset an USB device without unplugging it in Linux?

Every now and then there might come a need to reset a USB device, is there a way to perform the reset in software without unplugging the device itself and then pluggin it back in? More specifically I have a webcam which gets confused when playing too much with the settings in guvcapture and then needs a reset to get back on track.

5 Answers 5

usbutils includes usbreset.

Run it without any arguments to see usage and a list of devices. It requires superuser access to actually reset devices.

Usage: usbreset PPPP:VVVV - reset by product and vendor id usbreset BBB/DDD - reset by bus and device number usbreset "Product" - reset by product name 

This allows resetting individual devices which is an improvement over some answers that reset the entire bus. It might not resolve intermediary hub/bus issues, but it's a lot less disruptive to only reset the desired device.

You could try Benjamin Close's resetusb program to reset all devices — there are no binaries available, but compiling it is rather easy. Save the source code as resetusb.c , then run:

gcc -lusb resetusb.c -o resetusb 

You can now run the tool as resetusb . Alternatively, @unhammer points to Alan Stern's single-device version (plus some hints on how to use it).

modprobe -vr ehci_hcd modprobe -v ehci_hcd 

(you could of course script this)

Some distributions may also have their own tools to restart the USB subsystem; Mandrake apparently has /etc/init.d/usb .

$ sudo modprobe -vr ehci_hcd results in modprobe: FATAL: Module ehci_hcd is builtin. on kubuntu trusty.

On my laptop with debian 8, ehci_hcd gives errors. However, rmmod ehci_pci && sleep 2 && modprobe ehci_pci works perfectly.

Let's say I want to reset /dev/sdc .

# udevadm info -q all /dev/sdc | grep DEVPATH E: DEVPATH=/devices/pci0000:00/0000:00:14.0/usb2/2-1/2-1.4/2-1.4:1.0/host2/target2:0:0/2:0:0:0/block/sdc 

I take the 2-1.4 above (yours might just be 2-1 - my device is plugged into a hub) and do:

# echo 2-1.4 > /sys/bus/usb/drivers/usb/unbind # echo 2-1.4 > /sys/bus/usb/drivers/usb/bind 

I've made a one-liner(-ish) for that: DEV="sdc"; USB=$(udevadm info -q all /dev/$DEV | grep DEVPATH | grep -o '/usb9*/[1-9,-]*' | cut -d'/' -f3); echo $USB > /sys/bus/usb/drivers/usb/unbind; echo $USB > /sys/bus/usb/drivers/usb/bind Make DEV the drive you want to reset, and run - it'll extract the USB port number and unbind/bind it (untested).

Читайте также:  Microsoft linux rdp client

You can restart the hardware abstraction layer: sudo /etc/init.d/hal restart

i think HAL is replaced by something else in the newest version of ubuntu.. so its depend of distrib..

I seriously doubt it would have worked anyway. HAL wasn't a low-level abstraction layer like the Windows component of the same name.

I've created a Python script that simplifies the whole process:

Save the script below as reset_usb.py or clone this repo.

python reset_usb.py help # Show this help sudo python reset_usb.py list # List all USB devices sudo python reset_usb.py path /dev/bus/usb/XXX/YYY # Reset USB device using path /dev/bus/usb/XXX/YYY sudo python reset_usb.py search "search terms" # Search for USB device using the search terms within the search string returned by list and reset matching device sudo python reset_usb.py listpci # List all PCI USB devices sudo python reset_usb.py pathpci /sys/bus/pci/drivers/. /XXXX:XX:XX.X # Reset PCI USB device using path /sys/bus/pci/drivers/. /XXXX:XX:XX.X sudo python reset_usb.py searchpci "search terms" # Search for PCI USB device using the search terms within the search string returned by listpci and reset matching device 
#!/usr/bin/env python import os import sys from subprocess import Popen, PIPE import fcntl instructions = ''' Usage: python reset_usb.py help : Show this help sudo python reset_usb.py list : List all USB devices sudo python reset_usb.py path /dev/bus/usb/XXX/YYY : Reset USB device using path /dev/bus/usb/XXX/YYY sudo python reset_usb.py search "search terms" : Search for USB device using the search terms within the search string returned by list and reset matching device sudo python reset_usb.py listpci : List all PCI USB devices sudo python reset_usb.py pathpci /sys/bus/pci/drivers/. /XXXX:XX:XX.X : Reset PCI USB device using path sudo python reset_usb.py searchpci "search terms" : Search for PCI USB device using the search terms within the search string returned by listpci and reset matching device ''' if len(sys.argv) < 2: print(instructions) sys.exit(0) option = sys.argv[1].lower() if 'help' in option: print(instructions) sys.exit(0) def create_pci_list(): pci_usb_list = list() try: lspci_out = Popen('lspci -Dvmm', shell=True, bufsize=64, stdin=PIPE, stdout=PIPE, close_fds=True).stdout.read().strip().decode('utf-8') pci_devices = lspci_out.split('%s%s' % (os.linesep, os.linesep)) for pci_device in pci_devices: device_dict = dict() categories = pci_device.split(os.linesep) for category in categories: key, value = category.split('\t') device_dictПерезагрузить usb устройство linux] = value.strip() if 'USB' not in device_dict['Class']: continue for root, dirs, files in os.walk('/sys/bus/pci/drivers/'): slot = device_dict['Slot'] if slot in dirs: device_dict['path'] = os.path.join(root, slot) break pci_usb_list.append(device_dict) except Exception as ex: print('Failed to list pci devices! Error: %s' % ex) sys.exit(-1) return pci_usb_list def create_usb_list(): device_list = list() try: lsusb_out = Popen('lsusb -v', shell=True, bufsize=64, stdin=PIPE, stdout=PIPE, close_fds=True).stdout.read().strip().decode('utf-8') usb_devices = lsusb_out.split('%s%s' % (os.linesep, os.linesep)) for device_categories in usb_devices: if not device_categories: continue categories = device_categories.split(os.linesep) device_stuff = categories[0].strip().split() bus = device_stuff[1] device = device_stuff[3][:-1] device_dict = device_info = ' '.join(device_stuff[6:]) device_dict['description'] = device_info for category in categories: if not category: continue categoryinfo = category.strip().split() if categoryinfo[0] == 'iManufacturer': manufacturer_info = ' '.join(categoryinfo[2:]) device_dict['manufacturer'] = manufacturer_info if categoryinfo[0] == 'iProduct': device_info = ' '.join(categoryinfo[2:]) device_dict['device'] = device_info path = '/dev/bus/usb/%s/%s' % (bus, device) device_dict['path'] = path device_list.append(device_dict) except Exception as ex: print('Failed to list usb devices! Error: %s' % ex) sys.exit(-1) return device_list if 'listpci' in option: pci_usb_list = create_pci_list() for device in pci_usb_list: print('path=%s' % device['path']) print(' manufacturer=%s' % device['SVendor']) print(' device=%s' % device['SDevice']) print(' search string=%s %s' % (device['SVendor'], device['SDevice'])) sys.exit(0) if 'list' in option: usb_list = create_usb_list() for device in usb_list: print('path=%s' % device['path']) print(' description=%s' % device['description']) print(' manufacturer=%s' % device['manufacturer']) print(' device=%s' % device['device']) print(' search string=%s %s %s' % (device['description'], device['manufacturer'], device['device'])) sys.exit(0) if len(sys.argv) < 3: print(instructions) sys.exit(0) option2 = sys.argv[2] print('Resetting device: %s' % option2) # echo -n "0000:39:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/unbind;echo -n "0000:39:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/bind def reset_pci_usb_device(dev_path): folder, slot = os.path.split(dev_path) try: fp = open(os.path.join(folder, 'unbind'), 'wt') fp.write(slot) fp.close() fp = open(os.path.join(folder, 'bind'), 'wt') fp.write(slot) fp.close() print('Successfully reset %s' % dev_path) sys.exit(0) except Exception as ex: print('Failed to reset device! Error: %s' % ex) sys.exit(-1) if 'pathpci' in option: reset_pci_usb_device(option2) if 'searchpci' in option: pci_usb_list = create_pci_list() for device in pci_usb_list: text = '%s %s' % (device['SVendor'], device['SDevice']) if option2 in text: reset_pci_usb_device(device['path']) print('Failed to find device!') sys.exit(-1) def reset_usb_device(dev_path): USBDEVFS_RESET = 21780 try: f = open(dev_path, 'w', os.O_WRONLY) fcntl.ioctl(f, USBDEVFS_RESET, 0) print('Successfully reset %s' % dev_path) sys.exit(0) except Exception as ex: print('Failed to reset device! Error: %s' % ex) sys.exit(-1) if 'path' in option: reset_usb_device(option2) if 'search' in option: usb_list = create_usb_list() for device in usb_list: text = '%s %s %s' % (device['description'], device['manufacturer'], device['device']) if option2 in text: reset_usb_device(device['path']) print('Failed to find device!') sys.exit(-1) 

Источник

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