Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Disable and enable a specific USB device.
#! /usr/bin/python3
import os
import argparse
from time import sleep
PATH = '/sys/bus/usb/devices/'
def reset_device(key, value, coerce, sleep_time):
for device_dir, dirs, files in os.walk(PATH, followlinks=True):
if device_dir != PATH:
dirs[:] = []
if key in files:
with open(os.path.join(device_dir, key), 'r') as f:
d = coerce(f.read().strip())
if d == value:
break
else:
print("No such device")
return
print('Device found at: ' + device_dir)
if input('Sure you want to reset? (y/n): ').lower() == 'y':
reset_file = os.path.join(device_dir, 'authorized')
with open(reset_file, 'wb') as f:
f.write(b'0')
if sleep_time:
sleep(sleep_time)
with open(reset_file, 'wb') as f:
f.write(b'1')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', type=int, help="the device number of the device to reset (as seen in lsusb)")
parser.add_argument('-s', type=str, help="the device serial number (as seen in v4l)")
parser.add_argument('-t', type=float, default=0, help="the seconds to disable the device for")
args = parser.parse_args()
if args.d is not None:
reset_device('devnum', args.d, int, args.t)
elif args.s is not None:
reset_device('serial', args.s, str, args.t)
else:
parser.print_help()
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.