Instantly share code, notes, and snippets.

@stav /usbreset.py
Last active Aug 29, 2015

Embed
What would you like to do?
send a USB port reset to a USB device
#!/usr/bin/env python
# usbreset -- send a USB port reset to a USB device
#
# http://askubuntu.com/questions/645#answer-661
#
# $ sudo usbreset.py DUB
# Looking for device: DUB
# Executing command: `lsusb | grep DUB`
# Subprocess: b'Bus 001 Device 006: ID 2001:1a02 D-Link Corp. DUB-E100 Fast...'
# Found device 001 on bus 006 for "D-Link Corp. DUB-E100 Fast Ethernet Adapt..."
from __future__ import print_function
import os
import re
import sys
import fcntl
import argparse
import subprocess
USBDEVFS_RESET = 21780
def main():
command_line = argparse.ArgumentParser(description='USB device reset')
command_line.add_argument(
'desc', metavar='DESC',
type=str, nargs='?', default='USB',
help='Device description')
options = command_line.parse_args(sys.argv[1:])
print('Looking for device:', options.desc)
lsusb_cmd = 'lsusb | grep {}'.format(options.desc)
print('Executing command: `{}`'.format(lsusb_cmd))
lsusb_out = subprocess.check_output(lsusb_cmd, shell=True)
print('Subprocess: ', lsusb_out.strip())
parts = re.search(r'Bus (?P<bus>\d+) Device (?P<dev>\d+): ID [:\d\w]+ (?P<desc>.*)$', str(lsusb_out))
bus = parts.group('bus')
dev = parts.group('dev')
desc = parts.group('desc').strip()
print('Found device {} on bus {} for "{}"'.format(bus, dev, desc))
f = open('/dev/bus/usb/{}/{}'.format(bus, dev), 'w', os.O_WRONLY)
fcntl.ioctl(f, USBDEVFS_RESET, 0)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment