vncshot.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python3
  2. # vncshot.py <vnc unix socket> <out.png> - one full frame from QEMU's VNC server. QMP's screendump has no surface with
  3. # virtio-vga-gl + egl-headless, the VNC server gets the frames read back from the GPU.
  4. import socket, struct, sys
  5. from PIL import Image
  6. def recv(s, n):
  7. data = b''
  8. while len(data) < n:
  9. chunk = s.recv(n - len(data))
  10. if not chunk:
  11. raise EOFError('VNC server closed the connection')
  12. data += chunk
  13. return data
  14. def main():
  15. s = socket.socket(socket.AF_UNIX)
  16. s.connect(sys.argv[1])
  17. s.sendall(recv(s, 12)) # same protocol version back
  18. types = recv(s, recv(s, 1)[0])
  19. if 1 not in types:
  20. raise RuntimeError('VNC server wants authentication')
  21. s.sendall(b'\x01')
  22. if struct.unpack('>I', recv(s, 4))[0] != 0:
  23. raise RuntimeError('VNC security handshake failed')
  24. s.sendall(b'\x01') # shared
  25. width, height = struct.unpack('>HH', recv(s, 4))
  26. recv(s, 16)
  27. recv(s, struct.unpack('>I', recv(s, 4))[0])
  28. # 32 bpp, depth 24, little endian, true colour, BGRX
  29. s.sendall(struct.pack('>B3xBBBBHHHBBB3x', 0, 32, 24, 0, 1, 255, 255, 255, 16, 8, 0))
  30. s.sendall(struct.pack('>BBH', 2, 0, 1) + struct.pack('>i', 0)) # raw encoding only
  31. s.sendall(struct.pack('>BBHHHH', 3, 0, 0, 0, width, height))
  32. image = Image.new('RGB', (width, height))
  33. while True:
  34. kind = recv(s, 1)[0]
  35. if kind == 0:
  36. recv(s, 1)
  37. for _ in range(struct.unpack('>H', recv(s, 2))[0]):
  38. x, y, w, h, encoding = struct.unpack('>HHHHi', recv(s, 12))
  39. if encoding == -223: # desktop size
  40. width, height = w, h
  41. image = Image.new('RGB', (width, height))
  42. s.sendall(struct.pack('>BBHHHH', 3, 0, 0, 0, width, height))
  43. continue
  44. if encoding != 0:
  45. raise RuntimeError('unexpected encoding %d' % encoding)
  46. image.paste(Image.frombytes('RGB', (w, h), recv(s, w * h * 4), 'raw', 'BGRX'), (x, y))
  47. break
  48. elif kind == 2:
  49. continue
  50. elif kind == 3:
  51. recv(s, 3)
  52. recv(s, struct.unpack('>I', recv(s, 4))[0])
  53. elif kind == 1:
  54. recv(s, 3)
  55. recv(s, 6 * struct.unpack('>H', recv(s, 2))[0])
  56. image.save(sys.argv[2])
  57. main()