Created
March 11, 2021 12:03
-
-
Save vitezfh/ee8d08dcc3c599b7b7c3c7377adac2c2 to your computer and use it in GitHub Desktop.
USB Switch using usbip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -x | |
# This is a tool that emulates a usb switch by leveraging usbip | |
# The script is needed on two machines | |
# PC: 1 PC: 2 | |
# ############### ############## | |
# # # -- ./switch --> # # | |
# # SERVER # # CLIENT # | |
# # # <-- ./switch -- # # | |
# ############### ############## | |
# | ^ | |
# bus 1-2 - - - - - usbip - - - - - / | |
# | | | |
# ############# + + + + + + + | |
# # keyboard1 # + keyboard1 + | |
# ############# + + + + + + + | |
# TIP: You can key-bind this script or call it from console | |
# NOTE: you need the usbipd service running on the server; | |
# do: " sudo usbipd -D " or enable and start the usbipd service as usual | |
# NOTE: in void linux, the packaged usbipd service entry doesn't work... do it manually | |
sudo modprobe usbip_host usbip_core || exit 1 | |
####################### | |
#### CONFIG START | |
## The $SERVER and $CLIENT are adresses; but the hostnames are | |
### in the machines' /etc/hostname files respectively | |
SERVER=${SERVER-svwork} | |
SERVER_HOSTNAME=${SERVER_HOSTNAME-svwork} | |
CLIENT=${CLIENT-hyrican} | |
CLIENT_HOSTNAME=${CLIENT_HOSTNAME-void-usb} | |
# Multiple are allowed, e.g. usb_buses="1-5 1-3 1-7" | |
# Tip: to find out what devices you'd like to share from the server, do: sudo usbip list -l | |
usb_buses="1-5" | |
#### CONFIG END | |
###################### | |
bind_usb() { | |
sudo usbip bind -b $1 | |
} | |
release_usb() { | |
sudo usbip unbind -b $1 | |
} | |
attach_usb() { | |
ssh $CLIENT "sudo usbip attach -r $SERVER -b $1" | |
} | |
release_usb() { | |
ssh $SERVER "sudo usbip unbind -b $1" | |
} | |
release_usb_locally() { | |
sudo usbip unbind -b $1 | |
} | |
check_client() { | |
# Also loads vhci-hcd on client, just in case | |
ssh -q -o "ConnectTimeout=1" $USER@$CLIENT "sudo modprobe vhci-hcd && exit" | |
return $? | |
} | |
if [[ "$HOSTNAME" == "$CLIENT_HOSTNAME" ]] ; then | |
echo "Releasing devices..." | |
for bus in $usb_buses ; do release_usb $bus ; done ; exit | |
elif check_client; then | |
for bus in $usb_buses ; do | |
if bind_usb $bus; then | |
attach_usb $bus | |
else | |
release_usb_locally $bus | |
release_usb $bus | |
fi | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment