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
|
#!/usr/bin/env python3
# Fetch a byte range from a guest file via the QEMU guest agent.
# Usage: qga_snip.py <guest_path> <offset> <length> <host_out>
import base64
import json
import socket
import sys
GUEST, OFF, LEN, HOST = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]
import os
SOCK = os.environ.get("QGA_SOCK", "/tmp/qemu-guest-agent.sock")
def recv_line(s):
buf = b""
while b"\n" not in buf:
c = s.recv(65536)
if not c:
break
buf += c
return buf.split(b"\n", 1)[0]
def cmd(s, obj):
s.sendall((json.dumps(obj) + "\r\n").encode())
return json.loads(recv_line(s))
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(30.0)
s.connect(SOCK)
h = cmd(s, {"execute": "guest-file-open",
"arguments": {"path": GUEST, "mode": "r"}})["return"]
cmd(s, {"execute": "guest-file-seek",
"arguments": {"handle": h, "offset": OFF, "whence": 0}})
r = cmd(s, {"execute": "guest-file-read",
"arguments": {"handle": h, "count": LEN}})
data = base64.b64decode(r["return"].get("buf-b64", ""))
open(HOST, "wb").write(data)
cmd(s, {"execute": "guest-file-close", "arguments": {"handle": h}})
print(f"GOT {len(data)} bytes @ {OFF} -> {HOST}")
|