Skip to content

Instantly share code, notes, and snippets.

@arifbalik
Last active September 4, 2023 13:14
Show Gist options
  • Save arifbalik/6f5ef8ee3dbc410491fe2d766337c40f to your computer and use it in GitHub Desktop.
Save arifbalik/6f5ef8ee3dbc410491fe2d766337c40f to your computer and use it in GitHub Desktop.
USB/IP Host Bringup

USB/IP Setup Guide

USB/IP allows you to share USB devices over IP networks, enabling remote access to devices as if they were connected locally. This guide outlines the setup process for both the server and client sides of USB/IP.

Server Setup

Install Linux Tools

To begin, you need to install the necessary Linux tools on your server. Use the following command:

sudo apt-get install linux-tools-generic

Load Kernel Module

Load the USB/IP host kernel module using the following command:

sudo modprobe usbip_host

Add Module Exec to PATH

You should add the module exec path to your system's PATH variable. This step helps your system locate the necessary binaries. Run the following command:

export PATH="/usr/lib/linux-tools/$(uname -r):$PATH"

Please note that the '5.4.0-159-generic' part in the path may be specific to your installation. Adjust it accordingly.

Start USBIP Daemon

Initiate the USB/IP daemon to facilitate device sharing:

sudo usbipd &

Depending on your installation, the path to the daemon may vary.

Bind the USB Device

Bind the USB device you want to share using the following command:

sudo usbip bind -b <device-bus-id>

Replace <device-bus-id> with the actual bus ID of the USB device.

Client Setup

Download Latest Release

Begin by downloading the latest release of the USB/IP Windows client from the repository available at:

https://github.com/vadimgrn/usbip-win2

Enable Windows Test Signing Mode

To allow the installation of unsigned drivers (required for USB/IP), enable Windows Test Signing Mode. Execute the following command in an elevated Command Prompt:

bcdedit.exe /set testsigning on

Reboot your system to apply the changes.

Attach to Remote Device

Attach to the remote USB device using the USB/IP client. Execute the following command:

usbip attach -r <usbip-server-ip> -b <device-bus-id>

Replace <usbip-server-ip> with the IP address of the USB/IP server and <device-bus-id> with the actual bus ID of the USB device.

By following these steps, you can set up USB/IP for sharing USB devices over IP networks. This enables remote access to USB devices as if they were directly connected to your local machine.

@arifbalik
Copy link
Author

A useful script that checks the usb ports and outputs when a new device is inserted and removed

import re
import json
import os
import time
import argparse

def parse_output(output):
    devices = []
    lines = output.split('\n')

    current_device = None
    for line in lines:
        line = line.strip()
        if line.startswith('- busid'):
            if current_device:
                devices.append(current_device)
            match = re.match(r"- busid (\d+-\d+) \(([\w:]+)\)", line)
            if match:
                busid, vendor_device = match.groups()
                current_device = {
                    'busid': busid,
                    'vendor_device': vendor_device,
                }
        elif line.strip() and current_device:
            match = re.match(r"(.+) : (.+) \(([\w:]+)\)", line)
            if match:
                vendor_name, device_name, mac_address = match.groups()
                current_device['vendor_name'] = vendor_name.strip()
                current_device['device_name'] = device_name.strip()
                current_device['mac_address'] = mac_address.strip()

    if current_device:
        devices.append(current_device)

    return devices

previous_devices = []

def main():
    parser = argparse.ArgumentParser(description="Check for new USB devices periodically.")
    parser.add_argument("--delay", type=int, default=2, help="Delay time in seconds between checks")
    parser.add_argument("--verbose", type=bool, default=False, help="Verbose output")
 
    args = parser.parse_args()

    previous_devices = []

    while True:
        # Run the shell command and capture its output
        command = "usbip list -l"
        output = os.popen(command).read()

        # Parse the output to get the current devices
        current_devices = parse_output(output)

        # Compare current devices with previous devices
        new_devices = [device for device in current_devices if device not in previous_devices]

        removed_devices = [device for device in previous_devices if device not in current_devices]

        if new_devices:
            print("New device(s) connected:")
            for device in new_devices:
                print(f"- busid {device['busid']} ({device['device_name']})")

        if removed_devices:
            print("Device(s) removed:")
            for device in removed_devices:
                print(f"- busid {device['busid']} ({device['device_name']})")

        elif args.verbose is True:
            print("No change in device list.")

        # Update previous devices for the next iteration
        previous_devices = current_devices

        # Wait for the specified delay time before running the command again
        time.sleep(args.delay)

if __name__ == "__main__":
    main()

@arifbalik
Copy link
Author

arifbalik commented Sep 4, 2023

BUGFIX: usbip: error: failed to open /usr/share/hwdata//usb.ids

On ubuntu usbip throws an error and can't recognize devices because it can not find the description file usb.ids. We can create a link to solve the issue.

mkdir  /usr/share/hwdata//usb.ids
ln -sv  /var/lib/usbutils/usb.ids /usr/share/hwdata//usb.ids

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