qvm_run.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 main(args=None, app=None):
  88. '''Main function of qvm-run tool'''
  89. args = parser.parse_args(args, app=app)
  90. if args.color_output is None and args.filter_esc:
  91. args.color_output = '31'
  92. if args.color_output is None and os.isatty(sys.stderr.fileno()):
  93. args.color_stderr = 31
  94. if len(args.domains) > 1 and args.passio and not args.localcmd:
  95. parser.error('--passio cannot be used when more than 1 qube is chosen '
  96. 'and no --localcmd is used')
  97. if args.localcmd and not args.passio:
  98. parser.error('--localcmd have no effect without --pass-io')
  99. if args.color_output and not args.filter_esc:
  100. parser.error('--color-output must be used with --filter-escape-chars')
  101. retcode = 0
  102. run_kwargs = {}
  103. if not args.passio:
  104. run_kwargs['stdout'] = subprocess.DEVNULL
  105. run_kwargs['stderr'] = subprocess.DEVNULL
  106. else:
  107. # connect process output to stdout/err directly if --pass-io is given
  108. run_kwargs['stdout'] = None
  109. run_kwargs['stderr'] = None
  110. if isinstance(args.app, qubesadmin.app.QubesLocal) and \
  111. not args.passio and not args.localcmd and args.service:
  112. # wait=False works only in dom0; but it's still useful, to save on
  113. # simultaneous vchan connections
  114. run_kwargs['wait'] = False
  115. verbose = args.verbose - args.quiet
  116. if args.passio:
  117. verbose -= 1
  118. if args.color_output:
  119. sys.stdout.write('\033[0;{}m'.format(args.color_output))
  120. sys.stdout.flush()
  121. if args.color_stderr:
  122. sys.stderr.write('\033[0;{}m'.format(args.color_stderr))
  123. sys.stderr.flush()
  124. try:
  125. procs = []
  126. for vm in args.domains:
  127. if not args.autostart and not vm.is_running():
  128. continue
  129. try:
  130. if verbose > 0:
  131. if args.color_output:
  132. print('\033[0mRunning \'{}\' on {}\033[0;{}m'.format(
  133. args.cmd, vm.name, args.color_output),
  134. file=sys.stderr)
  135. else:
  136. print('Running \'{}\' on {}'.format(args.cmd, vm.name),
  137. file=sys.stderr)
  138. if args.gui:
  139. wait_session = vm.run_service('qubes.WaitForSession',
  140. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  141. wait_session.communicate(vm.default_user.encode())
  142. if args.passio and not args.localcmd:
  143. loop = asyncio.new_event_loop()
  144. loop.add_signal_handler(signal.SIGCHLD, loop.stop)
  145. if args.service:
  146. proc = vm.run_service(args.cmd,
  147. user=args.user,
  148. localcmd=args.localcmd,
  149. filter_esc=args.filter_esc,
  150. **run_kwargs)
  151. else:
  152. proc = vm.run_service('qubes.VMShell',
  153. user=args.user,
  154. localcmd=args.localcmd,
  155. filter_esc=args.filter_esc,
  156. **run_kwargs)
  157. proc.stdin.write(vm.prepare_input_for_vmshell(args.cmd))
  158. proc.stdin.flush()
  159. if args.passio and not args.localcmd:
  160. asyncio.ensure_future(loop.connect_read_pipe(
  161. functools.partial(DataCopyProtocol, proc.stdin,
  162. loop.stop),
  163. sys.stdin), loop=loop)
  164. loop.run_forever()
  165. loop.close()
  166. proc.stdin.close()
  167. procs.append(proc)
  168. except qubesadmin.exc.QubesException as e:
  169. if args.color_output:
  170. sys.stdout.write('\033[0m')
  171. sys.stdout.flush()
  172. vm.log.error(str(e))
  173. return -1
  174. for proc in procs:
  175. retcode = max(retcode, proc.wait())
  176. finally:
  177. if args.color_output:
  178. sys.stdout.write('\033[0m')
  179. sys.stdout.flush()
  180. if args.color_stderr:
  181. sys.stderr.write('\033[0m')
  182. sys.stderr.flush()
  183. return retcode
  184. if __name__ == '__main__':
  185. sys.exit(main())