Skip to content

Instantly share code, notes, and snippets.

@mukhortov
Forked from x2q/usbreset.c
Last active January 16, 2022 09:02
Show Gist options
  • Save mukhortov/b90ae7388c4ca09d82180e41a8b44c09 to your computer and use it in GitHub Desktop.
Save mukhortov/b90ae7388c4ca09d82180e41a8b44c09 to your computer and use it in GitHub Desktop.
/* usbreset -- send a USB port reset to a USB device
*
* Compile using: gcc -o usbreset usbreset.c
*
* */
#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-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;
}
@mukhortov
Copy link
Author

mukhortov commented Jan 16, 2022

  1. Download the file using wget
wget -c --no-check-certificate https://gist.githubusercontent.com/mukhortov/b90ae7388c4ca09d82180e41a8b44c09/raw/bf21dbda4a67de2c2d15d6c66b1e1bd0b1db7e1b/usbreset.c -O usbreset.c
  1. Compile C code as usbreset
cc usbreset.c -o usbreset
  1. Give execute permission to the usbreset program
chmod +x usbreset
  1. Run lsusb and find your device in the list. Remember the name of your device (ZTE, Huawei, etc)
lsusb
  1. Replace DEVICE_NAME with the device name from the previous step. The following command gets the device ID by name using lsusb and passes it as an argument to usbreset.
lsusb | grep DEVICE_NAME | cut -d' ' -f6 | xargs usbreset
  1. Add it to crontab to reset the USB device every 5 minutes. To start editing press i key.
crontab -e
  1. Add the following at the very end of the file. Make sure to replace the DEVICE_NAME with the name of your USB device. To save and exit press esc, type :wq, and hit enter.
*/5 * * * * lsusb | grep DEVICE_NAME | cut -d' ' -f6 | xargs usbreset

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment