-
Notifications
You must be signed in to change notification settings - Fork 0
/
virt-usb
executable file
·56 lines (46 loc) · 1.65 KB
/
virt-usb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python
import argparse
import contextlib
import libvirt
import sys
template = r'''
<hostdev mode='subsystem' type='usb'>
<source>
<vendor id='0x%04x'/>
<product id='0x%04x'/>
</source>
</hostdev>
'''.strip()
@contextlib.contextmanager
def libvirt_open(uri):
conn = libvirt.open(uri)
try:
yield conn
finally:
conn.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='USB passthrough helper')
parser.add_argument('-c', metavar='URI', default='qemu:///system',
help='URI to connect to')
parser.add_argument('--domain', required=True,
help='libvirt domain to attach device to')
parser.add_argument('--devices', metavar='VendorID:ProductID', nargs='+',
required=True, help='USB devices to passthrough')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--attach', action='store_true',
help='attach the devices to guest')
group.add_argument('--detach', action='store_false',
help='detach the devices from guest')
args = parser.parse_args()
try:
with libvirt_open(args.c) as conn:
domain = conn.lookupByName(args.domain)
for device in args.devices:
device = tuple(map(lambda x: int(x, 16), device.split(':')))
if args.attach:
domain.attachDevice(template % device)
else:
domain.detachDevice(template % device)
except (libvirt.libvirtError) as e:
print(e)
sys.exit(1)