qemu-monitor 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import telnetlib
  5. import common
  6. class Main(common.LkmcCliFunction):
  7. def __init__(self):
  8. super().__init__(
  9. description='''\
  10. Run a command on the QEMU monitor of a running QEMU instance
  11. If the stdin is a terminal, open an interact shell. Otherwise,
  12. run commands from stdin and quit.
  13. ''',
  14. )
  15. self.add_argument(
  16. 'command',
  17. help='If given, run this command and quit',
  18. nargs='*',
  19. )
  20. def timed_main(self):
  21. def write_and_read(tn, cmd, prompt):
  22. tn.write(cmd.encode('utf-8'))
  23. return '\n'.join(tn.read_until(prompt).decode('utf-8').splitlines()[1:])[:-len(prompt)]
  24. with telnetlib.Telnet('localhost', self.env['qemu_monitor_port']) as tn:
  25. prompt = b'\n(qemu) '
  26. # Couldn't disable server echo, so just removing the write for now.
  27. # https://stackoverflow.com/questions/12421799/how-to-disable-telnet-echo-in-python-telnetlib
  28. # sock = tn.get_socket()
  29. # sock.send(telnetlib.IAC + telnetlib.WILL + telnetlib.ECHO)
  30. if os.isatty(sys.stdin.fileno()):
  31. if self.env['command'] == []:
  32. print(tn.read_until(prompt).decode('utf-8'), end='')
  33. tn.interact()
  34. else:
  35. tn.read_until(prompt)
  36. print(write_and_read(tn, ' '.join(self.env['command']) + '\n', prompt))
  37. else:
  38. tn.read_until(prompt)
  39. print(write_and_read(tn, sys.stdin.read() + '\n', prompt))
  40. if __name__ == '__main__':
  41. Main().cli()