qvm-run 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #!/usr/bin/python2
  2. # -*- encoding: utf8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. #
  23. #
  24. from qubes.qubes import QubesVmCollection
  25. from qubes.qubes import QubesException
  26. from qubes.notify import notify_error_qubes_manager
  27. from qubes.notify import tray_notify,tray_notify_error,tray_notify_init
  28. from optparse import OptionParser
  29. import sys
  30. import os
  31. import os.path
  32. def vm_run_cmd(vm, cmd, options):
  33. if options.pause:
  34. if options.verbose:
  35. print >> sys.stderr, "Pausing VM: '{0}'...".format(vm.name)
  36. vm.pause()
  37. return 0
  38. if options.unpause:
  39. if options.verbose:
  40. print >> sys.stderr, "UnPausing VM: '{0}'...".format(vm.name)
  41. vm.unpause()
  42. return 0
  43. if options.verbose:
  44. print >> sys.stderr, "Running command on VM: '{0}'...".format(vm.name)
  45. if options.passio and options.color_output is not None:
  46. print "\033[0;%dm" % options.color_output,
  47. try:
  48. def tray_notify_generic(level, str):
  49. if level == "info":
  50. tray_notify(str, label=vm.label)
  51. elif level == "error":
  52. tray_notify_error(str)
  53. return vm.run(cmd, autostart = options.auto,
  54. verbose = options.verbose,
  55. user = options.user,
  56. notify_function = tray_notify_generic if options.tray else None,
  57. passio = options.passio, localcmd = options.localcmd,
  58. gui = options.gui, filter_esc = options.filter_esc)
  59. except QubesException as err:
  60. if options.passio and options.color_output is not None:
  61. sys.stdout.write("\033[0m")
  62. if options.tray:
  63. tray_notify_error(str(err))
  64. notify_error_qubes_manager(vm.name, str(err))
  65. print >> sys.stderr, "ERROR(%s): %s" % (str(vm.name), str(err))
  66. return 1
  67. finally:
  68. if options.passio and options.color_output is not None:
  69. sys.stdout.write("\033[0m")
  70. def main():
  71. usage = "usage: %prog [options] [<vm-name>] [<cmd>]"
  72. parser = OptionParser (usage)
  73. parser.add_option ("-q", "--quiet", action="store_false", dest="verbose", default=True)
  74. parser.add_option ("-a", "--auto", action="store_true", dest="auto", default=False,
  75. help="Auto start the VM if not running")
  76. parser.add_option ("-u", "--user", action="store", dest="user", default=None,
  77. help="Run command in a VM as a specified user")
  78. parser.add_option ("--tray", action="store_true", dest="tray", default=False,
  79. help="Use tray notifications instead of stdout" )
  80. parser.add_option ("--all", action="store_true", dest="run_on_all_running", default=False,
  81. help="Run command on all currently running VMs (or all paused, in case of --unpause)")
  82. parser.add_option ("--exclude", action="append", dest="exclude_list",
  83. help="When --all is used: exclude this VM name (may be "
  84. "repeated)")
  85. parser.add_option ("--pause", action="store_true", dest="pause", default=False,
  86. help="Do 'xl pause' for the VM(s) (can be combined this with --all)")
  87. parser.add_option ("--unpause", action="store_true", dest="unpause", default=False,
  88. help="Do 'xl unpause' for the VM(s) (can be combined this with --all)")
  89. parser.add_option ("-p", "--pass-io", action="store_true", dest="passio", default=False,
  90. help="Pass stdin/stdout/stderr from remote program (implies -q)")
  91. parser.add_option ("--localcmd", action="store", dest="localcmd", default=None,
  92. help="With --pass-io, pass stdin/stdout/stderr to the given program")
  93. parser.add_option ("--nogui", action="store_false", dest="gui", default=True,
  94. help="Run command without gui")
  95. parser.add_option ("--filter-escape-chars", action="store_true",
  96. dest="filter_esc",
  97. default=os.isatty(sys.stdout.fileno()),
  98. help="Filter terminal escape sequences (default if "
  99. "output is terminal)")
  100. parser.add_option("--no-filter-escape-chars", action="store_false",
  101. dest="filter_esc",
  102. help="Do not filter terminal escape sequences - "
  103. "overrides --filter-escape-chars, DANGEROUS when "
  104. "output is terminal")
  105. parser.add_option("--no-color-output", action="store_false",
  106. dest="color_output", default=None,
  107. help="Disable marking VM output with red color")
  108. parser.add_option("--color-output", action="store", type="int",
  109. dest="color_output",
  110. help="Force marking VM output with given ANSI style ("
  111. "use 31 for red)")
  112. (options, args) = parser.parse_args ()
  113. if options.passio and options.run_on_all_running:
  114. parser.error ("Options --all and --pass-io cannot be used together")
  115. if options.passio:
  116. options.verbose = False
  117. if options.color_output is None:
  118. if os.isatty(sys.stdout.fileno()):
  119. options.color_output = 31
  120. elif options.color_output is False:
  121. options.color_output = None
  122. if (options.pause or options.unpause):
  123. takes_cmd_argument = False
  124. else:
  125. takes_cmd_argument = True
  126. if options.run_on_all_running:
  127. if len(args) < 1 and takes_cmd_argument:
  128. parser.error ("You must provide a command to execute on all the VMs.")
  129. if len(args) > 1 or ((not takes_cmd_argument) and len(args) > 0):
  130. parser.error ("To many arguments...")
  131. cmdstr = args[0] if takes_cmd_argument else None
  132. else:
  133. if len (args) < 1 and not takes_cmd_argument:
  134. parser.error ("You must specify the VM name to pause/unpause.")
  135. if len (args) < 2 and takes_cmd_argument:
  136. parser.error ("You must specify the VM name and the command to execute in the VM.")
  137. if len (args) > 2 or ((not takes_cmd_argument) and len(args) > 1):
  138. parser.error ("To many arguments...")
  139. vmname = args[0]
  140. cmdstr = args[1] if takes_cmd_argument else None
  141. if options.tray:
  142. tray_notify_init()
  143. qvm_collection = QubesVmCollection()
  144. qvm_collection.lock_db_for_reading()
  145. qvm_collection.load()
  146. qvm_collection.unlock_db()
  147. vms_list = []
  148. if options.run_on_all_running:
  149. all_vms = [vm for vm in qvm_collection.values()]
  150. for vm in all_vms:
  151. if options.exclude_list is not None and vm.name in options.exclude_list:
  152. continue
  153. if vm.qid == 0:
  154. continue
  155. if (options.unpause and vm.is_paused()) or (not options.unpause and vm.is_running()):
  156. vms_list.append (vm)
  157. # disable options incompatible with --all
  158. options.passio = False
  159. else:
  160. vm = qvm_collection.get_vm_by_name(vmname)
  161. if vm is None:
  162. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system!".format(vmname)
  163. exit(1)
  164. vms_list.append(vm)
  165. retcode = 0
  166. for vm in vms_list:
  167. r = vm_run_cmd(vm, cmdstr, options)
  168. retcode = max(r, retcode)
  169. exit(retcode)
  170. main()