vboxshell.py revision 3d0cb7c5e86b0051797daeb2e9d354b30ab449b3
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync#!/usr/bin/python
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync#
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# Copyright (C) 2009-2010 Sun Microsystems, Inc.
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync#
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# This file is part of VirtualBox Open Source Edition (OSE), as
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# available from http://www.virtualbox.org. This file is free software;
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# you can redistribute it and/or modify it under the terms of the GNU
e64031e20c39650a7bc902a3e1aba613b9415deevboxsync# General Public License (GPL) as published by the Free Software
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# Foundation, in version 2 as it comes in the "COPYING" file of the
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync#
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# Clara, CA 95054 USA or visit http://www.sun.com if you need
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# additional information or have any questions.
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync#
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync#################################################################################
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# This program is a simple interactive shell for VirtualBox. You can query #
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# information and issue commands from a simple command line. #
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# #
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# It also provides you with examples on how to use VirtualBox's Python API. #
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# This shell is even somewhat documented, supports TAB-completion and #
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# history if you have Python readline installed. #
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# #
cf5f6bf2704d4fff443139e10bccc6a0a7fa4b85vboxsync# Finally, shell allows arbitrary custom extensions, just create #
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# .VirtualBox/shexts/ and drop your extensions there. #
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# Enjoy. #
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync################################################################################
7420e5ee5565b181c144eabb14da0da9e8cce657vboxsync
7420e5ee5565b181c144eabb14da0da9e8cce657vboxsyncimport os,sys
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncimport traceback
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncimport shlex
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncimport time
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# Simple implementation of IConsoleCallback, one can use it as skeleton
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync# for custom implementations
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncclass GuestMonitor:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def __init__(self, mach):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync self.mach = mach
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, needsHostCursor)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onStateChange(self, state):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onStateChange state=%d" %(self.mach.name, state)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onAdditionsStateChange(self):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onAdditionsStateChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onNetworkAdapterChange(self, adapter):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onNetworkAdapterChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onSerialPortChange(self, port):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onSerialPortChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onParallelPortChange(self, port):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onParallelPortChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onStorageControllerChange(self):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onStorageControllerChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onMediumChange(self, attachment):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onMediumChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onVRDPServerChange(self):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onVRDPServerChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onUSBControllerChange(self):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onUSBControllerChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onUSBDeviceStateChange(self, device, attached, error):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onUSBDeviceStateChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onSharedFolderChange(self, scope):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onSharedFolderChange" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onRuntimeError(self, fatal, id, message):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onCanShowWindow(self):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onCanShowWindow" %(self.mach.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return True
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onShowWindow(self, winId):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%s: onShowWindow: %d" %(self.mach.name, winId)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncclass VBoxMonitor:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def __init__(self, params):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync self.vbox = params[0]
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync self.isMscom = params[1]
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync pass
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onMachineStateChange(self, id, state):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onMachineStateChange: %s %d" %(id, state)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onMachineDataChange(self,id):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onMachineDataChange: %s" %(id)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onExtraDataCanChange(self, id, key, value):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # Witty COM bridge thinks if someone wishes to return tuple, hresult
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # is one of values we want to return
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if self.isMscom:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return "", 0, True
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync else:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return True, ""
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onExtraDataChange(self, id, key, value):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onExtraDataChange: %s %s=>%s" %(id, key, value)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onMediaRegistered(self, id, type, registered):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onMediaRegistered: %s" %(id)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onMachineRegistered(self, id, registred):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onMachineRegistered: %s" %(id)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onSessionStateChange(self, id, state):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onSessionStateChange: %s %d" %(id, state)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onSnapshotTaken(self, mach, id):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onSnapshotTaken: %s %s" %(mach, id)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onSnapshotDeleted(self, mach, id):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onSnapshotDeleted: %s %s" %(mach, id)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onSnapshotChange(self, mach, id):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onSnapshotChange: %s %s" %(mach, id)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def onGuestPropertyChange(self, id, name, newValue, flags):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncg_hasreadline = 1
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsynctry:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync import readline
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync import rlcompleter
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncexcept:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync g_hasreadline = 0
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncif g_hasreadline:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync class CompleterNG(rlcompleter.Completer):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def __init__(self, dic, ctx):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync self.ctx = ctx
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return rlcompleter.Completer.__init__(self,dic)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync def complete(self, text, state):
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync """
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync taken from:
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync """
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync if text == "":
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync return ['\t',None][state]
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync else:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return rlcompleter.Completer.complete(self,text,state)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync def global_matches(self, text):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync """
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync Compute matches when text is a simple name.
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync Return a list of all names currently defined
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync in self.namespace that match.
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync """
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync matches = []
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync n = len(text)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync for list in [ self.namespace ]:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync for word in list:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if word[:n] == text:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync matches.append(word)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync try:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync for m in getMachines(self.ctx):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # although it has autoconversion, we need to cast
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # explicitly for subscripts to work
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync word = str(m.name)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if word[:n] == text:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync matches.append(word)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync word = str(m.id)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if word[0] == '{':
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync word = word[1:-1]
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if word[:n] == text:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync matches.append(word)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync except Exception,e:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync traceback.print_exc()
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print e
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return matches
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef autoCompletion(commands, ctx):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync import platform
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if not g_hasreadline:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync comps = {}
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync for (k,v) in commands.items():
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync comps[k] = None
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync completer = CompleterNG(comps, ctx)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync readline.set_completer(completer.complete)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # OSX need it
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if platform.system() == 'Darwin':
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync readline.parse_and_bind ("bind ^I rl_complete")
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync readline.parse_and_bind("tab: complete")
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncg_verbose = True
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef split_no_quotes(s):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return shlex.split(s)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef progressBar(ctx,p,wait=1000):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync try:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync while not p.completed:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "%d %%\r" %(p.percent),
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync sys.stdout.flush()
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync p.waitForCompletion(wait)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync ctx['global'].waitForEvents(0)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync except KeyboardInterrupt:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "Interrupted."
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef reportError(ctx,session,rc):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if not ctx['remote']:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print session.QueryErrorObject(rc)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef createVm(ctx,name,kind,base):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync mgr = ctx['mgr']
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync vb = ctx['vb']
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync mach = vb.createMachine(name, kind, base, "", False)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync mach.saveSettings()
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "created machine with UUID",mach.id
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync vb.registerMachine(mach)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # update cache
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync getMachines(ctx, True)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef removeVm(ctx,mach):
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync mgr = ctx['mgr']
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync vb = ctx['vb']
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync id = mach.id
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync print "removing machine ",mach.name,"with UUID",id
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync mach = vb.unregisterMachine(id)
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync if mach:
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync mach.deleteSettings()
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync # update cache
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync getMachines(ctx, True)
85e5ab5adbba74b522731762dd05ca88cb529140vboxsync
85e5ab5adbba74b522731762dd05ca88cb529140vboxsyncdef startVm(ctx,mach,type):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync mgr = ctx['mgr']
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync vb = ctx['vb']
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync perf = ctx['perf']
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync session = mgr.getSessionObject(vb)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync uuid = mach.id
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync progress = vb.openRemoteSession(session, uuid, type, "")
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync progressBar(ctx, progress, 100)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync completed = progress.completed
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync rc = int(progress.resultCode)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print "Completed:", completed, "rc:",hex(rc&0xffffffff)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if rc == 0:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # we ignore exceptions to allow starting VM even if
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # perf collector cannot be started
974de75a5a0c1d17919acfe706ebd403d9dcc440vboxsync if perf:
974de75a5a0c1d17919acfe706ebd403d9dcc440vboxsync try:
5ce202824bd2fbece9bc3b1b3de6a7abfa6b8f9avboxsync perf.setup(['*'], [mach], 10, 15)
974de75a5a0c1d17919acfe706ebd403d9dcc440vboxsync except Exception,e:
974de75a5a0c1d17919acfe706ebd403d9dcc440vboxsync print e
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if g_verbose:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync traceback.print_exc()
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # if session not opened, close doesn't make sense
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync session.close()
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync else:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync reportError(ctx,session,rc)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef getMachines(ctx, invalidate = False):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if ctx['vb'] is not None:
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync if ctx['_machlist'] is None or invalidate:
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return ctx['_machlist']
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync else:
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync return []
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsyncdef asState(var):
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync if var:
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync return 'on'
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync else:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return 'off'
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef asFlag(var):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if var:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync return 'yes'
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync else:
d0a71f63bd810b54e0359223fe53b07730154dc5vboxsync return 'no'
d0a71f63bd810b54e0359223fe53b07730154dc5vboxsync
d0a71f63bd810b54e0359223fe53b07730154dc5vboxsyncdef perfStats(ctx,mach):
d0a71f63bd810b54e0359223fe53b07730154dc5vboxsync if not ctx['perf']:
d0a71f63bd810b54e0359223fe53b07730154dc5vboxsync return
d0a71f63bd810b54e0359223fe53b07730154dc5vboxsync for metric in ctx['perf'].query(["*"], [mach]):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync print metric['name'], metric['values_as_string']
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef guestExec(ctx, machine, console, cmds):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync exec cmds
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef monitorGuest(ctx, machine, console, dur):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync console.registerCallback(cb)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if dur == -1:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # not infinity, but close enough
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync dur = 100000
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync try:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync end = time.time() + dur
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync while time.time() < end:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync ctx['global'].waitForEvents(500)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # We need to catch all exceptions here, otherwise callback will never be unregistered
7420e5ee5565b181c144eabb14da0da9e8cce657vboxsync except:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync pass
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync console.unregisterCallback(cb)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
8fa7c8ea1fd9355ab51e7592aff6c1ae0836dcbfvboxsync
8fa7c8ea1fd9355ab51e7592aff6c1ae0836dcbfvboxsyncdef monitorVBox(ctx, dur):
8fa7c8ea1fd9355ab51e7592aff6c1ae0836dcbfvboxsync vbox = ctx['vb']
8fa7c8ea1fd9355ab51e7592aff6c1ae0836dcbfvboxsync isMscom = (ctx['global'].type == 'MSCOM')
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync vbox.registerCallback(cb)
8f1c8e96fab0c5f5a8dcabeb4e20a56a8b4cea18vboxsync if dur == -1:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # not infinity, but close enough
7420e5ee5565b181c144eabb14da0da9e8cce657vboxsync dur = 100000
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync try:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync end = time.time() + dur
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync while time.time() < end:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync ctx['global'].waitForEvents(500)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync # We need to catch all exceptions here, otherwise callback will never be unregistered
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync except:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync pass
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync vbox.unregisterCallback(cb)
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsyncdef takeScreenshot(ctx,console,args):
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync from PIL import Image
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync display = console.display
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if len(args) > 0:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync f = args[0]
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync else:
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync f = "/tmp/screenshot.png"
6a97c5c107ea1c9935054f25a4fb5ca59a214b72vboxsync if len(args) > 3:
7420e5ee5565b181c144eabb14da0da9e8cce657vboxsync screen = int(args[3])
7420e5ee5565b181c144eabb14da0da9e8cce657vboxsync else:
screen = 0
(fb,xorig,yorig) = display.getFramebuffer(screen)
if len(args) > 1:
w = int(args[1])
else:
w = fb.width
if len(args) > 2:
h = int(args[2])
else:
h = fb.height
print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
data = display.takeScreenShotToArray(screen, w,h)
size = (w,h)
mode = "RGBA"
im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
im.save(f, "PNG")
def teleport(ctx,session,console,args):
if args[0].find(":") == -1:
print "Use host:port format for teleport target"
return
(host,port) = args[0].split(":")
if len(args) > 1:
passwd = args[1]
else:
passwd = ""
if len(args) > 2:
maxDowntime = int(args[2])
else:
maxDowntime = 250
port = int(port)
print "Teleporting to %s:%d..." %(host,port)
progress = console.teleport(host, port, passwd, maxDowntime)
progressBar(ctx, progress, 100)
completed = progress.completed
rc = int(progress.resultCode)
if rc == 0:
print "Success!"
else:
reportError(ctx,session,rc)
def guestStats(ctx,console,args):
guest = console.guest
# we need to set up guest statistics
if len(args) > 0 :
update = args[0]
else:
update = 1
if guest.statisticsUpdateInterval != update:
guest.statisticsUpdateInterval = update
try:
time.sleep(float(update)+0.1)
except:
# to allow sleep interruption
pass
all_stats = ctx['ifaces'].all_values('GuestStatisticType')
cpu = 0
for s in all_stats.keys():
try:
val = guest.getStatistic( cpu, all_stats[s])
print "%s: %d" %(s, val)
except:
# likely not implemented
pass
def plugCpu(ctx,machine,session,args):
cpu = int(args[0])
print "Adding CPU %d..." %(cpu)
machine.hotPlugCPU(cpu)
def unplugCpu(ctx,machine,session,args):
cpu = int(args[0])
print "Removing CPU %d..." %(cpu)
machine.hotUnplugCPU(cpu)
def mountIso(ctx,machine,session,args):
machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
machine.saveSettings()
def ginfo(ctx,console, args):
guest = console.guest
if guest.additionsActive:
vers = int(guest.additionsVersion)
print "Additions active, version %d.%d" %(vers >> 16, vers & 0xffff)
print "Support seamless: %s" %(asFlag(guest.supportsSeamless))
print "Support graphics: %s" %(asFlag(guest.supportsGraphics))
print "Baloon size: %d" %(guest.memoryBalloonSize)
print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
else:
print "No additions"
def cmdExistingVm(ctx,mach,cmd,args):
mgr=ctx['mgr']
vb=ctx['vb']
session = mgr.getSessionObject(vb)
uuid = mach.id
try:
progress = vb.openExistingSession(session, uuid)
except Exception,e:
print "Session to '%s' not open: %s" %(mach.name,e)
if g_verbose:
traceback.print_exc()
return
if str(session.state) != str(ctx['ifaces'].SessionState_Open):
print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
return
# this could be an example how to handle local only (i.e. unavailable
# in Webservices) functionality
if ctx['remote'] and cmd == 'some_local_only_command':
print 'Trying to use local only functionality, ignored'
return
console=session.console
ops={'pause': lambda: console.pause(),
'resume': lambda: console.resume(),
'powerdown': lambda: console.powerDown(),
'powerbutton': lambda: console.powerButton(),
'stats': lambda: perfStats(ctx, mach),
'guest': lambda: guestExec(ctx, mach, console, args),
'ginfo': lambda: ginfo(ctx, console, args),
'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
'save': lambda: progressBar(ctx,console.saveState()),
'screenshot': lambda: takeScreenshot(ctx,console,args),
'teleport': lambda: teleport(ctx,session,console,args),
'gueststats': lambda: guestStats(ctx, console, args),
'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
'mountiso': lambda: mountIso(ctx, session.machine, session, args)
}
try:
ops[cmd]()
except Exception, e:
print 'failed: ',e
if g_verbose:
traceback.print_exc()
session.close()
def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
session = ctx['global'].openMachineSession(mach.id)
mach = session.machine
try:
cmd(ctx, mach, args)
except Exception, e:
print 'failed: ',e
if g_verbose:
traceback.print_exc()
if save:
mach.saveSettings()
session.close()
def machById(ctx,id):
mach = None
for m in getMachines(ctx):
if m.name == id:
mach = m
break
mid = str(m.id)
if mid[0] == '{':
mid = mid[1:-1]
if mid == id:
mach = m
break
return mach
def argsToMach(ctx,args):
if len(args) < 2:
print "usage: %s [vmname|uuid]" %(args[0])
return None
id = args[1]
m = machById(ctx, id)
if m == None:
print "Machine '%s' is unknown, use list command to find available machines" %(id)
return m
def helpSingleCmd(cmd,h,sp):
if sp != 0:
spec = " [ext from "+sp+"]"
else:
spec = ""
print " %s: %s%s" %(cmd,h,spec)
def helpCmd(ctx, args):
if len(args) == 1:
print "Help page:"
names = commands.keys()
names.sort()
for i in names:
helpSingleCmd(i, commands[i][0], commands[i][2])
else:
cmd = args[1]
c = commands.get(cmd)
if c == None:
print "Command '%s' not known" %(cmd)
else:
helpSingleCmd(cmd, c[0], c[2])
return 0
def asEnumElem(ctx,enum,elem):
all = ctx['ifaces'].all_values(enum)
for e in all.keys():
if str(elem) == str(all[e]):
return e
return "<unknown>"
def enumFromString(ctx,enum,str):
all = ctx['ifaces'].all_values(enum)
return all.get(str, None)
def listCmd(ctx, args):
for m in getMachines(ctx, True):
if m.teleporterEnabled:
tele = "[T] "
else:
tele = " "
print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,asEnumElem(ctx,"SessionState", m.sessionState))
return 0
def infoCmd(ctx,args):
if (len(args) < 2):
print "usage: info [vmname|uuid]"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
os = ctx['vb'].getGuestOSType(mach.OSTypeId)
print " One can use setvar <mach> <var> <value> to change variable, using name in []."
print " Name [name]: %s" %(mach.name)
print " Description [description]: %s" %(mach.description)
print " ID [n/a]: %s" %(mach.id)
print " OS Type [via OSTypeId]: %s" %(os.description)
print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
print
print " CPUs [CPUCount]: %d" %(mach.CPUCount)
print " RAM [memorySize]: %dM" %(mach.memorySize)
print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
print " Monitors [monitorCount]: %d" %(mach.monitorCount)
print
print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
print
if mach.teleporterEnabled:
print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
print
bios = mach.BIOSSettings
print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
if mach.audioAdapter.enabled:
print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
controllers = ctx['global'].getArray(mach, 'storageControllers')
if controllers:
print
print " Controllers:"
for controller in controllers:
print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
attaches = ctx['global'].getArray(mach, 'mediumAttachments')
if attaches:
print
print " Mediums:"
for a in attaches:
print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
m = a.medium
if a.type == ctx['global'].constants.DeviceType_HardDisk:
print " HDD:"
print " Id: %s" %(m.id)
print " Location: %s" %(m.location)
print " Name: %s" %(m.name)
print " Format: %s" %(m.format)
if a.type == ctx['global'].constants.DeviceType_DVD:
print " DVD:"
if m:
print " Id: %s" %(m.id)
print " Name: %s" %(m.name)
if m.hostDrive:
print " Host DVD %s" %(m.location)
if a.passthrough:
print " [passthrough mode]"
else:
print " Virtual image at %s" %(m.location)
print " Size: %s" %(m.size)
if a.type == ctx['global'].constants.DeviceType_Floppy:
print " Floppy:"
if m:
print " Id: %s" %(m.id)
print " Name: %s" %(m.name)
if m.hostDrive:
print " Host floppy %s" %(m.location)
else:
print " Virtual image at %s" %(m.location)
print " Size: %s" %(m.size)
return 0
def startCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
if len(args) > 2:
type = args[2]
else:
type = "gui"
startVm(ctx, mach, type)
return 0
def createVmCmd(ctx, args):
if (len(args) < 3 or len(args) > 4):
print "usage: createvm name ostype <basefolder>"
return 0
name = args[1]
oskind = args[2]
if len(args) == 4:
base = args[3]
else:
base = ''
try:
ctx['vb'].getGuestOSType(oskind)
except Exception, e:
print 'Unknown OS type:',oskind
return 0
createVm(ctx, name, oskind, base)
return 0
def ginfoCmd(ctx,args):
if (len(args) < 2):
print "usage: ginfo [vmname|uuid]"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'ginfo', '')
return 0
def execInGuest(ctx,console,args):
if len(args) < 1:
print "exec in guest needs at least program name"
return
user = ""
passwd = ""
tmo = 0
print "executing %s with %s" %(args[0], args[1:])
(progress, pid) = console.guest.executeProcess(args[0], 0, args[1:], [], "", "", "", user, passwd, tmo)
print "executed with pid %d" %(pid)
def gexecCmd(ctx,args):
if (len(args) < 2):
print "usage: gexec [vmname|uuid] command args"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
gargs = args[2:]
gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args))
cmdExistingVm(ctx, mach, 'guestlambda', gargs)
return 0
def removeVmCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
removeVm(ctx, mach)
return 0
def pauseCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'pause', '')
return 0
def powerdownCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'powerdown', '')
return 0
def powerbuttonCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'powerbutton', '')
return 0
def resumeCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'resume', '')
return 0
def saveCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'save', '')
return 0
def statsCmd(ctx, args):
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'stats', '')
return 0
def guestCmd(ctx, args):
if (len(args) < 3):
print "usage: guest name commands"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
return 0
def screenshotCmd(ctx, args):
if (len(args) < 2):
print "usage: screenshot vm <file> <width> <height> <monitor>"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'screenshot', args[2:])
return 0
def teleportCmd(ctx, args):
if (len(args) < 3):
print "usage: teleport name host:port <password>"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'teleport', args[2:])
return 0
def portalsettings(ctx,mach,args):
enabled = args[0]
mach.teleporterEnabled = enabled
if enabled:
port = args[1]
passwd = args[2]
mach.teleporterPort = port
mach.teleporterPassword = passwd
def openportalCmd(ctx, args):
if (len(args) < 3):
print "usage: openportal name port <password>"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
port = int(args[2])
if (len(args) > 3):
passwd = args[3]
else:
passwd = ""
if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
startVm(ctx, mach, "gui")
return 0
def closeportalCmd(ctx, args):
if (len(args) < 2):
print "usage: closeportal name"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
if mach.teleporterEnabled:
cmdClosedVm(ctx, mach, portalsettings, [False])
return 0
def gueststatsCmd(ctx, args):
if (len(args) < 2):
print "usage: gueststats name <check interval>"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdExistingVm(ctx, mach, 'gueststats', args[2:])
return 0
def plugcpu(ctx,mach,args):
plug = args[0]
cpu = args[1]
if plug:
print "Adding CPU %d..." %(cpu)
mach.hotPlugCPU(cpu)
else:
print "Removing CPU %d..." %(cpu)
mach.hotUnplugCPU(cpu)
def plugcpuCmd(ctx, args):
if (len(args) < 2):
print "usage: plugcpu name cpuid"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
if mach.CPUHotPlugEnabled:
cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
else:
cmdExistingVm(ctx, mach, 'plugcpu', args[2])
return 0
def unplugcpuCmd(ctx, args):
if (len(args) < 2):
print "usage: unplugcpu name cpuid"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
if mach.CPUHotPlugEnabled:
cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
else:
cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
return 0
def setvar(ctx,mach,args):
expr = 'mach.'+args[0]+' = '+args[1]
print "Executing",expr
exec expr
def setvarCmd(ctx, args):
if (len(args) < 4):
print "usage: setvar [vmname|uuid] expr value"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdClosedVm(ctx, mach, setvar, args[2:])
return 0
def setvmextra(ctx,mach,args):
key = args[0]
value = args[1]
print "%s: setting %s to %s" %(mach.name, key, value)
mach.setExtraData(key, value)
def setExtraDataCmd(ctx, args):
if (len(args) < 3):
print "usage: setextra [vmname|uuid|global] key <value>"
return 0
key = args[2]
if len(args) == 4:
value = args[3]
else:
value = None
if args[1] == 'global':
ctx['vb'].setExtraData(key, value)
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
cmdClosedVm(ctx, mach, setvmextra, [key, value])
return 0
def printExtraKey(obj, key, value):
print "%s: '%s' = '%s'" %(obj, key, value)
def getExtraDataCmd(ctx, args):
if (len(args) < 2):
print "usage: getextra [vmname|uuid|global] <key>"
return 0
if len(args) == 3:
key = args[2]
else:
key = None
if args[1] == 'global':
obj = ctx['vb']
else:
obj = argsToMach(ctx,args)
if obj == None:
return 0
if key == None:
keys = obj.getExtraDataKeys()
else:
keys = [ key ]
for k in keys:
printExtraKey(args[1], k, obj.getExtraData(k))
return 0
def quitCmd(ctx, args):
return 1
def aliasCmd(ctx, args):
if (len(args) == 3):
aliases[args[1]] = args[2]
return 0
for (k,v) in aliases.items():
print "'%s' is an alias for '%s'" %(k,v)
return 0
def verboseCmd(ctx, args):
global g_verbose
g_verbose = not g_verbose
return 0
def getUSBStateString(state):
if state == 0:
return "NotSupported"
elif state == 1:
return "Unavailable"
elif state == 2:
return "Busy"
elif state == 3:
return "Available"
elif state == 4:
return "Held"
elif state == 5:
return "Captured"
else:
return "Unknown"
def hostCmd(ctx, args):
host = ctx['vb'].host
cnt = host.processorCount
print "Processor count:",cnt
for i in range(0,cnt):
print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
if host.Acceleration3DAvailable:
print "3D acceleration available"
else:
print "3D acceleration NOT available"
print "Network interfaces:"
for ni in ctx['global'].getArray(host, 'networkInterfaces'):
print " %s (%s)" %(ni.name, ni.IPAddress)
print "DVD drives:"
for dd in ctx['global'].getArray(host, 'DVDDrives'):
print " %s - %s" %(dd.name, dd.description)
print "USB devices:"
for ud in ctx['global'].getArray(host, 'USBDevices'):
print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
if ctx['perf']:
for metric in ctx['perf'].query(["*"], [host]):
print metric['name'], metric['values_as_string']
return 0
def monitorGuestCmd(ctx, args):
if (len(args) < 2):
print "usage: monitorGuest name (duration)"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
dur = 5
if len(args) > 2:
dur = float(args[2])
cmdExistingVm(ctx, mach, 'monitorGuest', dur)
return 0
def monitorVBoxCmd(ctx, args):
if (len(args) > 2):
print "usage: monitorVBox (duration)"
return 0
dur = 5
if len(args) > 1:
dur = float(args[1])
monitorVBox(ctx, dur)
return 0
def getAdapterType(ctx, type):
if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
type == ctx['global'].constants.NetworkAdapterType_Am79C973):
return "pcnet"
elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
type == ctx['global'].constants.NetworkAdapterType_I82545EM or
type == ctx['global'].constants.NetworkAdapterType_I82543GC):
return "e1000"
elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
return "virtio"
elif (type == ctx['global'].constants.NetworkAdapterType_Null):
return None
else:
raise Exception("Unknown adapter type: "+type)
def portForwardCmd(ctx, args):
if (len(args) != 5):
print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
adapterNum = int(args[2])
hostPort = int(args[3])
guestPort = int(args[4])
proto = "TCP"
session = ctx['global'].openMachineSession(mach.id)
mach = session.machine
adapter = mach.getNetworkAdapter(adapterNum)
adapterType = getAdapterType(ctx, adapter.adapterType)
profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
config = "VBoxInternal/Devices/" + adapterType + "/"
config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
mach.setExtraData(config + "/Protocol", proto)
mach.setExtraData(config + "/HostPort", str(hostPort))
mach.setExtraData(config + "/GuestPort", str(guestPort))
mach.saveSettings()
session.close()
return 0
def showLogCmd(ctx, args):
if (len(args) < 2):
print "usage: showLog <vm> <num>"
return 0
mach = argsToMach(ctx,args)
if mach == None:
return 0
log = 0;
if (len(args) > 2):
log = args[2];
uOffset = 0;
while True:
data = mach.readLog(log, uOffset, 1024*1024)
if (len(data) == 0):
break
# print adds either NL or space to chunks not ending with a NL
sys.stdout.write(data)
uOffset += len(data)
return 0
def evalCmd(ctx, args):
expr = ' '.join(args[1:])
try:
exec expr
except Exception, e:
print 'failed: ',e
if g_verbose:
traceback.print_exc()
return 0
def reloadExtCmd(ctx, args):
# maybe will want more args smartness
checkUserExtensions(ctx, commands, getHomeFolder(ctx))
autoCompletion(commands, ctx)
return 0
def runScriptCmd(ctx, args):
if (len(args) != 2):
print "usage: runScript <script>"
return 0
try:
lf = open(args[1], 'r')
except IOError,e:
print "cannot open:",args[1], ":",e
return 0
try:
for line in lf:
done = runCommand(ctx, line)
if done != 0: break
except Exception,e:
print "error:",e
if g_verbose:
traceback.print_exc()
lf.close()
return 0
def sleepCmd(ctx, args):
if (len(args) != 2):
print "usage: sleep <secs>"
return 0
try:
time.sleep(float(args[1]))
except:
# to allow sleep interrupt
pass
return 0
def shellCmd(ctx, args):
if (len(args) < 2):
print "usage: shell <commands>"
return 0
cmd = ' '.join(args[1:])
try:
os.system(cmd)
except KeyboardInterrupt:
# to allow shell command interruption
pass
return 0
def connectCmd(ctx, args):
if (len(args) > 4):
print "usage: connect [url] [username] [passwd]"
return 0
if ctx['vb'] is not None:
print "Already connected, disconnect first..."
return 0
if (len(args) > 1):
url = args[1]
else:
url = None
if (len(args) > 2):
user = args[2]
else:
user = ""
if (len(args) > 3):
passwd = args[3]
else:
passwd = ""
vbox = ctx['global'].platform.connect(url, user, passwd)
ctx['vb'] = vbox
print "Running VirtualBox version %s" %(vbox.version)
ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
return 0
def disconnectCmd(ctx, args):
if (len(args) != 1):
print "usage: disconnect"
return 0
if ctx['vb'] is None:
print "Not connected yet."
return 0
try:
ctx['global'].platform.disconnect()
except:
ctx['vb'] = None
raise
ctx['vb'] = None
return 0
def exportVMCmd(ctx, args):
import sys
if len(args) < 3:
print "usage: exportVm <machine> <path> <format> <license>"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
path = args[2]
if (len(args) > 3):
format = args[3]
else:
format = "ovf-1.0"
if (len(args) > 4):
license = args[4]
else:
license = "GPL"
app = ctx['vb'].createAppliance()
desc = mach.export(app)
desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
p = app.write(format, path)
progressBar(ctx, p)
print "Exported to %s in format %s" %(path, format)
return 0
# PC XT scancodes
scancodes = {
'a': 0x1e,
'b': 0x30,
'c': 0x2e,
'd': 0x20,
'e': 0x12,
'f': 0x21,
'g': 0x22,
'h': 0x23,
'i': 0x17,
'j': 0x24,
'k': 0x25,
'l': 0x26,
'm': 0x32,
'n': 0x31,
'o': 0x18,
'p': 0x19,
'q': 0x10,
'r': 0x13,
's': 0x1f,
't': 0x14,
'u': 0x16,
'v': 0x2f,
'w': 0x11,
'x': 0x2d,
'y': 0x15,
'z': 0x2c,
'0': 0x0b,
'1': 0x02,
'2': 0x03,
'3': 0x04,
'4': 0x05,
'5': 0x06,
'6': 0x07,
'7': 0x08,
'8': 0x09,
'9': 0x0a,
' ': 0x39,
'-': 0xc,
'=': 0xd,
'[': 0x1a,
']': 0x1b,
';': 0x27,
'\'': 0x28,
',': 0x33,
'.': 0x34,
'/': 0x35,
'\t': 0xf,
'\n': 0x1c,
'`': 0x29
};
extScancodes = {
'ESC' : [0x01],
'BKSP': [0xe],
'SPACE': [0x39],
'TAB': [0x0f],
'CAPS': [0x3a],
'ENTER': [0x1c],
'LSHIFT': [0x2a],
'RSHIFT': [0x36],
'INS': [0xe0, 0x52],
'DEL': [0xe0, 0x53],
'END': [0xe0, 0x4f],
'HOME': [0xe0, 0x47],
'PGUP': [0xe0, 0x49],
'PGDOWN': [0xe0, 0x51],
'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
'RGUI': [0xe0, 0x5c],
'LCTR': [0x1d],
'RCTR': [0xe0, 0x1d],
'LALT': [0x38],
'RALT': [0xe0, 0x38],
'APPS': [0xe0, 0x5d],
'F1': [0x3b],
'F2': [0x3c],
'F3': [0x3d],
'F4': [0x3e],
'F5': [0x3f],
'F6': [0x40],
'F7': [0x41],
'F8': [0x42],
'F9': [0x43],
'F10': [0x44 ],
'F11': [0x57],
'F12': [0x58],
'UP': [0xe0, 0x48],
'LEFT': [0xe0, 0x4b],
'DOWN': [0xe0, 0x50],
'RIGHT': [0xe0, 0x4d],
};
def keyDown(ch):
code = scancodes.get(ch, 0x0)
if code != 0:
return [code]
extCode = extScancodes.get(ch, [])
if len(extCode) == 0:
print "bad ext",ch
return extCode
def keyUp(ch):
codes = keyDown(ch)[:] # make a copy
if len(codes) > 0:
codes[len(codes)-1] += 0x80
return codes
def typeInGuest(console, text, delay):
import time
pressed = []
group = False
modGroupEnd = True
i = 0
while i < len(text):
ch = text[i]
i = i+1
if ch == '{':
# start group, all keys to be pressed at the same time
group = True
continue
if ch == '}':
# end group, release all keys
for c in pressed:
console.keyboard.putScancodes(keyUp(c))
pressed = []
group = False
continue
if ch == 'W':
# just wait a bit
time.sleep(0.3)
continue
if ch == '^' or ch == '|' or ch == '$' or ch == '_':
if ch == '^':
ch = 'LCTR'
if ch == '|':
ch = 'LSHIFT'
if ch == '_':
ch = 'LALT'
if ch == '$':
ch = 'LGUI'
if not group:
modGroupEnd = False
else:
if ch == '\\':
if i < len(text):
ch = text[i]
i = i+1
if ch == 'n':
ch = '\n'
elif ch == '&':
combo = ""
while i < len(text):
ch = text[i]
i = i+1
if ch == ';':
break
combo += ch
ch = combo
modGroupEnd = True
console.keyboard.putScancodes(keyDown(ch))
pressed.insert(0, ch)
if not group and modGroupEnd:
for c in pressed:
console.keyboard.putScancodes(keyUp(c))
pressed = []
modGroupEnd = True
time.sleep(delay)
def typeGuestCmd(ctx, args):
import sys
if len(args) < 3:
print "usage: typeGuest <machine> <text> <charDelay>"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
text = args[2]
if len(args) > 3:
delay = float(args[3])
else:
delay = 0.1
gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
cmdExistingVm(ctx, mach, 'guestlambda', gargs)
return 0
def optId(verbose,id):
if verbose:
return ": "+id
else:
return ""
def asSize(val,inBytes):
if inBytes:
return int(val)/(1024*1024)
else:
return int(val)
def listMediumsCmd(ctx,args):
if len(args) > 1:
verbose = int(args[1])
else:
verbose = False
hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
print "Hard disks:"
for hdd in hdds:
if hdd.state != ctx['global'].constants.MediumState_Created:
hdd.refreshState()
print " %s (%s)%s %dM [logical %dM]" %(hdd.location, hdd.format, optId(verbose,hdd.id),asSize(hdd.size, True), asSize(hdd.logicalSize, False))
dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
print "CD/DVD disks:"
for dvd in dvds:
if dvd.state != ctx['global'].constants.MediumState_Created:
dvd.refreshState()
print " %s (%s)%s %dM" %(dvd.location, dvd.format,optId(verbose,hdd.id),asSize(hdd.size, True))
floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
print "Floopy disks:"
for floppy in floppys:
if floppy.state != ctx['global'].constants.MediumState_Created:
floppy.refreshState()
print " %s (%s)%s %dM" %(floppy.location, floppy.format,optId(verbose,hdd.id), asSize(hdd.size, True))
return 0
def createHddCmd(ctx,args):
if (len(args) < 3):
print "usage: createHdd sizeM location type"
return 0
size = int(args[1])
loc = args[2]
if len(args) > 3:
format = args[3]
else:
format = "vdi"
hdd = ctx['vb'].createHardDisk(format, loc)
progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
ctx['progressBar'](progress)
if not hdd.id:
print "cannot create disk (file %s exist?)" %(loc)
return 0
print "created HDD at %s as %s" %(hdd.location, hdd.id)
return 0
def registerHddCmd(ctx,args):
if (len(args) < 2):
print "usage: registerHdd location"
return 0
vb = ctx['vb']
loc = args[1]
setImageId = False
imageId = ""
setParentId = False
parentId = ""
hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
print "registered HDD as %s" %(hdd.id)
return 0
def controldevice(ctx,mach,args):
[ctr,port,slot,type,id] = args
mach.attachDevice(ctr, port, slot,type,id)
def attachHddCmd(ctx,args):
if (len(args) < 4):
print "usage: attachHdd vm hdd controller port:slot"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
vb = ctx['vb']
loc = args[2]
try:
hdd = vb.findHardDisk(loc)
except:
print "no HDD with path %s registered" %(loc)
return 0
ctr = args[3]
(port,slot) = args[4].split(":")
cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
return 0
def detachVmDevice(ctx,mach,args):
atts = ctx['global'].getArray(mach, 'mediumAttachments')
hid = args[0]
for a in atts:
if a.medium:
if hid == "ALL" or a.medium.id == hid:
mach.detachDevice(a.controller, a.port, a.device)
def detachMedium(ctx,mid,medium):
cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
def detachHddCmd(ctx,args):
if (len(args) < 3):
print "usage: detachHdd vm hdd"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
vb = ctx['vb']
loc = args[2]
try:
hdd = vb.findHardDisk(loc)
except:
print "no HDD with path %s registered" %(loc)
return 0
detachMedium(ctx,mach.id,hdd)
return 0
def unregisterHddCmd(ctx,args):
if (len(args) < 2):
print "usage: unregisterHdd path <vmunreg>"
return 0
vb = ctx['vb']
loc = args[1]
if (len(args) > 2):
vmunreg = int(args[2])
else:
vmunreg = 0
try:
hdd = vb.findHardDisk(loc)
except:
print "no HDD with path %s registered" %(loc)
return 0
if vmunreg != 0:
machs = ctx['global'].getArray(hdd, 'machineIds')
try:
for m in machs:
print "Trying to detach from %s" %(m)
detachMedium(ctx,m,hdd)
except Exception, e:
print 'failed: ',e
return 0
hdd.close()
return 0
def removeHddCmd(ctx,args):
if (len(args) != 2):
print "usage: removeHdd path"
return 0
vb = ctx['vb']
loc = args[1]
try:
hdd = vb.findHardDisk(loc)
except:
print "no HDD with path %s registered" %(loc)
return 0
progress = hdd.deleteStorage()
ctx['progressBar'](progress)
return 0
def registerIsoCmd(ctx,args):
if (len(args) < 2):
print "usage: registerIso location"
return 0
vb = ctx['vb']
loc = args[1]
id = ""
iso = vb.openDVDImage(loc, id)
print "registered ISO as %s" %(iso.id)
return 0
def unregisterIsoCmd(ctx,args):
if (len(args) != 2):
print "usage: unregisterIso path"
return 0
vb = ctx['vb']
loc = args[1]
try:
dvd = vb.findDVDImage(loc)
except:
print "no DVD with path %s registered" %(loc)
return 0
progress = dvd.close()
print "Unregistered ISO at %s" %(dvd.location)
return 0
def removeIsoCmd(ctx,args):
if (len(args) != 2):
print "usage: removeIso path"
return 0
vb = ctx['vb']
loc = args[1]
try:
dvd = vb.findDVDImage(loc)
except:
print "no DVD with path %s registered" %(loc)
return 0
progress = dvd.deleteStorage()
ctx['progressBar'](progress)
print "Removed ISO at %s" %(dvd.location)
return 0
def attachIsoCmd(ctx,args):
if (len(args) < 5):
print "usage: attachIso vm iso controller port:slot"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
vb = ctx['vb']
loc = args[2]
try:
dvd = vb.findDVDImage(loc)
except:
print "no DVD with path %s registered" %(loc)
return 0
ctr = args[3]
(port,slot) = args[4].split(":")
cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
return 0
def detachIsoCmd(ctx,args):
if (len(args) < 3):
print "usage: detachIso vm iso"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
vb = ctx['vb']
loc = args[2]
try:
dvd = vb.findDVDImage(loc)
except:
print "no DVD with path %s registered" %(loc)
return 0
detachMedium(ctx,mach.id,dvd)
return 0
def mountIsoCmd(ctx,args):
if (len(args) < 5):
print "usage: mountIso vm iso controller port:slot"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
vb = ctx['vb']
loc = args[2]
try:
dvd = vb.findDVDImage(loc)
except:
print "no DVD with path %s registered" %(loc)
return 0
ctr = args[3]
(port,slot) = args[4].split(":")
cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
return 0
def unmountIsoCmd(ctx,args):
if (len(args) < 4):
print "usage: unmountIso vm controller port:slot"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
vb = ctx['vb']
ctr = args[2]
(port,slot) = args[3].split(":")
cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
return 0
def attachCtr(ctx,mach,args):
[name, bus, type] = args
ctr = mach.addStorageController(name, bus)
if type != None:
ctr.controllerType = type
def attachCtrCmd(ctx,args):
if (len(args) < 4):
print "usage: attachCtr vm cname bus <type>"
return 0
if len(args) > 4:
type = enumFromString(ctx,'StorageControllerType', args[4])
if type == None:
print "Controller type %s unknown" %(args[4])
return 0
else:
type = None
mach = ctx['machById'](args[1])
if mach is None:
return 0
bus = enumFromString(ctx,'StorageBus', args[3])
if bus is None:
print "Bus type %s unknown" %(args[3])
return 0
name = args[2]
cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
return 0
def detachCtrCmd(ctx,args):
if (len(args) < 3):
print "usage: detachCtr vm name"
return 0
mach = ctx['machById'](args[1])
if mach is None:
return 0
ctr = args[2]
cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
return 0
aliases = {'s':'start',
'i':'info',
'l':'list',
'h':'help',
'a':'alias',
'q':'quit', 'exit':'quit',
'tg': 'typeGuest',
'v':'verbose'}
commands = {'help':['Prints help information', helpCmd, 0],
'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
'removeVm':['Remove virtual machine', removeVmCmd, 0],
'pause':['Pause virtual machine', pauseCmd, 0],
'resume':['Resume virtual machine', resumeCmd, 0],
'save':['Save execution state of virtual machine', saveCmd, 0],
'stats':['Stats for virtual machine', statsCmd, 0],
'powerdown':['Power down virtual machine', powerdownCmd, 0],
'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
'list':['Shows known virtual machines', listCmd, 0],
'info':['Shows info on machine', infoCmd, 0],
'ginfo':['Shows info on guest', ginfoCmd, 0],
'gexec':['Executes program in the guest', gexecCmd, 0],
'alias':['Control aliases', aliasCmd, 0],
'verbose':['Toggle verbosity', verboseCmd, 0],
'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
'quit':['Exits', quitCmd, 0],
'host':['Show host information', hostCmd, 0],
'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
'listMediums': ['List mediums known to this VBox instance', listMediumsCmd, 0]
}
def runCommandArgs(ctx, args):
c = args[0]
if aliases.get(c, None) != None:
c = aliases[c]
ci = commands.get(c,None)
if ci == None:
print "Unknown command: '%s', type 'help' for list of known commands" %(c)
return 0
return ci[1](ctx, args)
def runCommand(ctx, cmd):
if len(cmd) == 0: return 0
args = split_no_quotes(cmd)
if len(args) == 0: return 0
return runCommandArgs(ctx, args)
#
# To write your own custom commands to vboxshell, create
# file ~/.VirtualBox/shellext.py with content like
#
# def runTestCmd(ctx, args):
# print "Testy test", ctx['vb']
# return 0
#
# commands = {
# 'test': ['Test help', runTestCmd]
# }
# and issue reloadExt shell command.
# This file also will be read automatically on startup or 'reloadExt'.
#
# Also one can put shell extensions into ~/.VirtualBox/shexts and
# they will also be picked up, so this way one can exchange
# shell extensions easily.
def addExtsFromFile(ctx, cmds, file):
if not os.path.isfile(file):
return
d = {}
try:
execfile(file, d, d)
for (k,v) in d['commands'].items():
if g_verbose:
print "customize: adding \"%s\" - %s" %(k, v[0])
cmds[k] = [v[0], v[1], file]
except:
print "Error loading user extensions from %s" %(file)
traceback.print_exc()
def checkUserExtensions(ctx, cmds, folder):
folder = str(folder)
name = os.path.join(folder, "shellext.py")
addExtsFromFile(ctx, cmds, name)
# also check 'exts' directory for all files
shextdir = os.path.join(folder, "shexts")
if not os.path.isdir(shextdir):
return
exts = os.listdir(shextdir)
for e in exts:
addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
def getHomeFolder(ctx):
if ctx['remote'] or ctx['vb'] is None:
return os.path.join(os.path.expanduser("~"), ".VirtualBox")
else:
return ctx['vb'].homeFolder
def interpret(ctx):
if ctx['remote']:
commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
vbox = ctx['vb']
if vbox is not None:
print "Running VirtualBox version %s" %(vbox.version)
ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
else:
ctx['perf'] = None
home = getHomeFolder(ctx)
checkUserExtensions(ctx, commands, home)
autoCompletion(commands, ctx)
# to allow to print actual host information, we collect info for
# last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
if ctx['perf']:
try:
ctx['perf'].setup(['*'], [vbox.host], 10, 15)
except:
pass
while True:
try:
cmd = raw_input("vbox> ")
done = runCommand(ctx, cmd)
if done != 0: break
except KeyboardInterrupt:
print '====== You can type quit or q to leave'
break
except EOFError:
break;
except Exception,e:
print e
if g_verbose:
traceback.print_exc()
ctx['global'].waitForEvents(0)
try:
# There is no need to disable metric collection. This is just an example.
if ct['perf']:
ctx['perf'].disable(['*'], [vbox.host])
except:
pass
def runCommandCb(ctx, cmd, args):
args.insert(0, cmd)
return runCommandArgs(ctx, args)
def runGuestCommandCb(ctx, id, guestLambda, args):
mach = machById(ctx,id)
if mach == None:
return 0
args.insert(0, guestLambda)
cmdExistingVm(ctx, mach, 'guestlambda', args)
return 0
def main(argv):
style = None
autopath = False
argv.pop(0)
while len(argv) > 0:
if argv[0] == "-w":
style = "WEBSERVICE"
if argv[0] == "-a":
autopath = True
argv.pop(0)
if autopath:
cwd = os.getcwd()
vpp = os.environ.get("VBOX_PROGRAM_PATH")
if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
vpp = cwd
print "Autodetected VBOX_PROGRAM_PATH as",vpp
os.environ["VBOX_PROGRAM_PATH"] = cwd
sys.path.append(os.path.join(vpp, "sdk", "installer"))
from vboxapi import VirtualBoxManager
g_virtualBoxManager = VirtualBoxManager(style, None)
ctx = {'global':g_virtualBoxManager,
'mgr':g_virtualBoxManager.mgr,
'vb':g_virtualBoxManager.vbox,
'ifaces':g_virtualBoxManager.constants,
'remote':g_virtualBoxManager.remote,
'type':g_virtualBoxManager.type,
'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
'machById': lambda id: machById(ctx,id),
'argsToMach': lambda args: argsToMach(ctx,args),
'progressBar': lambda p: progressBar(ctx,p),
'typeInGuest': typeInGuest,
'_machlist':None
}
interpret(ctx)
g_virtualBoxManager.deinit()
del g_virtualBoxManager
if __name__ == '__main__':
main(sys.argv)