Changeset 46478 in vbox for trunk/src/VBox/Frontends/VBoxShell
- Timestamp:
- Jun 10, 2013 4:31:35 PM (12 years ago)
- svn:sync-xref-src-repo-rev:
- 86321
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/VBox/Frontends/VBoxShell/vboxshell.py
r44649 r46478 2 2 3 3 """ 4 Copyright (C) 2009-201 2Oracle Corporation4 Copyright (C) 2009-2013 Oracle Corporation 5 5 6 6 This file is part of VirtualBox Open Source Edition (OSE), as … … 26 26 ################################################################################ 27 27 28 import os, sys28 import os, sys 29 29 import traceback 30 30 import shlex … … 33 33 import platform 34 34 from optparse import OptionParser 35 36 g_batchmode = False 37 g_scripfile = None 38 g_cmd = None 39 g_hasreadline = True 35 from pprint import pprint 36 37 g_fBatchMode = False 38 g_sScriptFile = None 39 g_sCmd = None 40 g_fHasReadline = True 40 41 try: 41 if g_hasreadline: 42 import readline 43 import rlcompleter 44 except: 45 g_hasreadline = False 46 47 48 g_prompt = "vbox> " 49 50 g_hascolors = True 51 term_colors = { 42 import readline 43 import rlcompleter 44 except ImportError: 45 g_fHasReadline = False 46 47 g_sPrompt = "vbox> " 48 49 g_fHasColors = True 50 g_aTermColors = { 52 51 'red':'\033[31m', 53 52 'blue':'\033[94m', … … 57 56 'cyan':'\033[36m' 58 57 } 59 def colored(string,color): 60 if not g_hascolors: 61 return string 62 global term_colors 63 col = term_colors.get(color,None) 58 def colored(strg, color): 59 """ 60 Translates a string to one including coloring settings, if enabled. 61 """ 62 if not g_fHasColors: 63 return strg 64 col = g_aTermColors.get(color, None) 64 65 if col: 65 return col+str(string)+'\033[0m' 66 else: 67 return string 68 69 if g_hasreadline: 70 import string 71 class CompleterNG(rlcompleter.Completer): 72 def __init__(self, dic, ctx): 73 self.ctx = ctx 74 return rlcompleter.Completer.__init__(self,dic) 75 76 def complete(self, text, state): 77 """ 78 taken from: 79 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812 80 """ 81 if False and text == "": 82 return ['\t',None][state] 83 else: 84 return rlcompleter.Completer.complete(self,text,state) 85 86 def canBePath(self, phrase,word): 87 return word.startswith('/') 88 89 def canBeCommand(self, phrase, word): 90 spaceIdx = phrase.find(" ") 91 begIdx = readline.get_begidx() 92 firstWord = (spaceIdx == -1 or begIdx < spaceIdx) 93 if firstWord: 94 return True 95 if phrase.startswith('help'): 96 return True 97 return False 98 99 def canBeMachine(self,phrase,word): 100 return not self.canBePath(phrase,word) and not self.canBeCommand(phrase, word) 101 102 def global_matches(self, text): 103 """ 104 Compute matches when text is a simple name. 105 Return a list of all names currently defined 106 in self.namespace that match. 107 """ 108 109 matches = [] 110 phrase = readline.get_line_buffer() 111 112 try: 113 if self.canBePath(phrase,text): 114 (dir,rest) = os.path.split(text) 115 n = len(rest) 116 for word in os.listdir(dir): 117 if n == 0 or word[:n] == rest: 118 matches.append(os.path.join(dir,word)) 119 120 if self.canBeCommand(phrase,text): 121 n = len(text) 122 for list in [ self.namespace ]: 123 for word in list: 124 if word[:n] == text: 66 return col+str(strg)+'\033[0m' 67 else: 68 return strg 69 70 if g_fHasReadline: 71 class CompleterNG(rlcompleter.Completer): 72 def __init__(self, dic, ctx): 73 self.ctx = ctx 74 rlcompleter.Completer.__init__(self, dic) 75 76 def complete(self, text, state): 77 """ 78 taken from: 79 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812 80 """ 81 if False and text == "": 82 return ['\t', None][state] 83 else: 84 return rlcompleter.Completer.complete(self, text, state) 85 86 def canBePath(self, _phrase, word): 87 return word.startswith('/') 88 89 def canBeCommand(self, phrase, _word): 90 spaceIdx = phrase.find(" ") 91 begIdx = readline.get_begidx() 92 firstWord = (spaceIdx == -1 or begIdx < spaceIdx) 93 if firstWord: 94 return True 95 if phrase.startswith('help'): 96 return True 97 return False 98 99 def canBeMachine(self, phrase, word): 100 return not self.canBePath(phrase, word) and not self.canBeCommand(phrase, word) 101 102 def global_matches(self, text): 103 """ 104 Compute matches when text is a simple name. 105 Return a list of all names currently defined 106 in self.namespace that match. 107 """ 108 109 matches = [] 110 phrase = readline.get_line_buffer() 111 112 try: 113 if self.canBePath(phrase, text): 114 (directory, rest) = os.path.split(text) 115 c = len(rest) 116 for word in os.listdir(directory): 117 if c == 0 or word[:c] == rest: 118 matches.append(os.path.join(directory, word)) 119 120 if self.canBeCommand(phrase, text): 121 c = len(text) 122 for lst in [ self.namespace ]: 123 for word in lst: 124 if word[:c] == text: 125 matches.append(word) 126 127 if self.canBeMachine(phrase, text): 128 c = len(text) 129 for mach in getMachines(self.ctx, False, True): 130 # although it has autoconversion, we need to cast 131 # explicitly for subscripts to work 132 word = re.sub("(?<!\\\\) ", "\\ ", str(mach.name)) 133 if word[:c] == text: 125 134 matches.append(word) 126 127 if self.canBeMachine(phrase,text): 128 n = len(text) 129 for m in getMachines(self.ctx, False, True): 130 # although it has autoconversion, we need to cast 131 # explicitly for subscripts to work 132 word = re.sub("(?<!\\\\) ", "\\ ", str(m.name)) 133 if word[:n] == text: 134 matches.append(word) 135 word = str(m.id) 136 if word[:n] == text: 137 matches.append(word) 138 139 except Exception,e: 140 printErr(e) 141 if g_verbose: 142 traceback.print_exc() 143 144 return matches 145 146 def autoCompletion(commands, ctx): 147 if not g_hasreadline: 148 return 149 150 comps = {} 151 for (k,v) in commands.items(): 152 comps[k] = None 153 completer = CompleterNG(comps, ctx) 154 readline.set_completer(completer.complete) 155 delims = readline.get_completer_delims() 156 readline.set_completer_delims(re.sub("[\\./-]", "", delims)) # remove some of the delimiters 157 readline.parse_and_bind("set editing-mode emacs") 158 # OSX need it 159 if platform.system() == 'Darwin': 160 # see http://www.certif.com/spec_help/readline.html 161 readline.parse_and_bind ("bind ^I rl_complete") 162 readline.parse_and_bind ("bind ^W ed-delete-prev-word") 163 # Doesn't work well 164 # readline.parse_and_bind ("bind ^R em-inc-search-prev") 165 readline.parse_and_bind("tab: complete") 166 167 168 g_verbose = False 135 word = str(mach.id) 136 if word[:c] == text: 137 matches.append(word) 138 139 except Exception, e: 140 printErr(self.ctx, e) 141 if g_fVerbose: 142 traceback.print_exc() 143 144 return matches 145 146 def autoCompletion(cmds, ctx): 147 if not g_fHasReadline: 148 return 149 150 comps = {} 151 for (key, _value) in cmds.items(): 152 comps[key] = None 153 completer = CompleterNG(comps, ctx) 154 readline.set_completer(completer.complete) 155 delims = readline.get_completer_delims() 156 readline.set_completer_delims(re.sub("[\\./-]", "", delims)) # remove some of the delimiters 157 readline.parse_and_bind("set editing-mode emacs") 158 # OSX need it 159 if platform.system() == 'Darwin': 160 # see http://www.certif.com/spec_help/readline.html 161 readline.parse_and_bind ("bind ^I rl_complete") 162 readline.parse_and_bind ("bind ^W ed-delete-prev-word") 163 # Doesn't work well 164 # readline.parse_and_bind ("bind ^R em-inc-search-prev") 165 readline.parse_and_bind("tab: complete") 166 167 168 g_fVerbose = False 169 169 170 170 def split_no_quotes(s): 171 171 return shlex.split(s) 172 172 173 def progressBar(ctx, p,wait=1000):173 def progressBar(ctx, progress, wait=1000): 174 174 try: 175 while not p .completed:176 print "%s %%\r" % (colored(str(p.percent),'red')),175 while not progress.completed: 176 print "%s %%\r" % (colored(str(progress.percent), 'red')), 177 177 sys.stdout.flush() 178 p .waitForCompletion(wait)178 progress.waitForCompletion(wait) 179 179 ctx['global'].waitForEvents(0) 180 if int(p .resultCode) != 0:181 reportError(ctx, p )180 if int(progress.resultCode) != 0: 181 reportError(ctx, progress) 182 182 return 1 183 183 except KeyboardInterrupt: 184 184 print "Interrupted." 185 185 ctx['interrupt'] = True 186 if p .cancelable:186 if progress.cancelable: 187 187 print "Canceling task..." 188 p.cancel() 189 return 0 190 191 def printErr(ctx,e): 192 print colored(str(e), 'red') 193 194 def reportError(ctx,progress): 195 ei = progress.errorInfo 196 if ei: 197 print colored("Error in module '%s': %s" %(ei.component, ei.text), 'red') 198 199 def colCat(ctx,str): 200 return colored(str, 'magenta') 201 202 def colVm(ctx,vm): 203 return colored(vm, 'blue') 204 205 def colPath(ctx,p): 206 return colored(p, 'green') 207 208 def colSize(ctx,m): 209 return colored(m, 'red') 210 211 def colPci(ctx,vm): 212 return colored(vm, 'green') 213 214 def colDev(ctx,vm): 215 return colored(vm, 'cyan') 216 217 def colSizeM(ctx,m): 218 return colored(str(m)+'M', 'red') 219 220 def createVm(ctx,name,kind): 221 mgr = ctx['mgr'] 222 vb = ctx['vb'] 223 mach = vb.createMachine("", name, [], kind, "") 188 progress.cancel() 189 return 0 190 191 def printErr(_ctx, e): 192 print colored(str(e), 'red') 193 194 def reportError(_ctx, progress): 195 errorinfo = progress.errorInfo 196 if errorinfo: 197 print colored("Error in module '%s': %s" % (errorinfo.component, errorinfo.text), 'red') 198 199 def colCat(_ctx, strg): 200 return colored(strg, 'magenta') 201 202 def colVm(_ctx, vmname): 203 return colored(vmname, 'blue') 204 205 def colPath(_ctx, path): 206 return colored(path, 'green') 207 208 def colSize(_ctx, byte): 209 return colored(byte, 'red') 210 211 def colPci(_ctx, pcidev): 212 return colored(pcidev, 'green') 213 214 def colDev(_ctx, pcidev): 215 return colored(pcidev, 'cyan') 216 217 def colSizeM(_ctx, mbyte): 218 return colored(str(mbyte)+'M', 'red') 219 220 def createVm(ctx, name, kind): 221 vbox = ctx['vb'] 222 mach = vbox.createMachine("", name, [], kind, "") 224 223 mach.saveSettings() 225 print "created machine with UUID", mach.id226 vb .registerMachine(mach)224 print "created machine with UUID", mach.id 225 vbox.registerMachine(mach) 227 226 # update cache 228 227 getMachines(ctx, True) 229 228 230 def removeVm(ctx,mach): 231 mgr = ctx['mgr'] 232 vb = ctx['vb'] 233 id = mach.id 234 print "removing machine ",mach.name,"with UUID",id 229 def removeVm(ctx, mach): 230 uuid = mach.id 231 print "removing machine ", mach.name, "with UUID", uuid 235 232 cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"]) 236 233 mach = mach.unregister(ctx['global'].constants.CleanupMode_Full) 237 234 if mach: 238 235 mach.deleteSettings() 239 236 # update cache 240 237 getMachines(ctx, True) 241 238 242 def startVm(ctx, mach,type):239 def startVm(ctx, mach, vmtype): 243 240 mgr = ctx['mgr'] 244 vb = ctx['vb']241 vbox = ctx['vb'] 245 242 perf = ctx['perf'] 246 session = mgr.getSessionObject(vb )247 progress = mach.launchVMProcess(session, type, "")243 session = mgr.getSessionObject(vbox) 244 progress = mach.launchVMProcess(session, vmtype, "") 248 245 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0: 249 246 # we ignore exceptions to allow starting VM even if 250 247 # perf collector cannot be started 251 248 if perf: 252 try:253 perf.setup(['*'], [mach], 10, 15)254 except Exception,e:255 printErr(ctx, e)256 if g_verbose:257 traceback.print_exc()249 try: 250 perf.setup(['*'], [mach], 10, 15) 251 except Exception, e: 252 printErr(ctx, e) 253 if g_fVerbose: 254 traceback.print_exc() 258 255 session.unlockMachine() 259 256 260 257 class CachedMach: 261 def __init__(self, mach): 258 def __init__(self, mach): 259 if mach.accessible: 262 260 self.name = mach.name 263 self.id = mach.id 264 265 def cacheMachines(ctx,list): 261 else: 262 self.name = '<inaccessible>' 263 self.id = mach.id 264 265 def cacheMachines(_ctx, lst): 266 266 result = [] 267 for m in list: 268 try: 269 elem = CachedMach(m) 270 result.append(elem) 271 except: 272 pass 267 for mach in lst: 268 elem = CachedMach(mach) 269 result.append(elem) 273 270 return result 274 271 … … 277 274 if ctx['_machlist'] is None or invalidate: 278 275 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines') 279 ctx['_machlistsimple'] = cacheMachines(ctx, ctx['_machlist'])276 ctx['_machlistsimple'] = cacheMachines(ctx, ctx['_machlist']) 280 277 if simple: 281 278 return ctx['_machlistsimple'] … … 298 295 299 296 def getFacilityStatus(ctx, guest, facilityType): 300 (status, ts) = guest.getFacilityStatus(facilityType)297 (status, _timestamp) = guest.getFacilityStatus(facilityType) 301 298 return asEnumElem(ctx, 'AdditionsFacilityStatus', status) 302 299 … … 310 307 exec cmds 311 308 312 def printMouseEvent( ctx, mev):313 print "Mouse : absolute=%d x=%d y=%d z=%d buttons=%x" % (mev.absolute, mev.x, mev.y, mev.z, mev.buttons)309 def printMouseEvent(_ctx, mev): 310 print "Mouse : absolute=%d x=%d y=%d z=%d buttons=%x" % (mev.absolute, mev.x, mev.y, mev.z, mev.buttons) 314 311 315 312 def printKbdEvent(ctx, kev): 316 313 print "Kbd: ", ctx['global'].getArray(kev, 'scancodes') 317 314 318 def monitorSource(ctx, e s, active, dur):319 def handleEventImpl(ev ):320 type = ev.type321 print "got event: %s %s" %(str(type), asEnumElem(ctx, 'VBoxEventType',type))322 iftype == ctx['global'].constants.VBoxEventType_OnMachineStateChanged:323 scev = ctx['global'].queryInterface(ev, 'IMachineStateChangedEvent')324 325 print "machine state event: mach=%s state=%s" %(scev.machineId, scev.state)326 eliftype == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged:327 gpcev = ctx['global'].queryInterface(ev, 'IGuestPropertyChangedEvent')328 329 print "guest property change: name=%s value=%s" %(gpcev.name, gpcev.value)330 eliftype == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged:331 psev = ctx['global'].queryInterface(ev, 'IMousePointerShapeChangedEvent')332 333 334 335 336 337 print "pointer shape event: w=%d h=%d shape len=%d" %(psev.width, psev.height, len(shape))338 eliftype == ctx['global'].constants.VBoxEventType_OnGuestMouse:339 mev = ctx['global'].queryInterface(ev, 'IGuestMouseEvent')340 341 342 eliftype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:343 kev = ctx['global'].queryInterface(ev, 'IGuestKeyboardEvent')344 345 315 def monitorSource(ctx, eventSource, active, dur): 316 def handleEventImpl(event): 317 evtype = event.type 318 print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)) 319 if evtype == ctx['global'].constants.VBoxEventType_OnMachineStateChanged: 320 scev = ctx['global'].queryInterface(event, 'IMachineStateChangedEvent') 321 if scev: 322 print "machine state event: mach=%s state=%s" % (scev.machineId, scev.state) 323 elif evtype == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged: 324 gpcev = ctx['global'].queryInterface(event, 'IGuestPropertyChangedEvent') 325 if gpcev: 326 print "guest property change: name=%s value=%s" % (gpcev.name, gpcev.value) 327 elif evtype == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged: 328 psev = ctx['global'].queryInterface(event, 'IMousePointerShapeChangedEvent') 329 if psev: 330 shape = ctx['global'].getArray(psev, 'shape') 331 if shape is None: 332 print "pointer shape event - empty shape" 333 else: 334 print "pointer shape event: w=%d h=%d shape len=%d" % (psev.width, psev.height, len(shape)) 335 elif evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse: 336 mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent') 337 if mev: 338 printMouseEvent(ctx, mev) 339 elif evtype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard: 340 kev = ctx['global'].queryInterface(event, 'IGuestKeyboardEvent') 341 if kev: 342 printKbdEvent(ctx, kev) 346 343 347 344 class EventListener: 348 def __init__(self, arg):349 pass350 351 def handleEvent(self, ev):352 try:353 # a bit convoluted QI to make it work with MS COM354 handleEventImpl(ctx['global'].queryInterface(ev, 'IEvent'))355 except:356 traceback.print_exc()357 345 def __init__(self, arg): 346 pass 347 348 def handleEvent(self, event): 349 try: 350 # a bit convoluted QI to make it work with MS COM 351 handleEventImpl(ctx['global'].queryInterface(event, 'IEvent')) 352 except: 353 traceback.print_exc() 354 pass 358 355 359 356 if active: 360 357 listener = ctx['global'].createListener(EventListener) 361 358 else: 362 listener = e s.createListener()359 listener = eventSource.createListener() 363 360 registered = False 364 361 if dur == -1: … … 366 363 dur = 100000 367 364 try: 368 e s.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], active)365 eventSource.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], active) 369 366 registered = True 370 367 end = time.time() + dur … … 373 370 ctx['global'].waitForEvents(500) 374 371 else: 375 ev = es.getEvent(listener, 500)376 if ev :377 handleEventImpl(ev )372 event = eventSource.getEvent(listener, 500) 373 if event: 374 handleEventImpl(event) 378 375 # otherwise waitable events will leak (active listeners ACK automatically) 379 e s.eventProcessed(listener, ev)376 eventSource.eventProcessed(listener, event) 380 377 # We need to catch all exceptions here, otherwise listener will never be unregistered 381 378 except: … … 383 380 pass 384 381 if listener and registered: 385 e s.unregisterListener(listener)386 387 388 tsLast = 0389 def recordDemo(ctx, console, file , dur):390 demo = open(file , 'w')391 header ="VM="+console.machine.name+"\n"382 eventSource.unregisterListener(listener) 383 384 385 g_tsLast = 0 386 def recordDemo(ctx, console, filename, dur): 387 demo = open(filename, 'w') 388 header = "VM=" + console.machine.name + "\n" 392 389 demo.write(header) 393 390 394 global tsLast395 tsLast = time.time()391 global g_tsLast 392 g_tsLast = time.time() 396 393 397 394 def stamp(): 398 global tsLast395 global g_tsLast 399 396 tsCur = time.time() 400 rv = int((tsCur-tsLast)*1000)401 tsLast = tsCur402 return rv403 404 def handleEventImpl(ev ):405 type = ev.type406 #print "got event: %s %s" %(str(type), asEnumElem(ctx, 'VBoxEventType',type))407 iftype == ctx['global'].constants.VBoxEventType_OnGuestMouse:408 mev = ctx['global'].queryInterface(ev, 'IGuestMouseEvent')409 410 l = "%d: m %d %d %d %d %d %d\n" %(stamp(), mev.absolute, mev.x, mev.y, mev.z, mev.w, mev.buttons)411 demo.write(l)412 eliftype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:413 kev = ctx['global'].queryInterface(ev, 'IGuestKeyboardEvent')414 415 l = "%d: k %s\n" %(stamp(), str(ctx['global'].getArray(kev, 'scancodes')))416 demo.write(l)397 timePassed = int((tsCur-g_tsLast)*1000) 398 g_tsLast = tsCur 399 return timePassed 400 401 def handleEventImpl(event): 402 evtype = event.type 403 #print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)) 404 if evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse: 405 mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent') 406 if mev: 407 line = "%d: m %d %d %d %d %d %d\n" % (stamp(), mev.absolute, mev.x, mev.y, mev.z, mev.w, mev.buttons) 408 demo.write(line) 409 elif evtype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard: 410 kev = ctx['global'].queryInterface(event, 'IGuestKeyboardEvent') 411 if kev: 412 line = "%d: k %s\n" % (stamp(), str(ctx['global'].getArray(kev, 'scancodes'))) 413 demo.write(line) 417 414 418 415 listener = console.eventSource.createListener() … … 420 417 # we create an aggregated event source to listen for multiple event sources (keyboard and mouse in our case) 421 418 agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource]) 422 demo = open(file , 'w')423 header ="VM="+console.machine.name+"\n"419 demo = open(filename, 'w') 420 header = "VM=" + console.machine.name + "\n" 424 421 demo.write(header) 425 422 if dur == -1: … … 431 428 end = time.time() + dur 432 429 while time.time() < end: 433 ev = agg.getEvent(listener, 1000)434 if ev :435 handleEventImpl(ev )430 event = agg.getEvent(listener, 1000) 431 if event: 432 handleEventImpl(event) 436 433 # keyboard/mouse events aren't waitable, so no need for eventProcessed 437 434 # We need to catch all exceptions here, otherwise listener will never be unregistered … … 444 441 445 442 446 def playbackDemo(ctx, console, file , dur):447 demo = open(file , 'r')443 def playbackDemo(ctx, console, filename, dur): 444 demo = open(filename, 'r') 448 445 449 446 if dur == -1: … … 465 462 if time.time() > end: 466 463 break 467 m = basere.search(line)468 if m is None:464 match = basere.search(line) 465 if match is None: 469 466 continue 470 467 471 dict = m.groupdict()472 stamp = dict['s']473 params = dict['p']474 type =dict['t']468 rdict = match.groupdict() 469 stamp = rdict['s'] 470 params = rdict['p'] 471 rtype = rdict['t'] 475 472 476 473 time.sleep(float(stamp)/1000) 477 474 478 if type == 'k':479 codes =kre.findall(params)480 #print "KBD:", codes475 if rtype == 'k': 476 codes = kre.findall(params) 477 #print "KBD:", codes 481 478 kbd.putScancodes(codes) 482 elif type == 'm':479 elif rtype == 'm': 483 480 mm = mre.search(params) 484 481 if mm is not None: … … 486 483 if mdict['a'] == '1': 487 484 # absolute 488 #print "MA: ", mdict['x'],mdict['y'],mdict['z'],mdict['b']485 #print "MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b'] 489 486 mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 490 487 else: 491 #print "MR: ", mdict['x'],mdict['y'],mdict['b']488 #print "MR: ", mdict['x'], mdict['y'], mdict['b'] 492 489 mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 493 490 … … 501 498 502 499 503 def takeScreenshotOld( ctx,console,args):500 def takeScreenshotOld(_ctx, console, args): 504 501 from PIL import Image 505 502 display = console.display … … 512 509 else: 513 510 screen = 0 514 (fbw, fbh, fbbpp) = display.getScreenResolution(screen)511 (fbw, fbh, _fbbpp) = display.getScreenResolution(screen) 515 512 if len(args) > 1: 516 513 w = int(args[1]) … … 522 519 h = fbh 523 520 524 print "Saving screenshot (%d x %d) screen %d in %s..." % (w,h,screen,f)525 data = display.takeScreenShotToArray(screen, w, h)526 size = (w, h)521 print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f) 522 data = display.takeScreenShotToArray(screen, w, h) 523 size = (w, h) 527 524 mode = "RGBA" 528 525 im = Image.frombuffer(mode, size, str(data), "raw", mode, 0, 1) 529 526 im.save(f, "PNG") 530 527 531 def takeScreenshot( ctx,console,args):528 def takeScreenshot(_ctx, console, args): 532 529 display = console.display 533 530 if len(args) > 0: … … 539 536 else: 540 537 screen = 0 541 (fbw, fbh, fbbpp) = display.getScreenResolution(screen)538 (fbw, fbh, _fbbpp) = display.getScreenResolution(screen) 542 539 if len(args) > 1: 543 540 w = int(args[1]) … … 549 546 h = fbh 550 547 551 print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f) 552 data = display.takeScreenShotPNGToArray(screen, w,h) 553 size = (w,h) 554 file = open(f, 'wb') 555 file.write(data) 556 file.close() 557 558 def teleport(ctx,session,console,args): 548 print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f) 549 data = display.takeScreenShotPNGToArray(screen, w, h) 550 pngfile = open(f, 'wb') 551 pngfile.write(data) 552 pngfile.close() 553 554 def teleport(ctx, _session, console, args): 559 555 if args[0].find(":") == -1: 560 556 print "Use host:port format for teleport target" 561 557 return 562 (host, port) = args[0].split(":")558 (host, port) = args[0].split(":") 563 559 if len(args) > 1: 564 560 passwd = args[1] … … 567 563 568 564 if len(args) > 2: 569 maxDowntime 565 maxDowntime = int(args[2]) 570 566 else: 571 567 maxDowntime = 250 572 568 573 569 port = int(port) 574 print "Teleporting to %s:%d..." % (host,port)570 print "Teleporting to %s:%d..." % (host, port) 575 571 progress = console.teleport(host, port, passwd, maxDowntime) 576 572 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0: 577 573 print "Success!" 578 574 else: 579 reportError(ctx, progress)580 581 582 def guestStats(ctx, console,args):575 reportError(ctx, progress) 576 577 578 def guestStats(ctx, console, args): 583 579 guest = console.guest 584 580 # we need to set up guest statistics … … 599 595 try: 600 596 val = guest.getStatistic( cpu, all_stats[s]) 601 print "%s: %d" % (s, val)597 print "%s: %d" % (s, val) 602 598 except: 603 599 # likely not implemented 604 600 pass 605 601 606 def plugCpu( ctx,machine,session,args):602 def plugCpu(_ctx, machine, _session, args): 607 603 cpu = int(args[0]) 608 print "Adding CPU %d..." % (cpu)604 print "Adding CPU %d..." % (cpu) 609 605 machine.hotPlugCPU(cpu) 610 606 611 def unplugCpu( ctx,machine,session,args):607 def unplugCpu(_ctx, machine, _session, args): 612 608 cpu = int(args[0]) 613 print "Removing CPU %d..." % (cpu)609 print "Removing CPU %d..." % (cpu) 614 610 machine.hotUnplugCPU(cpu) 615 611 616 def mountIso( ctx,machine,session,args):612 def mountIso(_ctx, machine, _session, args): 617 613 machine.mountMedium(args[0], args[1], args[2], args[3], args[4]) 618 614 machine.saveSettings() 619 615 620 def cond(c, v1,v2):616 def cond(c, v1, v2): 621 617 if c: 622 618 return v1 … … 624 620 return v2 625 621 626 def printHostUsbDev(ctx, ud):627 print " %s: %s (vendorId=%d productId=%d serial=%s) %s" % (ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber,asEnumElem(ctx, 'USBDeviceState', ud.state))628 629 def printUsbDev( ctx,ud):630 print " %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber)631 632 def printSf(ctx, sf):633 print " name=%s host=%s %s %s" % (sf.name, colPath(ctx,sf.hostPath), cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))634 635 def ginfo(ctx, console,args):622 def printHostUsbDev(ctx, ud): 623 print " %s: %s (vendorId=%d productId=%d serial=%s) %s" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber, asEnumElem(ctx, 'USBDeviceState', ud.state)) 624 625 def printUsbDev(_ctx, ud): 626 print " %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber) 627 628 def printSf(ctx, sf): 629 print " name=%s host=%s %s %s" % (sf.name, colPath(ctx, sf.hostPath), cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only")) 630 631 def ginfo(ctx, console, _args): 636 632 guest = console.guest 637 633 if guest.additionsRunLevel != ctx['const'].AdditionsRunLevelType_None: 638 print "Additions active, version %s" %(guest.additionsVersion)639 print "Support seamless: %s" %(getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Seamless))640 print "Support graphics: %s" %(getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Graphics))641 print "Balloon size: %d" %(guest.memoryBalloonSize)642 print "Statistic update interval: %d" % (guest.statisticsUpdateInterval)634 print "Additions active, version %s" % (guest.additionsVersion) 635 print "Support seamless: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Seamless)) 636 print "Support graphics: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Graphics)) 637 print "Balloon size: %d" % (guest.memoryBalloonSize) 638 print "Statistic update interval: %d" % (guest.statisticsUpdateInterval) 643 639 else: 644 640 print "No additions" … … 646 642 print "Attached USB:" 647 643 for ud in usbs: 648 printUsbDev(ctx,ud)644 printUsbDev(ctx, ud) 649 645 rusbs = ctx['global'].getArray(console, 'remoteUSBDevices') 650 646 print "Remote USB:" 651 647 for ud in rusbs: 652 printHostUsbDev(ctx, ud)648 printHostUsbDev(ctx, ud) 653 649 print "Transient shared folders:" 654 sfs = 650 sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders') 655 651 for sf in sfs: 656 printSf(ctx, sf)657 658 def cmdExistingVm(ctx, mach,cmd,args):652 printSf(ctx, sf) 653 654 def cmdExistingVm(ctx, mach, cmd, args): 659 655 session = None 660 656 try: 661 vb = ctx['vb']662 session = ctx['mgr'].getSessionObject(vb )657 vbox = ctx['vb'] 658 session = ctx['mgr'].getSessionObject(vbox) 663 659 mach.lockMachine(session, ctx['global'].constants.LockType_Shared) 664 except Exception, e:665 printErr(ctx, "Session to '%s' not open: %s" % (mach.name,str(e)))666 if g_ verbose:660 except Exception, e: 661 printErr(ctx, "Session to '%s' not open: %s" % (mach.name, str(e))) 662 if g_fVerbose: 667 663 traceback.print_exc() 668 664 return 669 665 if session.state != ctx['const'].SessionState_Locked: 670 print "Session to '%s' in wrong state: %s" % (mach.name, session.state)666 print "Session to '%s' in wrong state: %s" % (mach.name, session.state) 671 667 session.unlockMachine() 672 668 return … … 677 673 session.unlockMachine() 678 674 return 679 console =session.console680 ops ={'pause': lambda: console.pause(),681 'resume': lambda: console.resume(),682 'powerdown': lambda: console.powerDown(),683 'powerbutton': lambda: console.powerButton(),684 'stats': lambda: perfStats(ctx, mach),685 'guest': lambda: guestExec(ctx, mach, console, args),686 'ginfo': lambda: ginfo(ctx, console, args),687 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),688 'save': lambda: progressBar(ctx,console.saveState()),689 'screenshot': lambda: takeScreenshot(ctx,console,args),690 'teleport': lambda: teleport(ctx,session,console,args),691 'gueststats': lambda: guestStats(ctx, console, args),692 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),693 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),694 'mountiso': lambda: mountIso(ctx, session.machine, session, args),695 }675 console = session.console 676 ops = {'pause': lambda: console.pause(), 677 'resume': lambda: console.resume(), 678 'powerdown': lambda: console.powerDown(), 679 'powerbutton': lambda: console.powerButton(), 680 'stats': lambda: perfStats(ctx, mach), 681 'guest': lambda: guestExec(ctx, mach, console, args), 682 'ginfo': lambda: ginfo(ctx, console, args), 683 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]), 684 'save': lambda: progressBar(ctx, console.saveState()), 685 'screenshot': lambda: takeScreenshot(ctx, console, args), 686 'teleport': lambda: teleport(ctx, session, console, args), 687 'gueststats': lambda: guestStats(ctx, console, args), 688 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args), 689 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args), 690 'mountiso': lambda: mountIso(ctx, session.machine, session, args), 691 } 696 692 try: 697 693 ops[cmd]() … … 699 695 ctx['interrupt'] = True 700 696 except Exception, e: 701 printErr(ctx, e)702 if g_ verbose:697 printErr(ctx, e) 698 if g_fVerbose: 703 699 traceback.print_exc() 704 700 … … 706 702 707 703 708 def cmdClosedVm(ctx, mach,cmd,args=[],save=True):704 def cmdClosedVm(ctx, mach, cmd, args=[], save=True): 709 705 session = ctx['global'].openMachineSession(mach, True) 710 706 mach = session.machine … … 713 709 except Exception, e: 714 710 save = False 715 printErr(ctx, e)716 if g_ verbose:711 printErr(ctx, e) 712 if g_fVerbose: 717 713 traceback.print_exc() 718 714 if save: … … 720 716 mach.saveSettings() 721 717 except Exception, e: 722 printErr(ctx, e)723 if g_ verbose:718 printErr(ctx, e) 719 if g_fVerbose: 724 720 traceback.print_exc() 725 721 ctx['global'].closeMachineSession(session) 726 722 727 723 728 def cmdAnyVm(ctx, mach,cmd, args=[],save=False):724 def cmdAnyVm(ctx, mach, cmd, args=[], save=False): 729 725 session = ctx['global'].openMachineSession(mach) 730 726 mach = session.machine 731 727 try: 732 728 cmd(ctx, mach, session.console, args) 733 729 except Exception, e: 734 save = False ;735 printErr(ctx, e)736 if g_ verbose:730 save = False 731 printErr(ctx, e) 732 if g_fVerbose: 737 733 traceback.print_exc() 738 734 if save: 739 735 mach.saveSettings() 740 736 ctx['global'].closeMachineSession(session) 741 737 742 def machById(ctx, id):738 def machById(ctx, uuid): 743 739 try: 744 mach = ctx['vb'].getMachine( id)740 mach = ctx['vb'].getMachine(uuid) 745 741 except: 746 mach = ctx['vb'].findMachine( id)742 mach = ctx['vb'].findMachine(uuid) 747 743 return mach 748 744 749 745 class XPathNode: 750 def __init__(self, parent, obj, type):746 def __init__(self, parent, obj, ntype): 751 747 self.parent = parent 752 748 self.obj = obj 753 self. type =type749 self.ntype = ntype 754 750 def lookup(self, subpath): 755 751 children = self.enum() … … 761 757 def enum(self): 762 758 return [] 763 def matches(self, subexp):764 if subexp == self. type:759 def matches(self, subexp): 760 if subexp == self.ntype: 765 761 return True 766 if not subexp.startswith(self. type):762 if not subexp.startswith(self.ntype): 767 763 return False 768 m = re.search(r"@(?P<a>\w+)=(?P<v>[^\'\[\]]+)", subexp)764 match = re.search(r"@(?P<a>\w+)=(?P<v>[^\'\[\]]+)", subexp) 769 765 matches = False 770 766 try: 771 if m is not None:772 dict = m.groupdict()773 attr = dict['a']774 val =dict['v']767 if match is not None: 768 xdict = match.groupdict() 769 attr = xdict['a'] 770 val = xdict['v'] 775 771 matches = (str(getattr(self.obj, attr)) == val) 776 772 except: … … 778 774 return matches 779 775 def apply(self, cmd): 780 exec(cmd, {'obj':self.obj, 'node':self,'ctx':self.getCtx()}, {})776 exec(cmd, {'obj':self.obj, 'node':self, 'ctx':self.getCtx()}, {}) 781 777 def getCtx(self): 782 if hasattr(self, 'ctx'):778 if hasattr(self, 'ctx'): 783 779 return self.ctx 784 780 return self.parent.getCtx() … … 792 788 def enum(self): 793 789 children = [] 794 for n in self.getCtx()['global'].getArray(self.obj, self.attr):795 node = self.heldClass(self, n)796 children.append(node )790 for node in self.getCtx()['global'].getArray(self.obj, self.attr): 791 nodexml = self.heldClass(self, node) 792 children.append(nodexml) 797 793 return children 798 def matches(self, subexp):794 def matches(self, subexp): 799 795 return subexp == self.xpathname 800 796 … … 803 799 XPathNode.__init__(self, parent, obj, 'val '+xpathname) 804 800 self.xpathname = xpathname 805 def matches(self, subexp):801 def matches(self, subexp): 806 802 return subexp == self.xpathname 807 803 … … 813 809 def __init__(self, parent, obj): 814 810 XPathNode.__init__(self, parent, obj, 'vm') 815 #def matches(self, subexp):811 #def matches(self, subexp): 816 812 # return subexp=='vm' 817 813 def enum(self): … … 834 830 def __init__(self, parent, obj): 835 831 XPathNode.__init__(self, parent, obj, 'nic') 836 def matches(self, subexp):837 return subexp =='nic'832 def matches(self, subexp): 833 return subexp == 'nic' 838 834 839 835 class XPathNodeRoot(XPathNode): … … 843 839 def enum(self): 844 840 return [XPathNodeHolderVM(self, self.ctx['vb'])] 845 def matches(self, subexp):841 def matches(self, subexp): 846 842 return True 847 843 848 def eval_xpath(ctx, scope):844 def eval_xpath(ctx, scope): 849 845 pathnames = scope.split("/")[2:] 850 846 nodes = [XPathNodeRoot(ctx)] 851 for p in pathnames:847 for path in pathnames: 852 848 seen = [] 853 849 while len(nodes) > 0: 854 n = nodes.pop()855 seen.append(n )850 node = nodes.pop() 851 seen.append(node) 856 852 for s in seen: 857 matches = s.lookup(p )858 for m in matches:859 nodes.append(m )853 matches = s.lookup(path) 854 for match in matches: 855 nodes.append(match) 860 856 if len(nodes) == 0: 861 857 break 862 858 return nodes 863 859 864 def argsToMach(ctx, args):860 def argsToMach(ctx, args): 865 861 if len(args) < 2: 866 print "usage: %s [vmname|uuid]" % (args[0])862 print "usage: %s [vmname|uuid]" % (args[0]) 867 863 return None 868 id = args[1]869 m = machById(ctx,id)870 if m == None:871 print "Machine '%s' is unknown, use list command to find available machines" % (id)872 return m 873 874 def helpSingleCmd(cmd, h,sp):864 uuid = args[1] 865 mach = machById(ctx, uuid) 866 if mach == None: 867 print "Machine '%s' is unknown, use list command to find available machines" % (uuid) 868 return mach 869 870 def helpSingleCmd(cmd, h, sp): 875 871 if sp != 0: 876 872 spec = " [ext from "+sp+"]" 877 873 else: 878 874 spec = "" 879 print " %s: %s%s" % (colored(cmd,'blue'),h,spec)880 881 def helpCmd( ctx, args):875 print " %s: %s%s" % (colored(cmd, 'blue'), h, spec) 876 877 def helpCmd(_ctx, args): 882 878 if len(args) == 1: 883 879 print "Help page:" … … 890 886 c = commands.get(cmd) 891 887 if c == None: 892 print "Command '%s' not known" % (cmd)888 print "Command '%s' not known" % (cmd) 893 889 else: 894 890 helpSingleCmd(cmd, c[0], c[2]) 895 891 return 0 896 892 897 def asEnumElem(ctx, enum,elem):898 all= ctx['const'].all_values(enum)899 for e in all.keys():900 if str(elem) == str( all[e]):893 def asEnumElem(ctx, enum, elem): 894 enumVals = ctx['const'].all_values(enum) 895 for e in enumVals.keys(): 896 if str(elem) == str(enumVals[e]): 901 897 return colored(e, 'green') 902 898 return colored("<unknown>", 'green') 903 899 904 def enumFromString(ctx, enum,str):905 all= ctx['const'].all_values(enum)906 return all.get(str, None)907 908 def listCmd(ctx, args):909 for m in getMachines(ctx, True):900 def enumFromString(ctx, enum, strg): 901 enumVals = ctx['const'].all_values(enum) 902 return enumVals.get(strg, None) 903 904 def listCmd(ctx, _args): 905 for mach in getMachines(ctx, True): 910 906 try: 911 if m .teleporterEnabled:907 if mach.teleporterEnabled: 912 908 tele = "[T] " 913 909 else: 914 910 tele = " " 915 print "%sMachine '%s' [%s], machineState=%s, sessionState=%s" % (tele,colVm(ctx,m.name),m.id,asEnumElem(ctx, "MachineState", m.state), asEnumElem(ctx,"SessionState", m.sessionState))911 print "%sMachine '%s' [%s], machineState=%s, sessionState=%s" % (tele, colVm(ctx, mach.name), mach.id, asEnumElem(ctx, "MachineState", mach.state), asEnumElem(ctx, "SessionState", mach.sessionState)) 916 912 except Exception, e: 917 printErr(ctx, e)918 if g_ verbose:913 printErr(ctx, e) 914 if g_fVerbose: 919 915 traceback.print_exc() 920 916 return 0 921 917 922 def infoCmd(ctx, args):918 def infoCmd(ctx, args): 923 919 if (len(args) < 2): 924 920 print "usage: info [vmname|uuid]" 925 921 return 0 926 mach = argsToMach(ctx, args)927 if mach == None: 928 return 0 929 os = ctx['vb'].getGuestOSType(mach.OSTypeId)922 mach = argsToMach(ctx, args) 923 if mach == None: 924 return 0 925 vmos = ctx['vb'].getGuestOSType(mach.OSTypeId) 930 926 print " One can use setvar <mach> <var> <value> to change variable, using name in []." 931 print " Name [name]: %s" % (colVm(ctx,mach.name))932 print " Description [description]: %s" % (mach.description)933 print " ID [n/a]: %s" % (mach.id)934 print " OS Type [via OSTypeId]: %s" % (os.description)935 print " Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)927 print " Name [name]: %s" % (colVm(ctx, mach.name)) 928 print " Description [description]: %s" % (mach.description) 929 print " ID [n/a]: %s" % (mach.id) 930 print " OS Type [via OSTypeId]: %s" % (vmos.description) 931 print " Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx, "FirmwareType", mach.firmwareType), mach.firmwareType) 936 932 print 937 print " CPUs [CPUCount]: %d" % (mach.CPUCount)938 print " RAM [memorySize]: %dM" % (mach.memorySize)939 print " VRAM [VRAMSize]: %dM" % (mach.VRAMSize)940 print " Monitors [monitorCount]: %d" % (mach.monitorCount)941 print " Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx,"ChipsetType", mach.chipsetType), mach.chipsetType)933 print " CPUs [CPUCount]: %d" % (mach.CPUCount) 934 print " RAM [memorySize]: %dM" % (mach.memorySize) 935 print " VRAM [VRAMSize]: %dM" % (mach.VRAMSize) 936 print " Monitors [monitorCount]: %d" % (mach.monitorCount) 937 print " Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx, "ChipsetType", mach.chipsetType), mach.chipsetType) 942 938 print 943 print " Clipboard mode [clipboardMode]: %s (%s)" % (asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)944 print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx, "SessionState", mach.sessionState), mach.sessionState)939 print " Clipboard mode [clipboardMode]: %s (%s)" % (asEnumElem(ctx, "ClipboardMode", mach.clipboardMode), mach.clipboardMode) 940 print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx, "SessionState", mach.sessionState), mach.sessionState) 945 941 print 946 942 if mach.teleporterEnabled: 947 print " Teleport target on port %d (%s)" % (mach.teleporterPort, mach.teleporterPassword)943 print " Teleport target on port %d (%s)" % (mach.teleporterPort, mach.teleporterPassword) 948 944 print 949 945 bios = mach.BIOSSettings 950 print " ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(bios.ACPIEnabled))951 print " APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(bios.IOAPICEnabled))946 print " ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(bios.ACPIEnabled)) 947 print " APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(bios.IOAPICEnabled)) 952 948 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled) 953 print " Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled)949 print " Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled) 954 950 hwVirtVPID = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID) 955 print " VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID)951 print " VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID) 956 952 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging) 957 print " Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging)953 print " Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging) 958 954 959 955 print " Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled) 960 956 print " Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled) 961 957 962 print " Use universal time [RTCUseUTC]: %s" % (asState(mach.RTCUseUTC))963 print " HPET [HPETEnabled]: %s" % (asState(mach.HPETEnabled))958 print " Use universal time [RTCUseUTC]: %s" % (asState(mach.RTCUseUTC)) 959 print " HPET [HPETEnabled]: %s" % (asState(mach.HPETEnabled)) 964 960 if mach.audioAdapter.enabled: 965 print " Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))961 print " Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx, "AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx, "AudioDriverType", mach.audioAdapter.audioDriver)) 966 962 if mach.USBController.enabled: 967 print " USB [via USBController]: high speed %s" % (asState(mach.USBController.enabledEHCI))968 print " CPU hotplugging [CPUHotPlugEnabled]: %s" % (asState(mach.CPUHotPlugEnabled))969 970 print " Keyboard [keyboardHIDType]: %s (%s)" % (asEnumElem(ctx,"KeyboardHIDType", mach.keyboardHIDType), mach.keyboardHIDType)971 print " Pointing device [pointingHIDType]: %s (%s)" % (asEnumElem(ctx,"PointingHIDType", mach.pointingHIDType), mach.pointingHIDType)963 print " USB [via USBController]: high speed %s" % (asState(mach.USBController.enabledEHCI)) 964 print " CPU hotplugging [CPUHotPlugEnabled]: %s" % (asState(mach.CPUHotPlugEnabled)) 965 966 print " Keyboard [keyboardHIDType]: %s (%s)" % (asEnumElem(ctx, "KeyboardHIDType", mach.keyboardHIDType), mach.keyboardHIDType) 967 print " Pointing device [pointingHIDType]: %s (%s)" % (asEnumElem(ctx, "PointingHIDType", mach.pointingHIDType), mach.pointingHIDType) 972 968 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000)) 973 969 # OSE has no VRDE 974 970 try: 975 print " VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled))971 print " VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled)) 976 972 except: 977 973 pass 978 974 print 979 print colCat(ctx, " I/O subsystem info:")980 print " Cache enabled [IOCacheEnabled]: %s" % (asState(mach.IOCacheEnabled))981 print " Cache size [IOCacheSize]: %dM" % (mach.IOCacheSize)975 print colCat(ctx, " I/O subsystem info:") 976 print " Cache enabled [IOCacheEnabled]: %s" % (asState(mach.IOCacheEnabled)) 977 print " Cache size [IOCacheSize]: %dM" % (mach.IOCacheSize) 982 978 983 979 controllers = ctx['global'].getArray(mach, 'storageControllers') 984 980 if controllers: 985 981 print 986 print colCat(ctx, " Controllers:")982 print colCat(ctx, " Controllers:") 987 983 for controller in controllers: 988 print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx, "StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))984 print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx, "StorageBus", controller.bus), asEnumElem(ctx, "StorageControllerType", controller.controllerType)) 989 985 990 986 attaches = ctx['global'].getArray(mach, 'mediumAttachments') 991 987 if attaches: 992 988 print 993 print colCat(ctx, " Media:")989 print colCat(ctx, " Media:") 994 990 for a in attaches: 995 print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx, "DeviceType", a.type), a.type)996 m = a.medium991 print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx, "DeviceType", a.type), a.type) 992 medium = a.medium 997 993 if a.type == ctx['global'].constants.DeviceType_HardDisk: 998 994 print " HDD:" 999 print " Id: %s" % (m.id)1000 print " Location: %s" % (colPath(ctx,m.location))1001 print " Name: %s" %(m.name)1002 print " Format: %s" %(m.format)995 print " Id: %s" % (medium.id) 996 print " Location: %s" % (colPath(ctx, medium.location)) 997 print " Name: %s" % (medium.name) 998 print " Format: %s" % (medium.format) 1003 999 1004 1000 if a.type == ctx['global'].constants.DeviceType_DVD: 1005 1001 print " DVD:" 1006 if m :1007 print " Id: %s" % (m.id)1008 print " Name: %s" % (m.name)1009 if m .hostDrive:1010 print " Host DVD %s" % (colPath(ctx,m.location))1002 if medium: 1003 print " Id: %s" % (medium.id) 1004 print " Name: %s" % (medium.name) 1005 if medium.hostDrive: 1006 print " Host DVD %s" % (colPath(ctx, medium.location)) 1011 1007 if a.passthrough: 1012 1008 print " [passthrough mode]" 1013 1009 else: 1014 print " Virtual image at %s" % (colPath(ctx,m.location))1015 print " Size: %s" % (m.size)1010 print " Virtual image at %s" % (colPath(ctx, medium.location)) 1011 print " Size: %s" % (medium.size) 1016 1012 1017 1013 if a.type == ctx['global'].constants.DeviceType_Floppy: 1018 1014 print " Floppy:" 1019 if m :1020 print " Id: %s" % (m.id)1021 print " Name: %s" % (m.name)1022 if m .hostDrive:1023 print " Host floppy %s" % (colPath(ctx,m.location))1015 if medium: 1016 print " Id: %s" % (medium.id) 1017 print " Name: %s" % (medium.name) 1018 if medium.hostDrive: 1019 print " Host floppy %s" % (colPath(ctx, medium.location)) 1024 1020 else: 1025 print " Virtual image at %s" % (colPath(ctx,m.location))1026 print " Size: %s" % (m.size)1021 print " Virtual image at %s" % (colPath(ctx, medium.location)) 1022 print " Size: %s" % (medium.size) 1027 1023 1028 1024 print 1029 print colCat(ctx, " Shared folders:")1025 print colCat(ctx, " Shared folders:") 1030 1026 for sf in ctx['global'].getArray(mach, 'sharedFolders'): 1031 printSf(ctx, sf)1027 printSf(ctx, sf) 1032 1028 1033 1029 return 0 … … 1037 1033 print "usage: start name <frontend>" 1038 1034 return 0 1039 mach = argsToMach(ctx, args)1035 mach = argsToMach(ctx, args) 1040 1036 if mach == None: 1041 1037 return 0 1042 1038 if len(args) > 2: 1043 type = args[2]1044 else: 1045 type = "gui"1046 startVm(ctx, mach, type)1039 vmtype = args[2] 1040 else: 1041 vmtype = "gui" 1042 startVm(ctx, mach, vmtype) 1047 1043 return 0 1048 1044 … … 1054 1050 oskind = args[2] 1055 1051 try: 1056 1057 except Exception , e:1058 print 'Unknown OS type:', oskind1052 ctx['vb'].getGuestOSType(oskind) 1053 except Exception: 1054 print 'Unknown OS type:', oskind 1059 1055 return 0 1060 1056 createVm(ctx, name, oskind) 1061 1057 return 0 1062 1058 1063 def ginfoCmd(ctx, args):1059 def ginfoCmd(ctx, args): 1064 1060 if (len(args) < 2): 1065 1061 print "usage: ginfo [vmname|uuid]" 1066 1062 return 0 1067 mach = argsToMach(ctx, args)1063 mach = argsToMach(ctx, args) 1068 1064 if mach == None: 1069 1065 return 0 … … 1071 1067 return 0 1072 1068 1073 def execInGuest(ctx, console,args,env,user,passwd,tmo,inputPipe=None,outputPipe=None):1069 def execInGuest(ctx, console, args, env, user, passwd, tmo, inputPipe=None, outputPipe=None): 1074 1070 if len(args) < 1: 1075 1071 print "exec in guest needs at least program name" … … 1079 1075 # shall contain program name as argv[0] 1080 1076 gargs = args 1081 print "executing %s with args %s as %s" % (args[0], gargs, user)1077 print "executing %s with args %s as %s" % (args[0], gargs, user) 1082 1078 flags = 0 1083 1079 if inputPipe is not None: … … 1085 1081 print args[0] 1086 1082 process = guestSession.processCreate(args[0], gargs, env, [], tmo) 1087 print "executed with pid %d" % (process.PID)1083 print "executed with pid %d" % (process.PID) 1088 1084 if pid != 0: 1089 1085 try: … … 1113 1109 if data and len(data) > 0: 1114 1110 if outputPipe is not None: 1115 outputPipe(ctx, data)1111 outputPipe(ctx, data) 1116 1112 else: 1117 1113 sys.stdout.write(data) … … 1125 1121 if progress.cancelable: 1126 1122 progress.cancel() 1127 ( reason, code,flags) = guest.getProcessStatus(pid)1128 print "Exit code: %d" % (code)1123 (_reason, code, _flags) = guest.getProcessStatus(pid) 1124 print "Exit code: %d" % (code) 1129 1125 return 0 1130 1126 else: 1131 1127 reportError(ctx, progress) 1132 1128 1133 def copyToGuest(ctx, console,args,user,passwd):1129 def copyToGuest(ctx, console, args, user, passwd): 1134 1130 src = args[0] 1135 1131 dst = args[1] 1136 1132 flags = 0 1137 print "Copying host %s to guest %s" % (src,dst)1133 print "Copying host %s to guest %s" % (src, dst) 1138 1134 progress = console.guest.copyToGuest(src, dst, user, passwd, flags) 1139 1135 progressBar(ctx, progress) … … 1152 1148 1153 1149 1154 def getCred( ctx):1150 def getCred(_ctx): 1155 1151 import getpass 1156 1152 user = getpass.getuser() 1157 user_inp = nh_raw_input("User (%s): " % (user))1153 user_inp = nh_raw_input("User (%s): " % (user)) 1158 1154 if len (user_inp) > 0: 1159 1155 user = user_inp 1160 1156 passwd = getpass.getpass() 1161 1157 1162 return (user, passwd)1163 1164 def gexecCmd(ctx, args):1158 return (user, passwd) 1159 1160 def gexecCmd(ctx, args): 1165 1161 if (len(args) < 2): 1166 1162 print "usage: gexec [vmname|uuid] command args" 1167 1163 return 0 1168 mach = argsToMach(ctx, args)1164 mach = argsToMach(ctx, args) 1169 1165 if mach == None: 1170 1166 return 0 1171 1167 gargs = args[2:] 1172 1168 env = [] # ["DISPLAY=:0"] 1173 (user, passwd) = getCred(ctx)1174 gargs.insert(0, lambda ctx, mach,console,args: execInGuest(ctx,console,args,env,user,passwd,10000))1169 (user, passwd) = getCred(ctx) 1170 gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000)) 1175 1171 cmdExistingVm(ctx, mach, 'guestlambda', gargs) 1176 1172 return 0 1177 1173 1178 def gcopyCmd(ctx, args):1174 def gcopyCmd(ctx, args): 1179 1175 if (len(args) < 2): 1180 1176 print "usage: gcopy [vmname|uuid] host_path guest_path" 1181 1177 return 0 1182 mach = argsToMach(ctx, args)1178 mach = argsToMach(ctx, args) 1183 1179 if mach == None: 1184 1180 return 0 1185 1181 gargs = args[2:] 1186 (user, passwd) = getCred(ctx)1187 gargs.insert(0, lambda ctx, mach,console,args: copyToGuest(ctx,console,args,user,passwd))1182 (user, passwd) = getCred(ctx) 1183 gargs.insert(0, lambda ctx, mach, console, args: copyToGuest(ctx, console, args, user, passwd)) 1188 1184 cmdExistingVm(ctx, mach, 'guestlambda', gargs) 1189 1185 return 0 1190 1186 1191 def readCmdPipe(ctx, hcmd):1187 def readCmdPipe(ctx, _hcmd): 1192 1188 try: 1193 1189 return ctx['process'].communicate()[0] … … 1195 1191 return None 1196 1192 1197 def gpipeCmd(ctx, args):1193 def gpipeCmd(ctx, args): 1198 1194 if (len(args) < 4): 1199 1195 print "usage: gpipe [vmname|uuid] hostProgram guestProgram, such as gpipe linux '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'" 1200 1196 return 0 1201 mach = argsToMach(ctx, args)1197 mach = argsToMach(ctx, args) 1202 1198 if mach == None: 1203 1199 return 0 1204 1200 hcmd = args[2] 1205 1201 gcmd = args[3] 1206 (user, passwd) = getCred(ctx)1202 (user, passwd) = getCred(ctx) 1207 1203 import subprocess 1208 1204 ctx['process'] = subprocess.Popen(split_no_quotes(hcmd), stdout=subprocess.PIPE) 1209 1205 gargs = split_no_quotes(gcmd) 1210 1206 env = [] 1211 gargs.insert(0, lambda ctx, mach,console,args: execInGuest(ctx,console,args,env,user,passwd, 10000,lambda ctx:readCmdPipe(ctx, hcmd)))1207 gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000, lambda ctx:readCmdPipe(ctx, hcmd))) 1212 1208 cmdExistingVm(ctx, mach, 'guestlambda', gargs) 1213 1209 try: … … 1220 1216 1221 1217 def removeVmCmd(ctx, args): 1222 mach = argsToMach(ctx, args)1218 mach = argsToMach(ctx, args) 1223 1219 if mach == None: 1224 1220 return 0 … … 1227 1223 1228 1224 def pauseCmd(ctx, args): 1229 mach = argsToMach(ctx, args)1225 mach = argsToMach(ctx, args) 1230 1226 if mach == None: 1231 1227 return 0 … … 1234 1230 1235 1231 def powerdownCmd(ctx, args): 1236 mach = argsToMach(ctx, args)1232 mach = argsToMach(ctx, args) 1237 1233 if mach == None: 1238 1234 return 0 … … 1241 1237 1242 1238 def powerbuttonCmd(ctx, args): 1243 mach = argsToMach(ctx, args)1239 mach = argsToMach(ctx, args) 1244 1240 if mach == None: 1245 1241 return 0 … … 1248 1244 1249 1245 def resumeCmd(ctx, args): 1250 mach = argsToMach(ctx, args)1246 mach = argsToMach(ctx, args) 1251 1247 if mach == None: 1252 1248 return 0 … … 1255 1251 1256 1252 def saveCmd(ctx, args): 1257 mach = argsToMach(ctx, args)1253 mach = argsToMach(ctx, args) 1258 1254 if mach == None: 1259 1255 return 0 … … 1262 1258 1263 1259 def statsCmd(ctx, args): 1264 mach = argsToMach(ctx, args)1260 mach = argsToMach(ctx, args) 1265 1261 if mach == None: 1266 1262 return 0 … … 1272 1268 print "usage: guest name commands" 1273 1269 return 0 1274 mach = argsToMach(ctx, args)1270 mach = argsToMach(ctx, args) 1275 1271 if mach == None: 1276 1272 return 0 … … 1285 1281 print "usage: screenshot vm <file> <width> <height> <monitor>" 1286 1282 return 0 1287 mach = argsToMach(ctx, args)1283 mach = argsToMach(ctx, args) 1288 1284 if mach == None: 1289 1285 return 0 … … 1295 1291 print "usage: teleport name host:port <password>" 1296 1292 return 0 1297 mach = argsToMach(ctx, args)1293 mach = argsToMach(ctx, args) 1298 1294 if mach == None: 1299 1295 return 0 … … 1301 1297 return 0 1302 1298 1303 def portalsettings( ctx,mach,args):1299 def portalsettings(_ctx, mach, args): 1304 1300 enabled = args[0] 1305 1301 mach.teleporterEnabled = enabled … … 1314 1310 print "usage: openportal name port <password>" 1315 1311 return 0 1316 mach = argsToMach(ctx, args)1312 mach = argsToMach(ctx, args) 1317 1313 if mach == None: 1318 1314 return 0 … … 1331 1327 print "usage: closeportal name" 1332 1328 return 0 1333 mach = argsToMach(ctx, args)1329 mach = argsToMach(ctx, args) 1334 1330 if mach == None: 1335 1331 return 0 … … 1342 1338 print "usage: gueststats name <check interval>" 1343 1339 return 0 1344 mach = argsToMach(ctx, args)1340 mach = argsToMach(ctx, args) 1345 1341 if mach == None: 1346 1342 return 0 … … 1348 1344 return 0 1349 1345 1350 def plugcpu( ctx,mach,args):1346 def plugcpu(_ctx, mach, args): 1351 1347 plug = args[0] 1352 1348 cpu = args[1] 1353 1349 if plug: 1354 print "Adding CPU %d..." % (cpu)1350 print "Adding CPU %d..." % (cpu) 1355 1351 mach.hotPlugCPU(cpu) 1356 1352 else: 1357 print "Removing CPU %d..." % (cpu)1353 print "Removing CPU %d..." % (cpu) 1358 1354 mach.hotUnplugCPU(cpu) 1359 1355 … … 1362 1358 print "usage: plugcpu name cpuid" 1363 1359 return 0 1364 mach = argsToMach(ctx, args)1360 mach = argsToMach(ctx, args) 1365 1361 if mach == None: 1366 1362 return 0 … … 1376 1372 print "usage: unplugcpu name cpuid" 1377 1373 return 0 1378 mach = argsToMach(ctx, args)1374 mach = argsToMach(ctx, args) 1379 1375 if mach == None: 1380 1376 return 0 … … 1386 1382 return 0 1387 1383 1388 def setvar( ctx,mach,args):1384 def setvar(_ctx, _mach, args): 1389 1385 expr = 'mach.'+args[0]+' = '+args[1] 1390 print "Executing", expr1386 print "Executing", expr 1391 1387 exec expr 1392 1388 … … 1395 1391 print "usage: setvar [vmname|uuid] expr value" 1396 1392 return 0 1397 mach = argsToMach(ctx, args)1393 mach = argsToMach(ctx, args) 1398 1394 if mach == None: 1399 1395 return 0 … … 1401 1397 return 0 1402 1398 1403 def setvmextra( ctx,mach,args):1399 def setvmextra(_ctx, mach, args): 1404 1400 key = args[0] 1405 1401 value = args[1] 1406 print "%s: setting %s to %s" % (mach.name, key, value)1402 print "%s: setting %s to %s" % (mach.name, key, value) 1407 1403 mach.setExtraData(key, value) 1408 1404 … … 1420 1416 return 0 1421 1417 1422 mach = argsToMach(ctx, args)1418 mach = argsToMach(ctx, args) 1423 1419 if mach == None: 1424 1420 return 0 … … 1427 1423 1428 1424 def printExtraKey(obj, key, value): 1429 print "%s: '%s' = '%s'" % (obj, key, value)1425 print "%s: '%s' = '%s'" % (obj, key, value) 1430 1426 1431 1427 def getExtraDataCmd(ctx, args): … … 1441 1437 obj = ctx['vb'] 1442 1438 else: 1443 obj = argsToMach(ctx, args)1439 obj = argsToMach(ctx, args) 1444 1440 if obj == None: 1445 1441 return 0 … … 1454 1450 return 0 1455 1451 1456 def quitCmd( ctx,args):1452 def quitCmd(_ctx, _args): 1457 1453 return 1 1458 1454 … … 1462 1458 return 0 1463 1459 1464 for (k ,v) in aliases.items():1465 print "'%s' is an alias for '%s'" % (k,v)1460 for (key, value) in aliases.items(): 1461 print "'%s' is an alias for '%s'" % (key, value) 1466 1462 return 0 1467 1463 1468 1464 def verboseCmd(ctx, args): 1469 global g_ verbose1465 global g_fVerbose 1470 1466 if (len(args) > 1): 1471 g_ verbose= (args[1]=='on')1472 else: 1473 g_ verbose = not g_verbose1467 g_fVerbose = (args[1]=='on') 1468 else: 1469 g_fVerbose = not g_fVerbose 1474 1470 return 0 1475 1471 1476 1472 def colorsCmd(ctx, args): 1477 global g_ hascolors1473 global g_fHasColors 1478 1474 if (len(args) > 1): 1479 g_ hascolors = (args[1]=='on')1480 else: 1481 g_ hascolors = not g_hascolors1475 g_fHasColors = (args[1] == 'on') 1476 else: 1477 g_fHasColors = not g_fHasColors 1482 1478 return 0 1483 1479 1484 1480 def hostCmd(ctx, args): 1485 vb = ctx['vb'] 1486 print "VirtualBox version %s" %(colored(vb.version, 'blue')) 1487 props = vb.systemProperties 1488 print "Machines: %s" %(colPath(ctx,props.defaultMachineFolder)) 1489 1490 #print "Global shared folders:" 1491 #for ud in ctx['global'].getArray(vb, 'sharedFolders'): 1492 # printSf(ctx,sf) 1493 host = vb.host 1494 cnt = host.processorCount 1495 print colCat(ctx,"Processors:") 1496 print " available/online: %d/%d " %(cnt,host.processorOnlineCount) 1497 for i in range(0,cnt): 1498 print " processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i)) 1499 1500 print colCat(ctx, "RAM:") 1501 print " %dM (free %dM)" %(host.memorySize, host.memoryAvailable) 1502 print colCat(ctx,"OS:"); 1503 print " %s (%s)" %(host.operatingSystem, host.OSVersion) 1504 if host.acceleration3DAvailable: 1505 print colCat(ctx,"3D acceleration available") 1506 else: 1507 print colCat(ctx,"3D acceleration NOT available") 1508 1509 print colCat(ctx,"Network interfaces:") 1510 for ni in ctx['global'].getArray(host, 'networkInterfaces'): 1511 print " %s (%s)" %(ni.name, ni.IPAddress) 1512 1513 print colCat(ctx,"DVD drives:") 1514 for dd in ctx['global'].getArray(host, 'DVDDrives'): 1515 print " %s - %s" %(dd.name, dd.description) 1516 1517 print colCat(ctx,"Floppy drives:") 1518 for dd in ctx['global'].getArray(host, 'floppyDrives'): 1519 print " %s - %s" %(dd.name, dd.description) 1520 1521 print colCat(ctx,"USB devices:") 1522 for ud in ctx['global'].getArray(host, 'USBDevices'): 1523 printHostUsbDev(ctx,ud) 1524 1525 if ctx['perf']: 1526 for metric in ctx['perf'].query(["*"], [host]): 1527 print metric['name'], metric['values_as_string'] 1528 1529 return 0 1481 vbox = ctx['vb'] 1482 try: 1483 print "VirtualBox version %s" % (colored(vbox.version, 'blue')) 1484 except Exception, e: 1485 printErr(ctx, e) 1486 if g_fVerbose: 1487 traceback.print_exc() 1488 props = vbox.systemProperties 1489 print "Machines: %s" % (colPath(ctx, props.defaultMachineFolder)) 1490 1491 #print "Global shared folders:" 1492 #for ud in ctx['global'].getArray(vbox, 'sharedFolders'): 1493 # printSf(ctx, sf) 1494 host = vbox.host 1495 cnt = host.processorCount 1496 print colCat(ctx, "Processors:") 1497 print " available/online: %d/%d " % (cnt, host.processorOnlineCount) 1498 for i in range(0, cnt): 1499 print " processor #%d speed: %dMHz %s" % (i, host.getProcessorSpeed(i), host.getProcessorDescription(i)) 1500 1501 print colCat(ctx, "RAM:") 1502 print " %dM (free %dM)" % (host.memorySize, host.memoryAvailable) 1503 print colCat(ctx, "OS:") 1504 print " %s (%s)" % (host.operatingSystem, host.OSVersion) 1505 if host.acceleration3DAvailable: 1506 print colCat(ctx, "3D acceleration available") 1507 else: 1508 print colCat(ctx, "3D acceleration NOT available") 1509 1510 print colCat(ctx, "Network interfaces:") 1511 for ni in ctx['global'].getArray(host, 'networkInterfaces'): 1512 print " %s (%s)" % (ni.name, ni.IPAddress) 1513 1514 print colCat(ctx, "DVD drives:") 1515 for dd in ctx['global'].getArray(host, 'DVDDrives'): 1516 print " %s - %s" % (dd.name, dd.description) 1517 1518 print colCat(ctx, "Floppy drives:") 1519 for dd in ctx['global'].getArray(host, 'floppyDrives'): 1520 print " %s - %s" % (dd.name, dd.description) 1521 1522 print colCat(ctx, "USB devices:") 1523 for ud in ctx['global'].getArray(host, 'USBDevices'): 1524 printHostUsbDev(ctx, ud) 1525 1526 if ctx['perf']: 1527 for metric in ctx['perf'].query(["*"], [host]): 1528 print metric['name'], metric['values_as_string'] 1529 1530 return 0 1530 1531 1531 1532 def monitorGuestCmd(ctx, args): … … 1533 1534 print "usage: monitorGuest name (duration)" 1534 1535 return 0 1535 mach = argsToMach(ctx, args)1536 mach = argsToMach(ctx, args) 1536 1537 if mach == None: 1537 1538 return 0 … … 1540 1541 dur = float(args[2]) 1541 1542 active = False 1542 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: monitorSource(ctx, console.eventSource, active, dur)])1543 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: monitorSource(ctx, console.eventSource, active, dur)]) 1543 1544 return 0 1544 1545 … … 1547 1548 print "usage: monitorGuestKbd name (duration)" 1548 1549 return 0 1549 mach = argsToMach(ctx, args)1550 mach = argsToMach(ctx, args) 1550 1551 if mach == None: 1551 1552 return 0 … … 1554 1555 dur = float(args[2]) 1555 1556 active = False 1556 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: monitorSource(ctx, console.keyboard.eventSource, active, dur)])1557 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: monitorSource(ctx, console.keyboard.eventSource, active, dur)]) 1557 1558 return 0 1558 1559 … … 1561 1562 print "usage: monitorGuestMouse name (duration)" 1562 1563 return 0 1563 mach = argsToMach(ctx, args)1564 mach = argsToMach(ctx, args) 1564 1565 if mach == None: 1565 1566 return 0 … … 1568 1569 dur = float(args[2]) 1569 1570 active = False 1570 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: monitorSource(ctx, console.mouse.eventSource, active, dur)])1571 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: monitorSource(ctx, console.mouse.eventSource, active, dur)]) 1571 1572 return 0 1572 1573 … … 1583 1584 return 0 1584 1585 1585 def getAdapterType(ctx, type):1586 if ( type == ctx['global'].constants.NetworkAdapterType_Am79C970A or1587 type == ctx['global'].constants.NetworkAdapterType_Am79C973):1586 def getAdapterType(ctx, natype): 1587 if (natype == ctx['global'].constants.NetworkAdapterType_Am79C970A or 1588 natype == ctx['global'].constants.NetworkAdapterType_Am79C973): 1588 1589 return "pcnet" 1589 elif ( type == ctx['global'].constants.NetworkAdapterType_I82540EM or1590 type == ctx['global'].constants.NetworkAdapterType_I82545EM or1591 type == ctx['global'].constants.NetworkAdapterType_I82543GC):1590 elif (natype == ctx['global'].constants.NetworkAdapterType_I82540EM or 1591 natype == ctx['global'].constants.NetworkAdapterType_I82545EM or 1592 natype == ctx['global'].constants.NetworkAdapterType_I82543GC): 1592 1593 return "e1000" 1593 elif ( type == ctx['global'].constants.NetworkAdapterType_Virtio):1594 elif (natype == ctx['global'].constants.NetworkAdapterType_Virtio): 1594 1595 return "virtio" 1595 elif ( type == ctx['global'].constants.NetworkAdapterType_Null):1596 elif (natype == ctx['global'].constants.NetworkAdapterType_Null): 1596 1597 return None 1597 1598 else: 1598 raise Exception("Unknown adapter type: "+ type)1599 raise Exception("Unknown adapter type: "+natype) 1599 1600 1600 1601 … … 1603 1604 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>" 1604 1605 return 0 1605 mach = argsToMach(ctx, args)1606 mach = argsToMach(ctx, args) 1606 1607 if mach == None: 1607 1608 return 0 … … 1634 1635 print "usage: showLog vm <num>" 1635 1636 return 0 1636 mach = argsToMach(ctx, args)1637 mach = argsToMach(ctx, args) 1637 1638 if mach == None: 1638 1639 return 0 … … 1640 1641 log = 0 1641 1642 if (len(args) > 2): 1642 log= args[2]1643 log = args[2] 1643 1644 1644 1645 uOffset = 0 … … 1657 1658 print "usage: findLog vm pattern <num>" 1658 1659 return 0 1659 mach = argsToMach(ctx, args)1660 mach = argsToMach(ctx, args) 1660 1661 if mach == None: 1661 1662 return 0 … … 1663 1664 log = 0 1664 1665 if (len(args) > 3): 1665 log= args[3]1666 log = args[3] 1666 1667 1667 1668 pattern = args[2] … … 1674 1675 d = str(data).split("\n") 1675 1676 for s in d: 1676 m = re.findall(pattern, s)1677 if len(m ) > 0:1678 for mt in m :1679 s = s.replace(mt, colored(mt, 'red'))1677 match = re.findall(pattern, s) 1678 if len(match) > 0: 1679 for mt in match: 1680 s = s.replace(mt, colored(mt, 'red')) 1680 1681 print s 1681 1682 uOffset += len(data) … … 1688 1689 print "usage: findAssert vm <num>" 1689 1690 return 0 1690 mach = argsToMach(ctx, args)1691 mach = argsToMach(ctx, args) 1691 1692 if mach == None: 1692 1693 return 0 … … 1694 1695 log = 0 1695 1696 if (len(args) > 2): 1696 log= args[2]1697 log = args[2] 1697 1698 1698 1699 uOffset = 0 … … 1714 1715 context = context - 1 1715 1716 continue 1716 m = ere.findall(s)1717 if len(m ) > 0:1717 match = ere.findall(s) 1718 if len(match) > 0: 1718 1719 active = True 1719 1720 context = 50 … … 1724 1725 1725 1726 def evalCmd(ctx, args): 1726 expr = ' '.join(args[1:])1727 try:1727 expr = ' '.join(args[1:]) 1728 try: 1728 1729 exec expr 1729 except Exception, e:1730 printErr(ctx, e)1731 if g_ verbose:1730 except Exception, e: 1731 printErr(ctx, e) 1732 if g_fVerbose: 1732 1733 traceback.print_exc() 1733 return 01734 return 0 1734 1735 1735 1736 def reloadExtCmd(ctx, args): 1736 # maybe will want more args smartness1737 checkUserExtensions(ctx, commands, getHomeFolder(ctx))1738 autoCompletion(commands, ctx)1739 return 01737 # maybe will want more args smartness 1738 checkUserExtensions(ctx, commands, getHomeFolder(ctx)) 1739 autoCompletion(commands, ctx) 1740 return 0 1740 1741 1741 1742 def runScriptCmd(ctx, args): … … 1745 1746 try: 1746 1747 lf = open(args[1], 'r') 1747 except IOError, e:1748 print "cannot open:", args[1], ":",e1748 except IOError, e: 1749 print "cannot open:", args[1], ":", e 1749 1750 return 0 1750 1751 … … 1760 1761 break 1761 1762 1762 except Exception, e:1763 printErr(ctx, e)1764 if g_ verbose:1763 except Exception, e: 1764 printErr(ctx, e) 1765 if g_fVerbose: 1765 1766 traceback.print_exc() 1766 1767 lf.close() … … 1821 1822 vbox = ctx['global'].platform.connect(url, user, passwd) 1822 1823 ctx['vb'] = vbox 1823 print "Running VirtualBox version %s" %(vbox.version) 1824 try: 1825 print "Running VirtualBox version %s" % (vbox.version) 1826 except Exception, e: 1827 printErr(ctx, e) 1828 if g_fVerbose: 1829 traceback.print_exc() 1824 1830 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb']) 1825 1831 return 0 … … 1853 1859 pass 1854 1860 1855 [url, user,passwd] = ctx['wsinfo']1861 [url, user, passwd] = ctx['wsinfo'] 1856 1862 ctx['vb'] = ctx['global'].platform.connect(url, user, passwd) 1857 print "Running VirtualBox version %s" %(ctx['vb'].version) 1863 try: 1864 print "Running VirtualBox version %s" % (ctx['vb'].version) 1865 except Exception, e: 1866 printErr(ctx, e) 1867 if g_fVerbose: 1868 traceback.print_exc() 1858 1869 return 0 1859 1870 1860 1871 def exportVMCmd(ctx, args): 1861 import sys1862 1863 1872 if len(args) < 3: 1864 1873 print "usage: exportVm <machine> <path> <format> <license>" 1865 1874 return 0 1866 mach = argsToMach(ctx, args)1875 mach = argsToMach(ctx, args) 1867 1876 if mach is None: 1868 1877 return 0 1869 1878 path = args[2] 1870 1879 if (len(args) > 3): 1871 f ormat = args[3]1872 else: 1873 f ormat = "ovf-1.0"1880 fmt = args[3] 1881 else: 1882 fmt = "ovf-1.0" 1874 1883 if (len(args) > 4): 1875 lic ense= args[4]1876 else: 1877 lic ense= "GPL"1884 lic = args[4] 1885 else: 1886 lic = "GPL" 1878 1887 1879 1888 app = ctx['vb'].createAppliance() 1880 1889 desc = mach.export(app) 1881 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, lic ense, "")1882 p = app.write(format, path)1883 if (progressBar(ctx, p ) and int(p.resultCode) == 0):1884 print "Exported to %s in format %s" % (path, format)1885 else: 1886 reportError(ctx, p)1890 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, lic, "") 1891 progress = app.write(fmt, path) 1892 if (progressBar(ctx, progress) and int(progress.resultCode) == 0): 1893 print "Exported to %s in format %s" % (path, fmt) 1894 else: 1895 reportError(ctx, progress) 1887 1896 return 0 1888 1897 … … 1938 1947 '\n': 0x1c, 1939 1948 '`': 0x29 1940 } ;1949 } 1941 1950 1942 1951 extScancodes = { … … 1978 1987 'DOWN': [0xe0, 0x50], 1979 1988 'RIGHT': [0xe0, 0x4d], 1980 } ;1989 } 1981 1990 1982 1991 def keyDown(ch): … … 1986 1995 extCode = extScancodes.get(ch, []) 1987 1996 if len(extCode) == 0: 1988 print "bad ext", ch1997 print "bad ext", ch 1989 1998 return extCode 1990 1999 … … 1996 2005 1997 2006 def typeInGuest(console, text, delay): 1998 import time1999 2007 pressed = [] 2000 2008 group = False … … 2012 2020 # end group, release all keys 2013 2021 for c in pressed: 2014 2022 kbd.putScancodes(keyUp(c)) 2015 2023 pressed = [] 2016 2024 group = False … … 2058 2066 2059 2067 def typeGuestCmd(ctx, args): 2060 import sys2061 2062 2068 if len(args) < 3: 2063 2069 print "usage: typeGuest <machine> <text> <charDelay>" 2064 2070 return 0 2065 mach = argsToMach(ctx,args)2071 mach = argsToMach(ctx, args) 2066 2072 if mach is None: 2067 2073 return 0 … … 2074 2080 delay = 0.1 2075 2081 2076 gargs = [lambda ctx, mach,console,args: typeInGuest(console, text, delay)]2082 gargs = [lambda ctx, mach, console, args: typeInGuest(console, text, delay)] 2077 2083 cmdExistingVm(ctx, mach, 'guestlambda', gargs) 2078 2084 2079 2085 return 0 2080 2086 2081 def optId(verbose, id):2082 if verbose:2083 return ": "+id2084 else:2085 return ""2086 2087 def asSize(val, inBytes):2088 if inBytes:2089 return int(val)/(1024*1024)2090 else:2091 return int(val)2092 2093 def listMediaCmd(ctx, args):2094 if len(args) > 1:2095 verbose = int(args[1])2096 else:2097 verbose = False2098 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')2099 print colCat(ctx,"Hard disks:")2100 for hdd in hdds:2101 if hdd.state != ctx['global'].constants.MediumState_Created:2102 hdd.refreshState()2103 print " %s (%s)%s %s [logical %s]" %(colPath(ctx,hdd.location), hdd.format, optId(verbose,hdd.id),colSizeM(ctx,asSize(hdd.size, True)), colSizeM(ctx,asSize(hdd.logicalSize, True)))2104 2105 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')2106 print colCat(ctx,"CD/DVD disks:")2107 for dvd in dvds:2108 if dvd.state != ctx['global'].constants.MediumState_Created:2109 dvd.refreshState()2110 print " %s (%s)%s %s" %(colPath(ctx,dvd.location), dvd.format,optId(verbose,dvd.id),colSizeM(ctx,asSize(dvd.size, True)))2111 2112 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')2113 print colCat(ctx,"Floppy disks:")2114 for floppy in floppys:2115 if floppy.state != ctx['global'].constants.MediumState_Created:2116 floppy.refreshState()2117 print " %s (%s)%s %s" %(colPath(ctx,floppy.location), floppy.format,optId(verbose,floppy.id), colSizeM(ctx,asSize(floppy.size, True)))2118 2119 return 02120 2121 def listUsbCmd(ctx, args):2122 if (len(args) > 1):2123 print "usage: listUsb"2124 return 02125 2126 host = ctx['vb'].host2127 for ud in ctx['global'].getArray(host, 'USBDevices'):2128 printHostUsbDev(ctx,ud)2129 2130 return 02131 2132 def findDevOfType(ctx, mach,type):2087 def optId(verbose, uuid): 2088 if verbose: 2089 return ": "+uuid 2090 else: 2091 return "" 2092 2093 def asSize(val, inBytes): 2094 if inBytes: 2095 return int(val)/(1024*1024) 2096 else: 2097 return int(val) 2098 2099 def listMediaCmd(ctx, args): 2100 if len(args) > 1: 2101 verbose = int(args[1]) 2102 else: 2103 verbose = False 2104 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks') 2105 print colCat(ctx, "Hard disks:") 2106 for hdd in hdds: 2107 if hdd.state != ctx['global'].constants.MediumState_Created: 2108 hdd.refreshState() 2109 print " %s (%s)%s %s [logical %s]" % (colPath(ctx, hdd.location), hdd.format, optId(verbose, hdd.id), colSizeM(ctx, asSize(hdd.size, True)), colSizeM(ctx, asSize(hdd.logicalSize, True))) 2110 2111 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages') 2112 print colCat(ctx, "CD/DVD disks:") 2113 for dvd in dvds: 2114 if dvd.state != ctx['global'].constants.MediumState_Created: 2115 dvd.refreshState() 2116 print " %s (%s)%s %s" % (colPath(ctx, dvd.location), dvd.format, optId(verbose, dvd.id), colSizeM(ctx, asSize(dvd.size, True))) 2117 2118 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages') 2119 print colCat(ctx, "Floppy disks:") 2120 for floppy in floppys: 2121 if floppy.state != ctx['global'].constants.MediumState_Created: 2122 floppy.refreshState() 2123 print " %s (%s)%s %s" % (colPath(ctx, floppy.location), floppy.format, optId(verbose, floppy.id), colSizeM(ctx, asSize(floppy.size, True))) 2124 2125 return 0 2126 2127 def listUsbCmd(ctx, args): 2128 if (len(args) > 1): 2129 print "usage: listUsb" 2130 return 0 2131 2132 host = ctx['vb'].host 2133 for ud in ctx['global'].getArray(host, 'USBDevices'): 2134 printHostUsbDev(ctx, ud) 2135 2136 return 0 2137 2138 def findDevOfType(ctx, mach, devtype): 2133 2139 atts = ctx['global'].getArray(mach, 'mediumAttachments') 2134 2140 for a in atts: 2135 if a.type == type:2141 if a.type == devtype: 2136 2142 return [a.controller, a.port, a.device] 2137 2143 return [None, 0, 0] 2138 2144 2139 def createHddCmd(ctx, args):2140 if (len(args) < 3):2141 print "usage: createHdd sizeM location type"2142 return 02143 2144 size = int(args[1])2145 loc = args[2]2146 if len(args) > 3:2147 format = args[3]2148 else:2149 format = "vdi"2150 2151 hdd = ctx['vb'].createHardDisk(format, loc)2152 progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, ))2153 if progressBar(ctx,progress) and hdd.id:2154 print "created HDD at %s as %s" %(colPath(ctx,hdd.location), hdd.id)2155 else:2156 print "cannot create disk (file %s exist?)" %(loc)2157 reportError(ctx,progress)2158 return 02159 2160 return 02161 2162 def registerHddCmd(ctx, args):2163 if (len(args) < 2):2164 print "usage: registerHdd location"2165 return 02166 2167 vb= ctx['vb']2168 loc = args[1]2169 setImageId = False2170 imageId = ""2171 setParentId = False2172 parentId = ""2173 hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)2174 print "registered HDD as %s" %(hdd.id)2175 return 02176 2177 def controldevice(ctx, mach,args):2178 [ctr, port,slot,type,id] = args2179 mach.attachDevice(ctr, port, slot, type,id)2180 2181 def attachHddCmd(ctx, args):2182 if (len(args) < 3):2183 print "usage: attachHdd vm hdd controller port:slot"2184 return 02185 2186 mach = argsToMach(ctx,args)2187 if mach is None:2188 return 0 2189 vb= ctx['vb']2190 loc = args[2]2191 try:2192 hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)2193 except:2194 print "no HDD with path %s registered" %(loc)2195 return 02196 if len(args) > 3:2197 ctr = args[3]2198 (port,slot) = args[4].split(":")2199 else:2200 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)2201 2202 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))2203 return 02204 2205 def detachVmDevice(ctx, mach,args):2145 def createHddCmd(ctx, args): 2146 if (len(args) < 3): 2147 print "usage: createHdd sizeM location type" 2148 return 0 2149 2150 size = int(args[1]) 2151 loc = args[2] 2152 if len(args) > 3: 2153 fmt = args[3] 2154 else: 2155 fmt = "vdi" 2156 2157 hdd = ctx['vb'].createHardDisk(format, loc) 2158 progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, )) 2159 if progressBar(ctx,progress) and hdd.id: 2160 print "created HDD at %s as %s" % (colPath(ctx,hdd.location), hdd.id) 2161 else: 2162 print "cannot create disk (file %s exist?)" % (loc) 2163 reportError(ctx,progress) 2164 return 0 2165 2166 return 0 2167 2168 def registerHddCmd(ctx, args): 2169 if (len(args) < 2): 2170 print "usage: registerHdd location" 2171 return 0 2172 2173 vbox = ctx['vb'] 2174 loc = args[1] 2175 setImageId = False 2176 imageId = "" 2177 setParentId = False 2178 parentId = "" 2179 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2180 print "registered HDD as %s" % (hdd.id) 2181 return 0 2182 2183 def controldevice(ctx, mach, args): 2184 [ctr, port, slot, devtype, uuid] = args 2185 mach.attachDevice(ctr, port, slot, devtype, uuid) 2186 2187 def attachHddCmd(ctx, args): 2188 if (len(args) < 3): 2189 print "usage: attachHdd vm hdd controller port:slot" 2190 return 0 2191 2192 mach = argsToMach(ctx, args) 2193 if mach is None: 2194 return 0 2195 vbox = ctx['vb'] 2196 loc = args[2] 2197 try: 2198 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2199 except: 2200 print "no HDD with path %s registered" % (loc) 2201 return 0 2202 if len(args) > 3: 2203 ctr = args[3] 2204 (port, slot) = args[4].split(":") 2205 else: 2206 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk) 2207 2208 cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk, hdd.id)) 2209 return 0 2210 2211 def detachVmDevice(ctx, mach, args): 2206 2212 atts = ctx['global'].getArray(mach, 'mediumAttachments') 2207 2213 hid = args[0] … … 2211 2217 mach.detachDevice(a.controller, a.port, a.device) 2212 2218 2213 def detachMedium(ctx, mid,medium):2219 def detachMedium(ctx, mid, medium): 2214 2220 cmdClosedVm(ctx, machById(ctx, mid), detachVmDevice, [medium]) 2215 2221 2216 def detachHddCmd(ctx,args): 2217 if (len(args) < 3): 2218 print "usage: detachHdd vm hdd" 2219 return 0 2220 2221 mach = argsToMach(ctx,args) 2222 if mach is None: 2223 return 0 2224 vb = ctx['vb'] 2225 loc = args[2] 2226 try: 2227 hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2228 except: 2229 print "no HDD with path %s registered" %(loc) 2230 return 0 2231 2232 detachMedium(ctx, mach.id, hdd) 2233 return 0 2234 2235 def unregisterHddCmd(ctx,args): 2236 if (len(args) < 2): 2237 print "usage: unregisterHdd path <vmunreg>" 2238 return 0 2239 2240 vb = ctx['vb'] 2241 loc = args[1] 2242 if (len(args) > 2): 2243 vmunreg = int(args[2]) 2244 else: 2245 vmunreg = 0 2246 try: 2247 hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2248 except: 2249 print "no HDD with path %s registered" %(loc) 2250 return 0 2251 2252 if vmunreg != 0: 2253 machs = ctx['global'].getArray(hdd, 'machineIds') 2254 try: 2255 for m in machs: 2256 print "Trying to detach from %s" %(m) 2257 detachMedium(ctx, m, hdd) 2258 except Exception, e: 2259 print 'failed: ',e 2260 return 0 2261 hdd.close() 2262 return 0 2263 2264 def removeHddCmd(ctx,args): 2265 if (len(args) != 2): 2266 print "usage: removeHdd path" 2267 return 0 2268 2269 vb = ctx['vb'] 2270 loc = args[1] 2271 try: 2272 hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2273 except: 2274 print "no HDD with path %s registered" %(loc) 2275 return 0 2276 2277 progress = hdd.deleteStorage() 2278 progressBar(ctx,progress) 2279 2280 return 0 2281 2282 def registerIsoCmd(ctx,args): 2283 if (len(args) < 2): 2284 print "usage: registerIso location" 2285 return 0 2286 vb = ctx['vb'] 2287 loc = args[1] 2288 iso = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2289 print "registered ISO as %s" %(iso.id) 2290 return 0 2291 2292 def unregisterIsoCmd(ctx,args): 2293 if (len(args) != 2): 2294 print "usage: unregisterIso path" 2295 return 0 2296 2297 vb = ctx['vb'] 2298 loc = args[1] 2299 try: 2300 dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2301 except: 2302 print "no DVD with path %s registered" %(loc) 2303 return 0 2304 2305 progress = dvd.close() 2306 print "Unregistered ISO at %s" %(colPath(ctx,loc)) 2307 2308 return 0 2309 2310 def removeIsoCmd(ctx,args): 2311 if (len(args) != 2): 2312 print "usage: removeIso path" 2313 return 0 2314 2315 vb = ctx['vb'] 2316 loc = args[1] 2317 try: 2318 dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2319 except: 2320 print "no DVD with path %s registered" %(loc) 2321 return 0 2322 2323 progress = dvd.deleteStorage() 2324 if progressBar(ctx,progress): 2325 print "Removed ISO at %s" %(colPath(ctx,dvd.location)) 2326 else: 2327 reportError(ctx,progress) 2328 return 0 2329 2330 def attachIsoCmd(ctx,args): 2331 if (len(args) < 3): 2332 print "usage: attachIso vm iso controller port:slot" 2333 return 0 2334 2335 mach = argsToMach(ctx,args) 2336 if mach is None: 2337 return 0 2338 vb = ctx['vb'] 2339 loc = args[2] 2340 try: 2341 dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2342 except: 2343 print "no DVD with path %s registered" %(loc) 2344 return 0 2345 if len(args) > 3: 2346 ctr = args[3] 2347 (port,slot) = args[4].split(":") 2348 else: 2349 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD) 2350 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd)) 2351 return 0 2352 2353 def detachIsoCmd(ctx,args): 2354 if (len(args) < 3): 2355 print "usage: detachIso vm iso" 2356 return 0 2357 2358 mach = argsToMach(ctx,args) 2359 if mach is None: 2360 return 0 2361 vb = ctx['vb'] 2362 loc = args[2] 2363 try: 2364 dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2365 except: 2366 print "no DVD with path %s registered" %(loc) 2367 return 0 2368 2369 detachMedium(ctx, mach.id, dvd) 2370 return 0 2371 2372 def mountIsoCmd(ctx,args): 2373 if (len(args) < 3): 2374 print "usage: mountIso vm iso controller port:slot" 2375 return 0 2376 2377 mach = argsToMach(ctx,args) 2378 if mach is None: 2379 return 0 2380 vb = ctx['vb'] 2381 loc = args[2] 2382 try: 2383 dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2384 except: 2385 print "no DVD with path %s registered" %(loc) 2386 return 0 2387 2388 if len(args) > 3: 2389 ctr = args[3] 2390 (port,slot) = args[4].split(":") 2391 else: 2392 # autodetect controller and location, just find first controller with media == DVD 2393 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD) 2394 2395 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd, True]) 2396 2397 return 0 2398 2399 def unmountIsoCmd(ctx,args): 2400 if (len(args) < 2): 2401 print "usage: unmountIso vm controller port:slot" 2402 return 0 2403 2404 mach = argsToMach(ctx,args) 2405 if mach is None: 2406 return 0 2407 vb = ctx['vb'] 2408 2409 if len(args) > 3: 2410 ctr = args[2] 2411 (port,slot) = args[3].split(":") 2412 else: 2413 # autodetect controller and location, just find first controller with media == DVD 2414 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD) 2415 2416 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, None, True]) 2417 2418 return 0 2419 2420 def attachCtr(ctx,mach,args): 2421 [name, bus, type] = args 2222 def detachHddCmd(ctx, args): 2223 if (len(args) < 3): 2224 print "usage: detachHdd vm hdd" 2225 return 0 2226 2227 mach = argsToMach(ctx, args) 2228 if mach is None: 2229 return 0 2230 vbox = ctx['vb'] 2231 loc = args[2] 2232 try: 2233 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2234 except: 2235 print "no HDD with path %s registered" % (loc) 2236 return 0 2237 2238 detachMedium(ctx, mach.id, hdd) 2239 return 0 2240 2241 def unregisterHddCmd(ctx, args): 2242 if (len(args) < 2): 2243 print "usage: unregisterHdd path <vmunreg>" 2244 return 0 2245 2246 vbox = ctx['vb'] 2247 loc = args[1] 2248 if (len(args) > 2): 2249 vmunreg = int(args[2]) 2250 else: 2251 vmunreg = 0 2252 try: 2253 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2254 except: 2255 print "no HDD with path %s registered" % (loc) 2256 return 0 2257 2258 if vmunreg != 0: 2259 machs = ctx['global'].getArray(hdd, 'machineIds') 2260 try: 2261 for mach in machs: 2262 print "Trying to detach from %s" % (mach) 2263 detachMedium(ctx, mach, hdd) 2264 except Exception, e: 2265 print 'failed: ', e 2266 return 0 2267 hdd.close() 2268 return 0 2269 2270 def removeHddCmd(ctx, args): 2271 if (len(args) != 2): 2272 print "usage: removeHdd path" 2273 return 0 2274 2275 vbox = ctx['vb'] 2276 loc = args[1] 2277 try: 2278 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false) 2279 except: 2280 print "no HDD with path %s registered" % (loc) 2281 return 0 2282 2283 progress = hdd.deleteStorage() 2284 progressBar(ctx, progress) 2285 2286 return 0 2287 2288 def registerIsoCmd(ctx, args): 2289 if (len(args) < 2): 2290 print "usage: registerIso location" 2291 return 0 2292 2293 vbox = ctx['vb'] 2294 loc = args[1] 2295 iso = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2296 print "registered ISO as %s" % (iso.id) 2297 return 0 2298 2299 def unregisterIsoCmd(ctx, args): 2300 if (len(args) != 2): 2301 print "usage: unregisterIso path" 2302 return 0 2303 2304 vbox = ctx['vb'] 2305 loc = args[1] 2306 try: 2307 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2308 except: 2309 print "no DVD with path %s registered" % (loc) 2310 return 0 2311 2312 progress = dvd.close() 2313 print "Unregistered ISO at %s" % (colPath(ctx, loc)) 2314 2315 return 0 2316 2317 def removeIsoCmd(ctx, args): 2318 if (len(args) != 2): 2319 print "usage: removeIso path" 2320 return 0 2321 2322 vbox = ctx['vb'] 2323 loc = args[1] 2324 try: 2325 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2326 except: 2327 print "no DVD with path %s registered" % (loc) 2328 return 0 2329 2330 progress = dvd.deleteStorage() 2331 if progressBar(ctx, progress): 2332 print "Removed ISO at %s" % (colPath(ctx, dvd.location)) 2333 else: 2334 reportError(ctx, progress) 2335 return 0 2336 2337 def attachIsoCmd(ctx, args): 2338 if (len(args) < 3): 2339 print "usage: attachIso vm iso controller port:slot" 2340 return 0 2341 2342 mach = argsToMach(ctx, args) 2343 if mach is None: 2344 return 0 2345 vbox = ctx['vb'] 2346 loc = args[2] 2347 try: 2348 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2349 except: 2350 print "no DVD with path %s registered" % (loc) 2351 return 0 2352 if len(args) > 3: 2353 ctr = args[3] 2354 (port, slot) = args[4].split(":") 2355 else: 2356 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD) 2357 cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd)) 2358 return 0 2359 2360 def detachIsoCmd(ctx, args): 2361 if (len(args) < 3): 2362 print "usage: detachIso vm iso" 2363 return 0 2364 2365 mach = argsToMach(ctx, args) 2366 if mach is None: 2367 return 0 2368 vbox = ctx['vb'] 2369 loc = args[2] 2370 try: 2371 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2372 except: 2373 print "no DVD with path %s registered" % (loc) 2374 return 0 2375 2376 detachMedium(ctx, mach.id, dvd) 2377 return 0 2378 2379 def mountIsoCmd(ctx, args): 2380 if (len(args) < 3): 2381 print "usage: mountIso vm iso controller port:slot" 2382 return 0 2383 2384 mach = argsToMach(ctx, args) 2385 if mach is None: 2386 return 0 2387 vbox = ctx['vb'] 2388 loc = args[2] 2389 try: 2390 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false) 2391 except: 2392 print "no DVD with path %s registered" % (loc) 2393 return 0 2394 2395 if len(args) > 3: 2396 ctr = args[3] 2397 (port, slot) = args[4].split(":") 2398 else: 2399 # autodetect controller and location, just find first controller with media == DVD 2400 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD) 2401 2402 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd, True]) 2403 2404 return 0 2405 2406 def unmountIsoCmd(ctx, args): 2407 if (len(args) < 2): 2408 print "usage: unmountIso vm controller port:slot" 2409 return 0 2410 2411 mach = argsToMach(ctx, args) 2412 if mach is None: 2413 return 0 2414 vbox = ctx['vb'] 2415 2416 if len(args) > 3: 2417 ctr = args[2] 2418 (port, slot) = args[3].split(":") 2419 else: 2420 # autodetect controller and location, just find first controller with media == DVD 2421 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD) 2422 2423 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, None, True]) 2424 2425 return 0 2426 2427 def attachCtr(ctx, mach, args): 2428 [name, bus, ctrltype] = args 2422 2429 ctr = mach.addStorageController(name, bus) 2423 if type != None:2424 ctr.controllerType = type2425 2426 def attachCtrCmd(ctx, args):2427 if (len(args) < 4):2428 print "usage: attachCtr vm cname bus <type>"2429 return 02430 2431 if len(args) > 4:2432 type = enumFromString(ctx,'StorageControllerType', args[4])2433 iftype == None:2434 print "Controller type %s unknown" %(args[4])2435 return 02436 else:2437 type = None2438 2439 mach = argsToMach(ctx,args)2440 if mach is None:2441 return 0 2442 bus = enumFromString(ctx,'StorageBus', args[3])2443 if bus is None:2444 print "Bus type %s unknown" %(args[3])2445 return 02446 name = args[2]2447 cmdClosedVm(ctx, mach, attachCtr, [name, bus,type])2448 return 02449 2450 def detachCtrCmd(ctx, args):2451 if (len(args) < 3):2452 print "usage: detachCtr vm name"2453 return 02454 2455 mach = argsToMach(ctx,args)2456 if mach is None:2457 return 0 2458 ctr = args[2]2459 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))2460 return 02461 2462 def usbctr(ctx, mach,console,args):2430 if ctrltype != None: 2431 ctr.controllerType = ctrltype 2432 2433 def attachCtrCmd(ctx, args): 2434 if (len(args) < 4): 2435 print "usage: attachCtr vm cname bus <type>" 2436 return 0 2437 2438 if len(args) > 4: 2439 ctrltype = enumFromString(ctx, 'StorageControllerType', args[4]) 2440 if ctrltype == None: 2441 print "Controller type %s unknown" % (args[4]) 2442 return 0 2443 else: 2444 ctrltype = None 2445 2446 mach = argsToMach(ctx, args) 2447 if mach is None: 2448 return 0 2449 bus = enumFromString(ctx, 'StorageBus', args[3]) 2450 if bus is None: 2451 print "Bus type %s unknown" % (args[3]) 2452 return 0 2453 name = args[2] 2454 cmdClosedVm(ctx, mach, attachCtr, [name, bus, ctrltype]) 2455 return 0 2456 2457 def detachCtrCmd(ctx, args): 2458 if (len(args) < 3): 2459 print "usage: detachCtr vm name" 2460 return 0 2461 2462 mach = argsToMach(ctx, args) 2463 if mach is None: 2464 return 0 2465 ctr = args[2] 2466 cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeStorageController(ctr)) 2467 return 0 2468 2469 def usbctr(ctx, mach, console, args): 2463 2470 if (args[0]): 2464 2471 console.attachUSBDevice(args[1]) … … 2466 2473 console.detachUSBDevice(args[1]) 2467 2474 2468 def attachUsbCmd(ctx, args):2469 if (len(args) < 3):2470 print "usage: attachUsb vm deviceuid"2471 return 02472 2473 mach = argsToMach(ctx,args)2474 if mach is None:2475 return 0 2476 dev = args[2]2477 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])2478 return 02479 2480 def detachUsbCmd(ctx, args):2481 if (len(args) < 3):2482 print "usage: detachUsb vm deviceuid"2483 return 02484 2485 mach = argsToMach(ctx,args)2486 if mach is None:2487 return 0 2488 dev = args[2]2489 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])2490 return 02491 2492 2493 def guiCmd(ctx, args):2494 if (len(args) > 1):2495 print "usage: gui"2496 return 02497 2498 binDir = ctx['global'].getBinDir()2499 2500 vbox = os.path.join(binDir, 'VirtualBox')2501 try:2475 def attachUsbCmd(ctx, args): 2476 if (len(args) < 3): 2477 print "usage: attachUsb vm deviceuid" 2478 return 0 2479 2480 mach = argsToMach(ctx, args) 2481 if mach is None: 2482 return 0 2483 dev = args[2] 2484 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr, True, dev]) 2485 return 0 2486 2487 def detachUsbCmd(ctx, args): 2488 if (len(args) < 3): 2489 print "usage: detachUsb vm deviceuid" 2490 return 0 2491 2492 mach = argsToMach(ctx, args) 2493 if mach is None: 2494 return 0 2495 dev = args[2] 2496 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr, False, dev]) 2497 return 0 2498 2499 2500 def guiCmd(ctx, args): 2501 if (len(args) > 1): 2502 print "usage: gui" 2503 return 0 2504 2505 binDir = ctx['global'].getBinDir() 2506 2507 vbox = os.path.join(binDir, 'VirtualBox') 2508 try: 2502 2509 os.system(vbox) 2503 except KeyboardInterrupt:2510 except KeyboardInterrupt: 2504 2511 # to allow interruption 2505 2512 pass 2506 return 02507 2508 def shareFolderCmd(ctx, args):2513 return 0 2514 2515 def shareFolderCmd(ctx, args): 2509 2516 if (len(args) < 4): 2510 2517 print "usage: shareFolder vm path name <writable> <persistent>" 2511 2518 return 0 2512 2519 2513 mach = argsToMach(ctx, args)2520 mach = argsToMach(ctx, args) 2514 2521 if mach is None: 2515 2522 return 0 … … 2525 2532 persistent = True 2526 2533 if persistent: 2527 cmdClosedVm(ctx, mach, lambda ctx, mach,args: mach.createSharedFolder(name, path, writable), [])2528 else: 2529 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: console.createSharedFolder(name, path, writable)])2530 return 0 2531 2532 def unshareFolderCmd(ctx, args):2534 cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.createSharedFolder(name, path, writable), []) 2535 else: 2536 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: console.createSharedFolder(name, path, writable)]) 2537 return 0 2538 2539 def unshareFolderCmd(ctx, args): 2533 2540 if (len(args) < 3): 2534 2541 print "usage: unshareFolder vm name" 2535 2542 return 0 2536 2543 2537 mach = argsToMach(ctx, args)2544 mach = argsToMach(ctx, args) 2538 2545 if mach is None: 2539 2546 return 0 … … 2542 2549 for sf in ctx['global'].getArray(mach, 'sharedFolders'): 2543 2550 if sf.name == name: 2544 cmdClosedVm(ctx, mach, lambda ctx, mach,args: mach.removeSharedFolder(name), [])2551 cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeSharedFolder(name), []) 2545 2552 found = True 2546 2553 break 2547 2554 if not found: 2548 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: console.removeSharedFolder(name)])2549 return 0 2550 2551 2552 def snapshotCmd(ctx, args):2555 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: console.removeSharedFolder(name)]) 2556 return 0 2557 2558 2559 def snapshotCmd(ctx, args): 2553 2560 if (len(args) < 2 or args[1] == 'help'): 2554 2561 print "Take snapshot: snapshot vm take name <description>" … … 2557 2564 return 0 2558 2565 2559 mach = argsToMach(ctx, args)2566 mach = argsToMach(ctx, args) 2560 2567 if mach is None: 2561 2568 return 0 … … 2570 2577 else: 2571 2578 desc = "" 2572 cmdAnyVm(ctx, mach, lambda ctx, mach,console,args: progressBar(ctx, console.takeSnapshot(name,desc)))2579 cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.takeSnapshot(name, desc))) 2573 2580 return 0 2574 2581 … … 2579 2586 name = args[3] 2580 2587 snap = mach.findSnapshot(name) 2581 cmdAnyVm(ctx, mach, lambda ctx, mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))2588 cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.restoreSnapshot(snap))) 2582 2589 return 0 2583 2590 … … 2587 2594 return 0 2588 2595 snap = mach.currentSnapshot() 2589 cmdAnyVm(ctx, mach, lambda ctx, mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))2596 cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.restoreSnapshot(snap))) 2590 2597 return 0 2591 2598 … … 2596 2603 name = args[3] 2597 2604 snap = mach.findSnapshot(name) 2598 cmdAnyVm(ctx, mach, lambda ctx, mach,console,args: progressBar(ctx, console.deleteSnapshot(snap.id)))2599 return 0 2600 2601 print "Command '%s' is unknown" % (cmd)2605 cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.deleteSnapshot(snap.id))) 2606 return 0 2607 2608 print "Command '%s' is unknown" % (cmd) 2602 2609 return 0 2603 2610 … … 2637 2644 print natAlias.__doc__ 2638 2645 return (1, None) 2639 nat.aliasMode = int(nat.aliasMode) | alias[args[a]] ;2646 nat.aliasMode = int(nat.aliasMode) | alias[args[a]] 2640 2647 return (0, None) 2641 2648 … … 2648 2655 """ 2649 2656 if len(args) == 1: 2650 (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings() ;2657 (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings() 2651 2658 if mtu == 0: mtu = 1500 2652 2659 if socksndbuf == 0: socksndbuf = 64 … … 2654 2661 if tcpsndwnd == 0: tcpsndwnd = 64 2655 2662 if tcprcvwnd == 0: tcprcvwnd = 64 2656 msg = 'mtu:%s socket(snd:%s, rcv:%s) tcpwnd(snd:%s, rcv:%s)' % (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) ;2663 msg = 'mtu:%s socket(snd:%s, rcv:%s) tcpwnd(snd:%s, rcv:%s)' % (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) 2657 2664 return (0, [msg]) 2658 2665 else: … … 2687 2694 else: 2688 2695 nat.DNSPassDomain = 'passdomain' in args 2689 nat.DNSProxy = 2690 nat.DNSUseHostResolver = 2696 nat.DNSProxy = 'proxy' in args 2697 nat.DNSUseHostResolver = 'usehostresolver' in args 2691 2698 return (0, None) 2692 2699 … … 2704 2711 if server is None: 2705 2712 server = '10.0.%d/24' % (int(nicnum) + 2) 2706 (server, mask) = server.split('/')2713 (server, mask) = server.split('/') 2707 2714 while server.count('.') != 3: 2708 2715 server += '.0' 2709 (a, b,c,d) = server.split('.')2710 server = '%d.%d.%d.4' % (a, b,c)2716 (a, b, c, d) = server.split('.') 2717 server = '%d.%d.%d.4' % (a, b, c) 2711 2718 prefix = nat.TFTPPrefix 2712 2719 if prefix is None: … … 2746 2753 pfs = ctx['global'].getArray(nat, 'redirects') 2747 2754 for pf in pfs: 2748 (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(', ')2755 (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(', ') 2749 2756 msg.append('%s: %s %s:%s => %s:%s' % (pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp)) 2750 2757 return (0, msg) # msg is array … … 2841 2848 if len(cmdargs) > 1: 2842 2849 rosession = 0 2843 session = ctx['global'].openMachineSession(mach, False) ;2844 mach = session.machine ;2850 session = ctx['global'].openMachineSession(mach, False) 2851 mach = session.machine 2845 2852 2846 2853 adapter = mach.getNetworkAdapter(nicnum) … … 2884 2891 def nicLineSpeedSubCmd(ctx, vm, nicnum, adapter, args): 2885 2892 if len(args) == 1: 2886 r = '%d kbps'% (adapter.lineSpeed)2893 r = '%d kbps'% (adapter.lineSpeed) 2887 2894 return (0, r) 2888 2895 else: … … 2911 2918 if len(args) == 1: 2912 2919 nictypes = ctx['const'].all_values('NetworkAdapterType') 2913 for nin nictypes.keys():2914 if str(adapter.adapterType) == str(nictypes[ n]):2915 return (0, str( n))2920 for key in nictypes.keys(): 2921 if str(adapter.adapterType) == str(nictypes[key]): 2922 return (0, str(key)) 2916 2923 return (1, None) 2917 2924 else: … … 3014 3021 if len(args) < 3 \ 3015 3022 or int(args[2]) not in range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType)): 3016 print 'please specify adapter num %d isn\'t in range [0-%d]'%(args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType))3017 3023 print 'please specify adapter num %d isn\'t in range [0-%d]'% (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType)) 3024 return 0 3018 3025 nicnum = int(args[2]) 3019 3026 cmdargs = args[3:] … … 3025 3032 (rc, report) = niccomand[func](ctx, vm, nicnum, adapter, cmdargs) 3026 3033 if rc == 0: 3027 3034 vm.saveSettings() 3028 3035 if report is not None: 3029 3036 print '%s nic %d %s: %s' % (vm.name, nicnum, args[3], report) … … 3034 3041 def promptCmd(ctx, args): 3035 3042 if len(args) < 2: 3036 print "Current prompt: '%s'" % (ctx['prompt'])3043 print "Current prompt: '%s'" % (ctx['prompt']) 3037 3044 return 0 3038 3045 … … 3047 3054 scope = args[1] 3048 3055 cmd = args[2] 3049 elems = eval_xpath(ctx, scope)3056 elems = eval_xpath(ctx, scope) 3050 3057 try: 3051 3058 for e in elems: … … 3062 3069 cmdargs = args[1:] 3063 3070 cmdargs.insert(1, '') 3064 for m in getMachines(ctx):3065 cmdargs[1] = m .id3071 for mach in getMachines(ctx): 3072 cmdargs[1] = mach.id 3066 3073 runCommandArgs(ctx, cmdargs) 3067 3074 return 0 … … 3071 3078 print "usage: recordDemo vm filename (duration)" 3072 3079 return 0 3073 mach = argsToMach(ctx, args)3080 mach = argsToMach(ctx, args) 3074 3081 if mach == None: 3075 3082 return 0 … … 3078 3085 if len(args) > 3: 3079 3086 dur = float(args[3]) 3080 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: recordDemo(ctx, console, filename, dur)])3087 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: recordDemo(ctx, console, filename, dur)]) 3081 3088 return 0 3082 3089 … … 3085 3092 print "usage: playbackDemo vm filename (duration)" 3086 3093 return 0 3087 mach = argsToMach(ctx, args)3094 mach = argsToMach(ctx, args) 3088 3095 if mach == None: 3089 3096 return 0 … … 3092 3099 if len(args) > 3: 3093 3100 dur = float(args[3]) 3094 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: playbackDemo(ctx, console, filename, dur)])3095 return 0 3096 3097 3098 def pciAddr(ctx, addr):3099 str = "%02x:%02x.%d" %(addr >> 8, (addr & 0xff) >> 3, addr & 7)3100 return colPci(ctx, str )3101 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: playbackDemo(ctx, console, filename, dur)]) 3102 return 0 3103 3104 3105 def pciAddr(ctx, addr): 3106 strg = "%02x:%02x.%d" % (addr >> 8, (addr & 0xff) >> 3, addr & 7) 3107 return colPci(ctx, strg) 3101 3108 3102 3109 def lspci(ctx, console): … … 3104 3111 for a in assigned: 3105 3112 if a.isPhysicalDevice: 3106 print "%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress))3113 print "%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress)) 3107 3114 3108 3115 atts = ctx['global'].getArray(console, 'attachedPCIDevices') 3109 3116 for a in atts: 3110 3117 if a.isPhysicalDevice: 3111 print "%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress))3118 print "%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress)) 3112 3119 else: 3113 print "%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress))3120 print "%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress)) 3114 3121 return 3115 3122 3116 def parsePci(str ):3123 def parsePci(strg): 3117 3124 pcire = re.compile(r'(?P<b>[0-9a-fA-F]+):(?P<d>[0-9a-fA-F]+)\.(?P<f>\d)') 3118 m = pcire.search(str)3119 if m is None:3125 match = pcire.search(strg) 3126 if match is None: 3120 3127 return -1 3121 dict = m.groupdict()3122 return ((int( dict['b'], 16)) << 8) | ((int(dict['d'], 16)) << 3) | int(dict['f'])3128 pdict = match.groupdict() 3129 return ((int(pdict['b'], 16)) << 8) | ((int(pdict['d'], 16)) << 3) | int(pdict['f']) 3123 3130 3124 3131 def lspciCmd(ctx, args): … … 3126 3133 print "usage: lspci vm" 3127 3134 return 0 3128 mach = argsToMach(ctx, args)3129 if mach == None: 3130 return 0 3131 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach,console,args: lspci(ctx, console)])3135 mach = argsToMach(ctx, args) 3136 if mach == None: 3137 return 0 3138 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: lspci(ctx, console)]) 3132 3139 return 0 3133 3140 … … 3136 3143 print "usage: attachpci vm hostpci <guestpci>" 3137 3144 return 0 3138 mach = argsToMach(ctx, args)3145 mach = argsToMach(ctx, args) 3139 3146 if mach == None: 3140 3147 return 0 3141 3148 hostaddr = parsePci(args[2]) 3142 3149 if hostaddr == -1: 3143 print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2])3150 print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]) 3144 3151 return 0 3145 3152 … … 3147 3154 guestaddr = parsePci(args[3]) 3148 3155 if guestaddr == -1: 3149 print "invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3])3156 print "invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3]) 3150 3157 return 0 3151 3158 else: 3152 3159 guestaddr = hostaddr 3153 cmdClosedVm(ctx, mach, lambda ctx, mach,a: mach.attachHostPCIDevice(hostaddr, guestaddr, True))3160 cmdClosedVm(ctx, mach, lambda ctx, mach, a: mach.attachHostPCIDevice(hostaddr, guestaddr, True)) 3154 3161 return 0 3155 3162 … … 3158 3165 print "usage: detachpci vm hostpci" 3159 3166 return 0 3160 mach = argsToMach(ctx, args)3167 mach = argsToMach(ctx, args) 3161 3168 if mach == None: 3162 3169 return 0 3163 3170 hostaddr = parsePci(args[2]) 3164 3171 if hostaddr == -1: 3165 print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2])3166 return 0 3167 3168 cmdClosedVm(ctx, mach, lambda ctx, mach,a: mach.detachHostPCIDevice(hostaddr))3172 print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]) 3173 return 0 3174 3175 cmdClosedVm(ctx, mach, lambda ctx, mach, a: mach.detachHostPCIDevice(hostaddr)) 3169 3176 return 0 3170 3177 … … 3208 3215 'verbose':['Toggle verbosity', verboseCmd, 0], 3209 3216 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0], 3210 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name, "has",m.memorySize,"M"\'', evalCmd, 0],3217 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name, "has", m.memorySize, "M"\'', evalCmd, 0], 3211 3218 'quit':['Exits', quitCmd, 0], 3212 3219 'host':['Show host information', hostCmd, 0], … … 3229 3236 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0], 3230 3237 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0], 3231 'closeportal':['Close teleportation portal (see openportal, teleport): closeportal Win', closeportalCmd, 0],3238 'closeportal':['Close teleportation portal (see openportal, teleport): closeportal Win', closeportalCmd, 0], 3232 3239 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0], 3233 3240 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0], … … 3276 3283 if aliases.get(c, None) != None: 3277 3284 c = aliases[c] 3278 ci = commands.get(c, None)3285 ci = commands.get(c, None) 3279 3286 if ci == None: 3280 print "Unknown command: '%s', type 'help' for list of known commands" % (c)3287 print "Unknown command: '%s', type 'help' for list of known commands" % (c) 3281 3288 return 0 3282 3289 if ctx['remote'] and ctx['vb'] is None: 3283 3290 if c not in ['connect', 'reconnect', 'help', 'quit']: 3284 print "First connect to remote server with %s command." % (colored('connect', 'blue'))3291 print "First connect to remote server with %s command." % (colored('connect', 'blue')) 3285 3292 return 0 3286 3293 return ci[1](ctx, args) … … 3310 3317 # they will also be picked up, so this way one can exchange 3311 3318 # shell extensions easily. 3312 def addExtsFromFile(ctx, cmds, file ):3313 if not os.path.isfile(file ):3319 def addExtsFromFile(ctx, cmds, filename): 3320 if not os.path.isfile(filename): 3314 3321 return 3315 3322 d = {} 3316 3323 try: 3317 execfile(file , d, d)3318 for (k, v) in d['commands'].items():3319 if g_ verbose:3320 print "customize: adding \"%s\" - %s" % (k, v[0])3321 cmds[k] = [v[0], v[1], file ]3324 execfile(filename, d, d) 3325 for (k, v) in d['commands'].items(): 3326 if g_fVerbose: 3327 print "customize: adding \"%s\" - %s" % (k, v[0]) 3328 cmds[k] = [v[0], v[1], filename] 3322 3329 except: 3323 print "Error loading user extensions from %s" % (file)3330 print "Error loading user extensions from %s" % (filename) 3324 3331 traceback.print_exc() 3325 3332 … … 3337 3344 # not editor temporary files, please. 3338 3345 if e.endswith('.py'): 3339 addExtsFromFile(ctx, cmds, os.path.join(shextdir, e))3346 addExtsFromFile(ctx, cmds, os.path.join(shextdir, e)) 3340 3347 3341 3348 def getHomeFolder(ctx): … … 3356 3363 vbox = ctx['vb'] 3357 3364 if vbox is not None: 3358 print "Running VirtualBox version %s" %(vbox.version) 3365 try: 3366 print "Running VirtualBox version %s" % (vbox.version) 3367 except Exception, e: 3368 printErr(ctx, e) 3369 if g_fVerbose: 3370 traceback.print_exc() 3359 3371 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox) 3360 3372 else: … … 3364 3376 checkUserExtensions(ctx, commands, home) 3365 3377 if platform.system() in ['Windows', 'Microsoft']: 3366 global g_ hascolors3367 g_ hascolors = False3368 hist_file =os.path.join(home, ".vboxshellhistory")3378 global g_fHasColors 3379 g_fHasColors = False 3380 hist_file = os.path.join(home, ".vboxshellhistory") 3369 3381 autoCompletion(commands, ctx) 3370 3382 3371 if g_ hasreadline and os.path.exists(hist_file):3383 if g_fHasReadline and os.path.exists(hist_file): 3372 3384 readline.read_history_file(hist_file) 3373 3385 … … 3375 3387 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples) 3376 3388 if ctx['perf']: 3377 try:3378 ctx['perf'].setup(['*'], [vbox.host], 10, 15)3379 except:3380 pass3389 try: 3390 ctx['perf'].setup(['*'], [vbox.host], 10, 15) 3391 except: 3392 pass 3381 3393 cmds = [] 3382 3394 3383 if g_ cmd is not None:3384 cmds = g_ cmd.split(';')3395 if g_sCmd is not None: 3396 cmds = g_sCmd.split(';') 3385 3397 it = cmds.__iter__() 3386 3398 3387 3399 while True: 3388 3400 try: 3389 if g_ batchmode:3390 cmd = 'runScript %s'% (g_scripfile)3391 elif g_ cmd is not None:3401 if g_fBatchMode: 3402 cmd = 'runScript %s'% (g_sScriptFile) 3403 elif g_sCmd is not None: 3392 3404 cmd = it.next() 3393 3405 else: … … 3395 3407 done = runCommand(ctx, cmd) 3396 3408 if done != 0: break 3397 if g_ batchmode:3409 if g_fBatchMode: 3398 3410 break 3399 3411 except KeyboardInterrupt: … … 3403 3415 except EOFError: 3404 3416 break 3405 except Exception, e:3406 printErr(ctx, e)3407 if g_ verbose:3417 except Exception, e: 3418 printErr(ctx, e) 3419 if g_fVerbose: 3408 3420 traceback.print_exc() 3409 3421 ctx['global'].waitForEvents(0) … … 3411 3423 # There is no need to disable metric collection. This is just an example. 3412 3424 if ct['perf']: 3413 ctx['perf'].disable(['*'], [vbox.host])3425 ctx['perf'].disable(['*'], [vbox.host]) 3414 3426 except: 3415 3427 pass 3416 if g_ hasreadline:3428 if g_fHasReadline: 3417 3429 readline.write_history_file(hist_file) 3418 3430 … … 3421 3433 return runCommandArgs(ctx, args) 3422 3434 3423 def runGuestCommandCb(ctx, id, guestLambda, args):3424 mach = machById(ctx,id)3435 def runGuestCommandCb(ctx, uuid, guestLambda, args): 3436 mach = machById(ctx, uuid) 3425 3437 if mach == None: 3426 3438 return 0 … … 3441 3453 parse.add_option("-c", dest="command_line", help = "command sequence to execute") 3442 3454 parse.add_option("-o", dest="opt_line", help = "option line") 3443 global g_ verbose, g_scripfile, g_batchmode, g_hascolors, g_hasreadline, g_cmd3455 global g_fVerbose, g_sScriptFile, g_fBatchMode, g_fHasColors, g_fHasReadline, g_sCmd 3444 3456 (options, args) = parse.parse_args() 3445 g_ verbose = options.verbose3457 g_fVerbose = options.verbose 3446 3458 style = options.style 3447 3459 if options.batch_file is not None: 3448 g_ batchmode = True3449 g_ hascolors = False3450 g_ hasreadline = False3451 g_s cripfile = options.batch_file3460 g_fBatchMode = True 3461 g_fHasColors = False 3462 g_fHasReadline = False 3463 g_sScriptFile = options.batch_file 3452 3464 if options.command_line is not None: 3453 g_ hascolors = False3454 g_ hasreadline = False3455 g_ cmd = options.command_line3465 g_fHasColors = False 3466 g_fHasReadline = False 3467 g_sCmd = options.command_line 3456 3468 if options.opt_line is not None: 3457 3469 params = {} 3458 3470 strparams = options.opt_line 3459 l= strparams.split(',')3460 for e in l:3461 (k ,v) = e.split('=')3462 params[k ] = v3471 strparamlist = strparams.split(',') 3472 for strparam in strparamlist: 3473 (key, value) = strparam.split('=') 3474 params[key] = value 3463 3475 else: 3464 3476 params = None … … 3469 3481 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) : 3470 3482 vpp = cwd 3471 print "Autodetected VBOX_PROGRAM_PATH as", vpp3483 print "Autodetected VBOX_PROGRAM_PATH as", vpp 3472 3484 os.environ["VBOX_PROGRAM_PATH"] = vpp 3473 3485 sys.path.append(os.path.join(vpp, "sdk", "installer")) … … 3478 3490 vsp = os.path.join(vpp, "sdk") 3479 3491 if vsp is not None : 3480 print "Autodetected VBOX_SDK_PATH as", vsp3492 print "Autodetected VBOX_SDK_PATH as", vsp 3481 3493 os.environ["VBOX_SDK_PATH"] = vsp 3482 3494 3483 3495 from vboxapi import VirtualBoxManager 3484 g_virtualBoxManager = VirtualBoxManager(style, params)3485 ctx = {'global': g_virtualBoxManager,3486 'mgr': g_virtualBoxManager.mgr,3487 'vb': g_virtualBoxManager.vbox,3488 'const': g_virtualBoxManager.constants,3489 'remote': g_virtualBoxManager.remote,3490 'type': g_virtualBoxManager.type,3491 'run': lambda cmd, args: runCommandCb(ctx, cmd, args),3492 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx,id, guestLambda, args),3493 'machById': lambda id: machById(ctx,id),3494 'argsToMach': lambda args: argsToMach(ctx, args),3495 'progressBar': lambda p: progressBar(ctx, p),3496 virtualBoxManager = VirtualBoxManager(style, params) 3497 ctx = {'global':virtualBoxManager, 3498 'mgr':virtualBoxManager.mgr, 3499 'vb':virtualBoxManager.vbox, 3500 'const':virtualBoxManager.constants, 3501 'remote':virtualBoxManager.remote, 3502 'type':virtualBoxManager.type, 3503 'run': lambda cmd, args: runCommandCb(ctx, cmd, args), 3504 'guestlambda': lambda uuid, guestLambda, args: runGuestCommandCb(ctx, uuid, guestLambda, args), 3505 'machById': lambda uuid: machById(ctx, uuid), 3506 'argsToMach': lambda args: argsToMach(ctx, args), 3507 'progressBar': lambda p: progressBar(ctx, p), 3496 3508 'typeInGuest': typeInGuest, 3497 3509 '_machlist': None, 3498 'prompt': g_ prompt,3510 'prompt': g_sPrompt, 3499 3511 'scriptLine': 0, 3500 3512 'interrupt': False 3501 3513 } 3502 3514 interpret(ctx) 3503 g_virtualBoxManager.deinit()3504 del g_virtualBoxManager3515 virtualBoxManager.deinit() 3516 del virtualBoxManager 3505 3517 3506 3518 if __name__ == '__main__':
Note:
See TracChangeset
for help on using the changeset viewer.