Skip to main content

max / alloy

1.1 KB · 45 lines History Blame Raw
1 #!/usr/bin/env python3
2 """Send a shell command to the guest's serial debug shell and read the reply.
3
4 serial.py "cmd" run and read for 5s
5 serial.py "cmd" 20 run and read for 20s
6 serial.py --read 5 read only
7 """
8 import socket, sys, time, os
9
10 SCRATCH = os.environ.get(
11 "VM_STATE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "state")
12 )
13 s = socket.socket(socket.AF_UNIX)
14 s.connect(os.path.join(SCRATCH, "serial.sock"))
15 s.settimeout(0.5)
16
17
18 def drain():
19 out = b""
20 try:
21 while True:
22 c = s.recv(65536)
23 if not c:
24 break
25 out += c
26 except (socket.timeout, BlockingIOError):
27 pass
28 return out
29
30
31 if sys.argv[1] == "--read":
32 time.sleep(float(sys.argv[2]))
33 sys.stdout.write(drain().decode(errors="replace"))
34 sys.exit()
35
36 drain()
37 cmd = sys.argv[1]
38 secs = float(sys.argv[2]) if len(sys.argv) > 2 else 5.0
39 s.sendall(("\n" + cmd + "\n").encode())
40 end = time.time() + secs
41 out = b""
42 while time.time() < end:
43 out += drain()
44 sys.stdout.write(out.decode(errors="replace"))
45