qvm_run.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. ''' qvm-run tool'''
  21. import os
  22. import signal
  23. import sys
  24. import asyncio
  25. import functools
  26. import subprocess
  27. import qubesadmin.tools
  28. import qubesadmin.exc
  29. parser = qubesadmin.tools.QubesArgumentParser(vmname_nargs='+')
  30. parser.add_argument('--user', '-u', metavar='USER',
  31. help='run command in a qube as USER (available only from dom0)')
  32. parser.add_argument('--autostart', '--auto', '-a',
  33. action='store_true', default=True,
  34. help='option ignored, this is default')
  35. parser.add_argument('--no-autostart', '--no-auto', '-n',
  36. action='store_false',
  37. help='do not autostart qube')
  38. parser.add_argument('--pass-io', '-p',
  39. action='store_true', dest='passio', default=False,
  40. help='pass stdio from remote program')
  41. parser.add_argument('--localcmd', metavar='COMMAND',
  42. help='with --pass-io, pass stdio to the given program')
  43. parser.add_argument('--gui',
  44. action='store_true', default=True,
  45. help='run the command with GUI (default on)')
  46. parser.add_argument('--no-gui', '--nogui',
  47. action='store_false', dest='gui',
  48. help='run the command without GUI')
  49. parser.add_argument('--colour-output', '--color-output', metavar='COLOUR',
  50. action='store', dest='color_output', default=None,
  51. help='mark the qube output with given ANSI colour (ie. "31" for red)')
  52. parser.add_argument('--colour-stderr', '--color-stderr', metavar='COLOUR',
  53. action='store', dest='color_stderr', default=None,
  54. help='mark the qube stderr with given ANSI colour (ie. "31" for red)')
  55. parser.add_argument('--no-colour-output', '--no-color-output',
  56. action='store_false', dest='color_output',
  57. help='disable colouring the stdio')
  58. parser.add_argument('--no-colour-stderr', '--no-color-stderr',
  59. action='store_false', dest='color_stderr',
  60. help='disable colouring the stderr')
  61. parser.add_argument('--filter-escape-chars',
  62. action='store_true', dest='filter_esc',
  63. default=os.isatty(sys.stdout.fileno()),
  64. help='filter terminal escape sequences (default if output is terminal)')
  65. parser.add_argument('--no-filter-escape-chars',
  66. action='store_false', dest='filter_esc',
  67. help='do not filter terminal escape sequences; DANGEROUS when output is a'
  68. ' terminal emulator')
  69. parser.add_argument('--service',
  70. action='store_true', dest='service',
  71. help='run a qrexec service (named by COMMAND) instead of shell command')
  72. parser.add_argument('cmd', metavar='COMMAND',
  73. help='command to run')
  74. class DataCopyProtocol(asyncio.Protocol):
  75. '''Simple protocol to copy received data into another stream'''
  76. def __init__(self, target_stream, eof_callback=None):
  77. self.target_stream = target_stream
  78. self.eof_callback = eof_callback
  79. def data_received(self, data):
  80. '''Handle received data'''
  81. self.target_stream.write(data)
  82. self.target_stream.flush()
  83. def eof_received(self):
  84. '''Handle received EOF'''
  85. if self.eof_callback:
  86. self.eof_callback()
  87. def stop_loop_if_terminated(proc, loop):
  88. '''Stop event loop if given process is terminated'''
  89. if proc.poll():
  90. loop.stop()
  91. def main(args=None, app=None):
  92. '''Main function of qvm-run tool'''
  93. args = parser.parse_args(args, app=app)
  94. if args.color_output is None and args.filter_esc:
  95. args.color_output = '31'
  96. if args.color_output is None and os.isatty(sys.stderr.fileno()):
  97. args.color_stderr = 31
  98. if len(args.domains) > 1 and args.passio and not args.localcmd:
  99. parser.error('--passio cannot be used when more than 1 qube is chosen '
  100. 'and no --localcmd is used')
  101. if args.localcmd and not args.passio:
  102. parser.error('--localcmd have no effect without --pass-io')
  103. if args.color_output and not args.filter_esc:
  104. parser.error('--color-output must be used with --filter-escape-chars')
  105. retcode = 0
  106. run_kwargs = {}
  107. if not args.passio:
  108. run_kwargs['stdout'] = subprocess.DEVNULL
  109. run_kwargs['stderr'] = subprocess.DEVNULL
  110. else:
  111. # connect process output to stdout/err directly if --pass-io is given
  112. run_kwargs['stdout'] = None
  113. run_kwargs['stderr'] = None
  114. if isinstance(args.app, qubesadmin.app.QubesLocal) and \
  115. not args.passio and not args.localcmd and args.service:
  116. # wait=False works only in dom0; but it's still useful, to save on
  117. # simultaneous vchan connections
  118. run_kwargs['wait'] = False
  119. verbose = args.verbose - args.quiet
  120. if args.passio:
  121. verbose -= 1
  122. if args.color_output:
  123. sys.stdout.write('\033[0;{}m'.format(args.color_output))
  124. sys.stdout.flush()
  125. if args.color_stderr:
  126. sys.stderr.write('\033[0;{}m'.format(args.color_stderr))
  127. sys.stderr.flush()
  128. try:
  129. procs = []
  130. for vm in args.domains:
  131. if not args.autostart and not vm.is_running():
  132. continue
  133. try:
  134. if verbose > 0:
  135. if args.color_output:
  136. print('\033[0mRunning \'{}\' on {}\033[0;{}m'.format(
  137. args.cmd, vm.name, args.color_output),
  138. file=sys.stderr)
  139. else:
  140. print('Running \'{}\' on {}'.format(args.cmd, vm.name),
  141. file=sys.stderr)
  142. if args.gui:
  143. wait_session = vm.run_service('qubes.WaitForSession',
  144. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  145. wait_session.communicate(vm.default_user.encode())
  146. if args.service:
  147. proc = vm.run_service(args.cmd,
  148. user=args.user,
  149. localcmd=args.localcmd,
  150. filter_esc=args.filter_esc,
  151. **run_kwargs)
  152. else:
  153. proc = vm.run_service('qubes.VMShell',
  154. user=args.user,
  155. localcmd=args.localcmd,
  156. filter_esc=args.filter_esc,
  157. **run_kwargs)
  158. proc.stdin.write(vm.prepare_input_for_vmshell(args.cmd))
  159. proc.stdin.flush()
  160. if args.passio and not args.localcmd:
  161. loop = asyncio.new_event_loop()
  162. loop.add_signal_handler(signal.SIGCHLD,
  163. functools.partial(stop_loop_if_terminated, proc, loop))
  164. asyncio.ensure_future(loop.connect_read_pipe(
  165. functools.partial(DataCopyProtocol, proc.stdin,
  166. loop.stop),
  167. sys.stdin), loop=loop)
  168. stop_loop_if_terminated(proc, loop)
  169. loop.run_forever()
  170. loop.close()
  171. proc.stdin.close()
  172. procs.append(proc)
  173. except qubesadmin.exc.QubesException as e:
  174. if args.color_output:
  175. sys.stdout.write('\033[0m')
  176. sys.stdout.flush()
  177. vm.log.error(str(e))
  178. return -1
  179. for proc in procs:
  180. retcode = max(retcode, proc.wait())
  181. finally:
  182. if args.color_output:
  183. sys.stdout.write('\033[0m')
  184. sys.stdout.flush()
  185. if args.color_stderr:
  186. sys.stderr.write('\033[0m')
  187. sys.stderr.flush()
  188. return retcode
  189. if __name__ == '__main__':
  190. sys.exit(main())