如何从命令行重新设置USB设备?

分享于 

4分钟阅读

ubuntu

  繁體

是否可以重置USB设备的连接,而无需从PC机上断开/连接?


答案1

将以下内容另存为usbreset.c


/* usbreset -- send a USB port reset to a USB device */



#include <stdio.h>


#include <unistd.h>


#include <fcntl.h>


#include <errno.h>


#include <sys/ioctl.h>



#include <linux/usbdevice_fs.h>



int main(int argc, char **argv)


{


 const char *filename;


 int fd;


 int rc;



 if (argc != 2) {


 fprintf(stderr,"Usage: usbreset device-filenamen");


 return 1;


 }


 filename = argv[1];



 fd = open(filename, O_WRONLY);


 if (fd < 0) {


 perror("Error opening output file");


 return 1;


 }



 printf("Resetting USB device %sn", filename);


 rc = ioctl(fd, USBDEVFS_RESET, 0);


 if (rc < 0) {


 perror("Error in ioctl");


 return 1;


 }


 printf("Reset successfuln");



 close(fd);


 return 0;


}



在终端中运行以下命令:

  • 编译程序:

    
    $ cc usbreset.c -o usbreset
    
    
    
    
  • 获取要重置的USB设备的总线和设备ID:

    
    $ lsusb 
    
    
    Bus 002 Device 003: ID 0fe9:9010 DVICO 
    
    
    
    
  • 使我们编译的程序可执行:

    
    $ chmod +x usbreset
    
    
    
    
  • 使用sudo权限执行程序;对<Bus><Device> id进行必要的替换,方法是运行lsusb命令:

    
    $ sudo ./usbreset /dev/bus/usb/002/003 
    
    
    
    
  • 以上程序的源代码:http://marc.info/?l=linux-usb&m=121459435621262&w=2


  • 答案2

    无需外部应用程序

    
    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"
    
    
    
    
    
    for X in /sys/bus/usb/devices/*; do 
    
    
     echo"$X"
    
    
     cat"$X/idVendor" 2>/dev/null 
    
    
     cat"$X/idProduct" 2>/dev/null
    
    
     echo
    
    
    done
    
    
    
    

    答案3

    重置所有USB1/2/3附加端口[1]:

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

    答案4

    需要在python脚本中实现自动化,

    
    #!/usr/bin/env python
    
    
    import os
    
    
    import sys
    
    
    from subprocess import Popen, PIPE
    
    
    import fcntl
    
    
    driver = sys.argv[-1]
    
    
    print"resetting driver:", driver
    
    
    USBDEVFS_RESET= 21780
    
    
    
    try:
    
    
     lsusb_out = Popen("lsusb | grep -i %s"%driver, shell=True, bufsize=64, stdin=PIPE, stdout=PIPE, close_fds=True).stdout.read().strip().split()
    
    
     bus = lsusb_out[1]
    
    
     device = lsusb_out[3][:-1]
    
    
     f = open("/dev/bus/usb/%s/%s"%(bus, device), 'w', os.O_WRONLY)
    
    
     fcntl.ioctl(f, USBDEVFS_RESET, 0)
    
    
    except Exception, msg:
    
    
     print"failed to reset device:", msg
    
    
    
    

    COM  COMM  Comma  命令行  USB  重设  
    相关文章