VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxShell/vboxshell.py@ 27894

Last change on this file since 27894 was 27894, checked in by vboxsync, 15 years ago

vboxshell: cold hotplug shall handle errors better

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 44.0 KB
Line 
1#!/usr/bin/python
2#
3# Copyright (C) 2009 Sun Microsystems, Inc.
4#
5# This file is part of VirtualBox Open Source Edition (OSE), as
6# available from http://www.215389.xyz. This file is free software;
7# you can redistribute it and/or modify it under the terms of the GNU
8# General Public License (GPL) as published by the Free Software
9# Foundation, in version 2 as it comes in the "COPYING" file of the
10# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
11# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
12#
13# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
14# Clara, CA 95054 USA or visit http://www.sun.com if you need
15# additional information or have any questions.
16#
17#################################################################################
18# This program is a simple interactive shell for VirtualBox. You can query #
19# information and issue commands from a simple command line. #
20# #
21# It also provides you with examples on how to use VirtualBox's Python API. #
22# This shell is even somewhat documented and supports TAB-completion and #
23# history if you have Python readline installed. #
24# #
25# Enjoy. #
26################################################################################
27
28import os,sys
29import traceback
30import shlex
31import time
32
33# Simple implementation of IConsoleCallback, one can use it as skeleton
34# for custom implementations
35class GuestMonitor:
36 def __init__(self, mach):
37 self.mach = mach
38
39 def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
40 print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
41 def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
42 print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, needsHostCursor)
43
44 def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
45 print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
46
47 def onStateChange(self, state):
48 print "%s: onStateChange state=%d" %(self.mach.name, state)
49
50 def onAdditionsStateChange(self):
51 print "%s: onAdditionsStateChange" %(self.mach.name)
52
53 def onNetworkAdapterChange(self, adapter):
54 print "%s: onNetworkAdapterChange" %(self.mach.name)
55
56 def onSerialPortChange(self, port):
57 print "%s: onSerialPortChange" %(self.mach.name)
58
59 def onParallelPortChange(self, port):
60 print "%s: onParallelPortChange" %(self.mach.name)
61
62 def onStorageControllerChange(self):
63 print "%s: onStorageControllerChange" %(self.mach.name)
64
65 def onMediumChange(self, attachment):
66 print "%s: onMediumChange" %(self.mach.name)
67
68 def onVRDPServerChange(self):
69 print "%s: onVRDPServerChange" %(self.mach.name)
70
71 def onUSBControllerChange(self):
72 print "%s: onUSBControllerChange" %(self.mach.name)
73
74 def onUSBDeviceStateChange(self, device, attached, error):
75 print "%s: onUSBDeviceStateChange" %(self.mach.name)
76
77 def onSharedFolderChange(self, scope):
78 print "%s: onSharedFolderChange" %(self.mach.name)
79
80 def onRuntimeError(self, fatal, id, message):
81 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
82
83 def onCanShowWindow(self):
84 print "%s: onCanShowWindow" %(self.mach.name)
85 return True
86
87 def onShowWindow(self, winId):
88 print "%s: onShowWindow: %d" %(self.mach.name, winId)
89
90class VBoxMonitor:
91 def __init__(self, params):
92 self.vbox = params[0]
93 self.isMscom = params[1]
94 pass
95
96 def onMachineStateChange(self, id, state):
97 print "onMachineStateChange: %s %d" %(id, state)
98
99 def onMachineDataChange(self,id):
100 print "onMachineDataChange: %s" %(id)
101
102 def onExtraDataCanChange(self, id, key, value):
103 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
104 # Witty COM bridge thinks if someone wishes to return tuple, hresult
105 # is one of values we want to return
106 if self.isMscom:
107 return "", 0, True
108 else:
109 return True, ""
110
111 def onExtraDataChange(self, id, key, value):
112 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
113
114 def onMediaRegistered(self, id, type, registered):
115 print "onMediaRegistered: %s" %(id)
116
117 def onMachineRegistered(self, id, registred):
118 print "onMachineRegistered: %s" %(id)
119
120 def onSessionStateChange(self, id, state):
121 print "onSessionStateChange: %s %d" %(id, state)
122
123 def onSnapshotTaken(self, mach, id):
124 print "onSnapshotTaken: %s %s" %(mach, id)
125
126 def onSnapshotDiscarded(self, mach, id):
127 print "onSnapshotDiscarded: %s %s" %(mach, id)
128
129 def onSnapshotChange(self, mach, id):
130 print "onSnapshotChange: %s %s" %(mach, id)
131
132 def onGuestPropertyChange(self, id, name, newValue, flags):
133 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
134
135g_hasreadline = 1
136try:
137 import readline
138 import rlcompleter
139except:
140 g_hasreadline = 0
141
142
143if g_hasreadline:
144 class CompleterNG(rlcompleter.Completer):
145 def __init__(self, dic, ctx):
146 self.ctx = ctx
147 return rlcompleter.Completer.__init__(self,dic)
148
149 def complete(self, text, state):
150 """
151 taken from:
152 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
153 """
154 if text == "":
155 return ['\t',None][state]
156 else:
157 return rlcompleter.Completer.complete(self,text,state)
158
159 def global_matches(self, text):
160 """
161 Compute matches when text is a simple name.
162 Return a list of all names currently defined
163 in self.namespace that match.
164 """
165
166 matches = []
167 n = len(text)
168
169 for list in [ self.namespace ]:
170 for word in list:
171 if word[:n] == text:
172 matches.append(word)
173
174
175 try:
176 for m in getMachines(self.ctx):
177 # although it has autoconversion, we need to cast
178 # explicitly for subscripts to work
179 word = str(m.name)
180 if word[:n] == text:
181 matches.append(word)
182 word = str(m.id)
183 if word[0] == '{':
184 word = word[1:-1]
185 if word[:n] == text:
186 matches.append(word)
187 except Exception,e:
188 traceback.print_exc()
189 print e
190
191 return matches
192
193
194def autoCompletion(commands, ctx):
195 if not g_hasreadline:
196 return
197
198 comps = {}
199 for (k,v) in commands.items():
200 comps[k] = None
201 completer = CompleterNG(comps, ctx)
202 readline.set_completer(completer.complete)
203 readline.parse_and_bind("tab: complete")
204
205g_verbose = True
206
207def split_no_quotes(s):
208 return shlex.split(s)
209
210def progressBar(ctx,p,wait=1000):
211 try:
212 while not p.completed:
213 print "%d %%\r" %(p.percent),
214 sys.stdout.flush()
215 p.waitForCompletion(wait)
216 ctx['global'].waitForEvents(0)
217 except KeyboardInterrupt:
218 print "Interrupted."
219
220
221def reportError(ctx,session,rc):
222 if not ctx['remote']:
223 print session.QueryErrorObject(rc)
224
225
226def createVm(ctx,name,kind,base):
227 mgr = ctx['mgr']
228 vb = ctx['vb']
229 mach = vb.createMachine(name, kind, base, "")
230 mach.saveSettings()
231 print "created machine with UUID",mach.id
232 vb.registerMachine(mach)
233 # update cache
234 getMachines(ctx, True)
235
236def removeVm(ctx,mach):
237 mgr = ctx['mgr']
238 vb = ctx['vb']
239 id = mach.id
240 print "removing machine ",mach.name,"with UUID",id
241 session = ctx['global'].openMachineSession(id)
242 try:
243 mach = session.machine
244 for d in ctx['global'].getArray(mach, 'mediumAttachments'):
245 mach.detachDevice(d.controller, d.port, d.device)
246 except:
247 traceback.print_exc()
248 mach.saveSettings()
249 ctx['global'].closeMachineSession(session)
250 mach = vb.unregisterMachine(id)
251 if mach:
252 mach.deleteSettings()
253 # update cache
254 getMachines(ctx, True)
255
256def startVm(ctx,mach,type):
257 mgr = ctx['mgr']
258 vb = ctx['vb']
259 perf = ctx['perf']
260 session = mgr.getSessionObject(vb)
261 uuid = mach.id
262 progress = vb.openRemoteSession(session, uuid, type, "")
263 progressBar(ctx, progress, 100)
264 completed = progress.completed
265 rc = int(progress.resultCode)
266 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
267 if rc == 0:
268 # we ignore exceptions to allow starting VM even if
269 # perf collector cannot be started
270 if perf:
271 try:
272 perf.setup(['*'], [mach], 10, 15)
273 except Exception,e:
274 print e
275 if g_verbose:
276 traceback.print_exc()
277 pass
278 # if session not opened, close doesn't make sense
279 session.close()
280 else:
281 reportError(ctx,session,rc)
282
283def getMachines(ctx, invalidate = False):
284 if ctx['vb'] is not None:
285 if ctx['_machlist'] is None or invalidate:
286 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
287 return ctx['_machlist']
288 else:
289 return []
290
291def asState(var):
292 if var:
293 return 'on'
294 else:
295 return 'off'
296
297def perfStats(ctx,mach):
298 if not ctx['perf']:
299 return
300 for metric in ctx['perf'].query(["*"], [mach]):
301 print metric['name'], metric['values_as_string']
302
303def guestExec(ctx, machine, console, cmds):
304 exec cmds
305
306def monitorGuest(ctx, machine, console, dur):
307 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
308 console.registerCallback(cb)
309 if dur == -1:
310 # not infinity, but close enough
311 dur = 100000
312 try:
313 end = time.time() + dur
314 while time.time() < end:
315 ctx['global'].waitForEvents(500)
316 # We need to catch all exceptions here, otherwise callback will never be unregistered
317 except:
318 pass
319 console.unregisterCallback(cb)
320
321
322def monitorVBox(ctx, dur):
323 vbox = ctx['vb']
324 isMscom = (ctx['global'].type == 'MSCOM')
325 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
326 vbox.registerCallback(cb)
327 if dur == -1:
328 # not infinity, but close enough
329 dur = 100000
330 try:
331 end = time.time() + dur
332 while time.time() < end:
333 ctx['global'].waitForEvents(500)
334 # We need to catch all exceptions here, otherwise callback will never be unregistered
335 except:
336 pass
337 vbox.unregisterCallback(cb)
338
339
340def takeScreenshot(ctx,console,args):
341 from PIL import Image
342 display = console.display
343 if len(args) > 0:
344 f = args[0]
345 else:
346 f = "/tmp/screenshot.png"
347 if len(args) > 1:
348 w = args[1]
349 else:
350 w = console.display.width
351 if len(args) > 2:
352 h = args[2]
353 else:
354 h = console.display.height
355 print "Saving screenshot (%d x %d) in %s..." %(w,h,f)
356 data = display.takeScreenShotSlow(w,h)
357 size = (w,h)
358 mode = "RGBA"
359 im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
360 im.save(f, "PNG")
361
362
363def teleport(ctx,session,console,args):
364 if args[0].find(":") == -1:
365 print "Use host:port format for teleport target"
366 return
367 (host,port) = args[0].split(":")
368 if len(args) > 1:
369 passwd = args[1]
370 else:
371 passwd = ""
372
373 if len(args) > 2:
374 maxDowntime = int(args[2])
375 else:
376 maxDowntime = 250
377
378 port = int(port)
379 print "Teleporting to %s:%d..." %(host,port)
380 progress = console.teleport(host, port, passwd, maxDowntime)
381 progressBar(ctx, progress, 100)
382 completed = progress.completed
383 rc = int(progress.resultCode)
384 if rc == 0:
385 print "Success!"
386 else:
387 reportError(ctx,session,rc)
388
389
390def guestStats(ctx,console,args):
391 guest = console.guest
392 # we need to set up guest statistics
393 if len(args) > 0 :
394 update = args[0]
395 else:
396 update = 1
397 if guest.statisticsUpdateInterval != update:
398 guest.statisticsUpdateInterval = update
399 try:
400 time.sleep(float(update)+0.1)
401 except:
402 # to allow sleep interruption
403 pass
404 all_stats = ctx['ifaces'].all_values('GuestStatisticType')
405 cpu = 0
406 for s in all_stats.keys():
407 try:
408 val = guest.getStatistic( cpu, all_stats[s])
409 print "%s: %d" %(s, val)
410 except:
411 # likely not implemented
412 pass
413
414def plugCpu(ctx,machine,session,args):
415 cpu = int(args)
416 print "Adding CPU %d..." %(cpu)
417 machine.hotPlugCPU(cpu)
418
419def unplugCpu(ctx,machine,session,args):
420 cpu = int(args)
421 print "Removing CPU %d..." %(cpu)
422 machine.hotUnplugCPU(cpu)
423
424def cmdExistingVm(ctx,mach,cmd,args):
425 mgr=ctx['mgr']
426 vb=ctx['vb']
427 session = mgr.getSessionObject(vb)
428 uuid = mach.id
429 try:
430 progress = vb.openExistingSession(session, uuid)
431 except Exception,e:
432 print "Session to '%s' not open: %s" %(mach.name,e)
433 if g_verbose:
434 traceback.print_exc()
435 return
436 if str(session.state) != str(ctx['ifaces'].SessionState_Open):
437 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
438 return
439 # this could be an example how to handle local only (i.e. unavailable
440 # in Webservices) functionality
441 if ctx['remote'] and cmd == 'some_local_only_command':
442 print 'Trying to use local only functionality, ignored'
443 return
444 console=session.console
445 ops={'pause': lambda: console.pause(),
446 'resume': lambda: console.resume(),
447 'powerdown': lambda: console.powerDown(),
448 'powerbutton': lambda: console.powerButton(),
449 'stats': lambda: perfStats(ctx, mach),
450 'guest': lambda: guestExec(ctx, mach, console, args),
451 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
452 'save': lambda: progressBar(ctx,console.saveState()),
453 'screenshot': lambda: takeScreenshot(ctx,console,args),
454 'teleport': lambda: teleport(ctx,session,console,args),
455 'gueststats': lambda: guestStats(ctx, console, args),
456 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
457 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
458 }
459 try:
460 ops[cmd]()
461 except Exception, e:
462 print 'failed: ',e
463 if g_verbose:
464 traceback.print_exc()
465
466 session.close()
467
468def machById(ctx,id):
469 mach = None
470 for m in getMachines(ctx):
471 if m.name == id:
472 mach = m
473 break
474 mid = str(m.id)
475 if mid[0] == '{':
476 mid = mid[1:-1]
477 if mid == id:
478 mach = m
479 break
480 return mach
481
482def argsToMach(ctx,args):
483 if len(args) < 2:
484 print "usage: %s [vmname|uuid]" %(args[0])
485 return None
486 id = args[1]
487 m = machById(ctx, id)
488 if m == None:
489 print "Machine '%s' is unknown, use list command to find available machines" %(id)
490 return m
491
492def helpSingleCmd(cmd,h,sp):
493 if sp != 0:
494 spec = " [ext from "+sp+"]"
495 else:
496 spec = ""
497 print " %s: %s%s" %(cmd,h,spec)
498
499def helpCmd(ctx, args):
500 if len(args) == 1:
501 print "Help page:"
502 names = commands.keys()
503 names.sort()
504 for i in names:
505 helpSingleCmd(i, commands[i][0], commands[i][2])
506 else:
507 cmd = args[1]
508 c = commands.get(cmd)
509 if c == None:
510 print "Command '%s' not known" %(cmd)
511 else:
512 helpSingleCmd(cmd, c[0], c[2])
513 return 0
514
515def listCmd(ctx, args):
516 for m in getMachines(ctx, True):
517 if m.teleporterEnabled:
518 tele = "[T] "
519 else:
520 tele = " "
521 print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,m.sessionState)
522 return 0
523
524def getControllerType(type):
525 if type == 0:
526 return "Null"
527 elif type == 1:
528 return "LsiLogic"
529 elif type == 2:
530 return "BusLogic"
531 elif type == 3:
532 return "IntelAhci"
533 elif type == 4:
534 return "PIIX3"
535 elif type == 5:
536 return "PIIX4"
537 elif type == 6:
538 return "ICH6"
539 else:
540 return "Unknown"
541
542def getFirmwareType(type):
543 if type == 0:
544 return "invalid"
545 elif type == 1:
546 return "bios"
547 elif type == 2:
548 return "efi"
549 elif type == 3:
550 return "efi64"
551 elif type == 4:
552 return "efidual"
553 else:
554 return "Unknown"
555
556
557def asEnumElem(ctx,enum,elem):
558 all = ctx['ifaces'].all_values(enum)
559 for e in all.keys():
560 if elem == all[e]:
561 return e
562 return "<unknown>"
563
564def infoCmd(ctx,args):
565 if (len(args) < 2):
566 print "usage: info [vmname|uuid]"
567 return 0
568 mach = argsToMach(ctx,args)
569 if mach == None:
570 return 0
571 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
572 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
573 print " Name [name]: %s" %(mach.name)
574 print " ID [n/a]: %s" %(mach.id)
575 print " OS Type [n/a]: %s" %(os.description)
576 print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
577 print
578 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
579 print " RAM [memorySize]: %dM" %(mach.memorySize)
580 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
581 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
582 print
583 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
584 print " Machine status [n/a]: %d" % (mach.sessionState)
585 print
586 if mach.teleporterEnabled:
587 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
588 print
589 bios = mach.BIOSSettings
590 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
591 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
592 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
593 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
594 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
595 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
596 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
597 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
598
599 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
600 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
601
602 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
603 print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
604
605 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
606 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
607 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
608 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
609
610 controllers = ctx['global'].getArray(mach, 'storageControllers')
611 if controllers:
612 print
613 print " Controllers:"
614 for controller in controllers:
615 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
616
617 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
618 if attaches:
619 print
620 print " Mediums:"
621 for a in attaches:
622 print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
623 m = a.medium
624 if a.type == ctx['global'].constants.DeviceType_HardDisk:
625 print " HDD:"
626 print " Id: %s" %(m.id)
627 print " Location: %s" %(m.location)
628 print " Name: %s" %(m.name)
629 print " Format: %s" %(m.format)
630
631 if a.type == ctx['global'].constants.DeviceType_DVD:
632 print " DVD:"
633 if m:
634 print " Id: %s" %(m.id)
635 print " Name: %s" %(m.name)
636 if m.hostDrive:
637 print " Host DVD %s" %(m.location)
638 if a.passthrough:
639 print " [passthrough mode]"
640 else:
641 print " Virtual image at %s" %(m.location)
642 print " Size: %s" %(m.size)
643
644 if a.type == ctx['global'].constants.DeviceType_Floppy:
645 print " Floppy:"
646 if m:
647 print " Id: %s" %(m.id)
648 print " Name: %s" %(m.name)
649 if m.hostDrive:
650 print " Host floppy %s" %(m.location)
651 else:
652 print " Virtual image at %s" %(m.location)
653 print " Size: %s" %(m.size)
654
655 return 0
656
657def startCmd(ctx, args):
658 mach = argsToMach(ctx,args)
659 if mach == None:
660 return 0
661 if len(args) > 2:
662 type = args[2]
663 else:
664 type = "gui"
665 startVm(ctx, mach, type)
666 return 0
667
668def createCmd(ctx, args):
669 if (len(args) < 3 or len(args) > 4):
670 print "usage: create name ostype <basefolder>"
671 return 0
672 name = args[1]
673 oskind = args[2]
674 if len(args) == 4:
675 base = args[3]
676 else:
677 base = ''
678 try:
679 ctx['vb'].getGuestOSType(oskind)
680 except Exception, e:
681 print 'Unknown OS type:',oskind
682 return 0
683 createVm(ctx, name, oskind, base)
684 return 0
685
686def removeCmd(ctx, args):
687 mach = argsToMach(ctx,args)
688 if mach == None:
689 return 0
690 removeVm(ctx, mach)
691 return 0
692
693def pauseCmd(ctx, args):
694 mach = argsToMach(ctx,args)
695 if mach == None:
696 return 0
697 cmdExistingVm(ctx, mach, 'pause', '')
698 return 0
699
700def powerdownCmd(ctx, args):
701 mach = argsToMach(ctx,args)
702 if mach == None:
703 return 0
704 cmdExistingVm(ctx, mach, 'powerdown', '')
705 return 0
706
707def powerbuttonCmd(ctx, args):
708 mach = argsToMach(ctx,args)
709 if mach == None:
710 return 0
711 cmdExistingVm(ctx, mach, 'powerbutton', '')
712 return 0
713
714def resumeCmd(ctx, args):
715 mach = argsToMach(ctx,args)
716 if mach == None:
717 return 0
718 cmdExistingVm(ctx, mach, 'resume', '')
719 return 0
720
721def saveCmd(ctx, args):
722 mach = argsToMach(ctx,args)
723 if mach == None:
724 return 0
725 cmdExistingVm(ctx, mach, 'save', '')
726 return 0
727
728def statsCmd(ctx, args):
729 mach = argsToMach(ctx,args)
730 if mach == None:
731 return 0
732 cmdExistingVm(ctx, mach, 'stats', '')
733 return 0
734
735def guestCmd(ctx, args):
736 if (len(args) < 3):
737 print "usage: guest name commands"
738 return 0
739 mach = argsToMach(ctx,args)
740 if mach == None:
741 return 0
742 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
743 return 0
744
745def screenshotCmd(ctx, args):
746 if (len(args) < 3):
747 print "usage: screenshot name file <width> <height>"
748 return 0
749 mach = argsToMach(ctx,args)
750 if mach == None:
751 return 0
752 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
753 return 0
754
755def teleportCmd(ctx, args):
756 if (len(args) < 3):
757 print "usage: teleport name host:port <password>"
758 return 0
759 mach = argsToMach(ctx,args)
760 if mach == None:
761 return 0
762 cmdExistingVm(ctx, mach, 'teleport', args[2:])
763 return 0
764
765def openportalCmd(ctx, args):
766 if (len(args) < 3):
767 print "usage: openportal name port <password>"
768 return 0
769 mach = argsToMach(ctx,args)
770 if mach == None:
771 return 0
772 port = int(args[2])
773 if (len(args) > 3):
774 passwd = args[3]
775 else:
776 passwd = ""
777 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
778 session = ctx['global'].openMachineSession(mach.id)
779 mach1 = session.machine
780 mach1.teleporterEnabled = True
781 mach1.teleporterPort = port
782 mach1.teleporterPassword = passwd
783 mach1.saveSettings()
784 session.close()
785 startVm(ctx, mach, "gui")
786 return 0
787
788def closeportalCmd(ctx, args):
789 if (len(args) < 2):
790 print "usage: closeportal name"
791 return 0
792 mach = argsToMach(ctx,args)
793 if mach == None:
794 return 0
795 if mach.teleporterEnabled:
796 session = ctx['global'].openMachineSession(mach.id)
797 mach1 = session.machine
798 mach1.teleporterEnabled = False
799 mach1.saveSettings()
800 session.close()
801 return 0
802
803def gueststatsCmd(ctx, args):
804 if (len(args) < 2):
805 print "usage: gueststats name <check interval>"
806 return 0
807 mach = argsToMach(ctx,args)
808 if mach == None:
809 return 0
810 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
811 return 0
812
813def plugcpuCmd(ctx, args):
814 if (len(args) < 2):
815 print "usage: plugcpu name cpuid"
816 return 0
817 mach = argsToMach(ctx,args)
818 if mach == None:
819 return 0
820 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
821 if mach.CPUHotPlugEnabled:
822 session = ctx['global'].openMachineSession(mach.id)
823 try:
824 mach1 = session.machine
825 cpu = int(args[2])
826 print "Adding CPU %d..." %(cpu)
827 mach1.hotPlugCPU(cpu)
828 mach1.saveSettings()
829 except:
830 session.close()
831 raise
832 session.close()
833 else:
834 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
835 return 0
836
837def unplugcpuCmd(ctx, args):
838 if (len(args) < 2):
839 print "usage: unplugcpu name cpuid"
840 return 0
841 mach = argsToMach(ctx,args)
842 if mach == None:
843 return 0
844 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
845 if mach.CPUHotPlugEnabled:
846 session = ctx['global'].openMachineSession(mach.id)
847 try:
848 mach1 = session.machine
849 cpu = int(args[2])
850 print "Removing CPU %d..." %(cpu)
851 mach1.hotUnplugCPU(cpu)
852 mach1.saveSettings()
853 except:
854 session.close()
855 raise
856 session.close()
857 else:
858 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
859 return 0
860
861def setvarCmd(ctx, args):
862 if (len(args) < 4):
863 print "usage: setvar [vmname|uuid] expr value"
864 return 0
865 mach = argsToMach(ctx,args)
866 if mach == None:
867 return 0
868 session = ctx['global'].openMachineSession(mach.id)
869 mach = session.machine
870 expr = 'mach.'+args[2]+' = '+args[3]
871 print "Executing",expr
872 try:
873 exec expr
874 except Exception, e:
875 print 'failed: ',e
876 if g_verbose:
877 traceback.print_exc()
878 mach.saveSettings()
879 session.close()
880 return 0
881
882
883def setExtraDataCmd(ctx, args):
884 if (len(args) < 3):
885 print "usage: setextra [vmname|uuid|global] key <value>"
886 return 0
887 key = args[2]
888 if len(args) == 4:
889 value = args[3]
890 else:
891 value = None
892 if args[1] == 'global':
893 ctx['vb'].setExtraData(key, value)
894 return 0
895
896 mach = argsToMach(ctx,args)
897 if mach == None:
898 return 0
899 session = ctx['global'].openMachineSession(mach.id)
900 mach = session.machine
901 mach.setExtraData(key, value)
902 mach.saveSettings()
903 session.close()
904 return 0
905
906def printExtraKey(obj, key, value):
907 print "%s: '%s' = '%s'" %(obj, key, value)
908
909def getExtraDataCmd(ctx, args):
910 if (len(args) < 2):
911 print "usage: getextra [vmname|uuid|global] <key>"
912 return 0
913 if len(args) == 3:
914 key = args[2]
915 else:
916 key = None
917
918 if args[1] == 'global':
919 obj = ctx['vb']
920 else:
921 obj = argsToMach(ctx,args)
922 if obj == None:
923 return 0
924
925 if key == None:
926 keys = obj.getExtraDataKeys()
927 else:
928 keys = [ key ]
929 for k in keys:
930 printExtraKey(args[1], k, ctx['vb'].getExtraData(k))
931
932 return 0
933
934def quitCmd(ctx, args):
935 return 1
936
937def aliasCmd(ctx, args):
938 if (len(args) == 3):
939 aliases[args[1]] = args[2]
940 return 0
941
942 for (k,v) in aliases.items():
943 print "'%s' is an alias for '%s'" %(k,v)
944 return 0
945
946def verboseCmd(ctx, args):
947 global g_verbose
948 g_verbose = not g_verbose
949 return 0
950
951def getUSBStateString(state):
952 if state == 0:
953 return "NotSupported"
954 elif state == 1:
955 return "Unavailable"
956 elif state == 2:
957 return "Busy"
958 elif state == 3:
959 return "Available"
960 elif state == 4:
961 return "Held"
962 elif state == 5:
963 return "Captured"
964 else:
965 return "Unknown"
966
967def hostCmd(ctx, args):
968 host = ctx['vb'].host
969 cnt = host.processorCount
970 print "Processor count:",cnt
971 for i in range(0,cnt):
972 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
973
974 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
975 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
976 if host.Acceleration3DAvailable:
977 print "3D acceleration available"
978 else:
979 print "3D acceleration NOT available"
980
981 print "Network interfaces:"
982 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
983 print " %s (%s)" %(ni.name, ni.IPAddress)
984
985 print "DVD drives:"
986 for dd in ctx['global'].getArray(host, 'DVDDrives'):
987 print " %s - %s" %(dd.name, dd.description)
988
989 print "USB devices:"
990 for ud in ctx['global'].getArray(host, 'USBDevices'):
991 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
992
993 if ctx['perf']:
994 for metric in ctx['perf'].query(["*"], [host]):
995 print metric['name'], metric['values_as_string']
996
997 return 0
998
999def monitorGuestCmd(ctx, args):
1000 if (len(args) < 2):
1001 print "usage: monitorGuest name (duration)"
1002 return 0
1003 mach = argsToMach(ctx,args)
1004 if mach == None:
1005 return 0
1006 dur = 5
1007 if len(args) > 2:
1008 dur = float(args[2])
1009 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1010 return 0
1011
1012def monitorVBoxCmd(ctx, args):
1013 if (len(args) > 2):
1014 print "usage: monitorVBox (duration)"
1015 return 0
1016 dur = 5
1017 if len(args) > 1:
1018 dur = float(args[1])
1019 monitorVBox(ctx, dur)
1020 return 0
1021
1022def getAdapterType(ctx, type):
1023 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1024 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1025 return "pcnet"
1026 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1027 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1028 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1029 return "e1000"
1030 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1031 return "virtio"
1032 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1033 return None
1034 else:
1035 raise Exception("Unknown adapter type: "+type)
1036
1037
1038def portForwardCmd(ctx, args):
1039 if (len(args) != 5):
1040 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1041 return 0
1042 mach = argsToMach(ctx,args)
1043 if mach == None:
1044 return 0
1045 adapterNum = int(args[2])
1046 hostPort = int(args[3])
1047 guestPort = int(args[4])
1048 proto = "TCP"
1049 session = ctx['global'].openMachineSession(mach.id)
1050 mach = session.machine
1051
1052 adapter = mach.getNetworkAdapter(adapterNum)
1053 adapterType = getAdapterType(ctx, adapter.adapterType)
1054
1055 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1056 config = "VBoxInternal/Devices/" + adapterType + "/"
1057 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1058
1059 mach.setExtraData(config + "/Protocol", proto)
1060 mach.setExtraData(config + "/HostPort", str(hostPort))
1061 mach.setExtraData(config + "/GuestPort", str(guestPort))
1062
1063 mach.saveSettings()
1064 session.close()
1065
1066 return 0
1067
1068
1069def showLogCmd(ctx, args):
1070 if (len(args) < 2):
1071 print "usage: showLog <vm> <num>"
1072 return 0
1073 mach = argsToMach(ctx,args)
1074 if mach == None:
1075 return 0
1076
1077 log = "VBox.log"
1078 if (len(args) > 2):
1079 log += "."+args[2]
1080 fileName = os.path.join(mach.logFolder, log)
1081
1082 try:
1083 lf = open(fileName, 'r')
1084 except IOError,e:
1085 print "cannot open: ",e
1086 return 0
1087
1088 for line in lf:
1089 print line,
1090 lf.close()
1091
1092 return 0
1093
1094def evalCmd(ctx, args):
1095 expr = ' '.join(args[1:])
1096 try:
1097 exec expr
1098 except Exception, e:
1099 print 'failed: ',e
1100 if g_verbose:
1101 traceback.print_exc()
1102 return 0
1103
1104def reloadExtCmd(ctx, args):
1105 # maybe will want more args smartness
1106 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1107 autoCompletion(commands, ctx)
1108 return 0
1109
1110
1111def runScriptCmd(ctx, args):
1112 if (len(args) != 2):
1113 print "usage: runScript <script>"
1114 return 0
1115 try:
1116 lf = open(args[1], 'r')
1117 except IOError,e:
1118 print "cannot open:",args[1], ":",e
1119 return 0
1120
1121 try:
1122 for line in lf:
1123 done = runCommand(ctx, line)
1124 if done != 0: break
1125 except Exception,e:
1126 print "error:",e
1127 if g_verbose:
1128 traceback.print_exc()
1129 lf.close()
1130 return 0
1131
1132def sleepCmd(ctx, args):
1133 if (len(args) != 2):
1134 print "usage: sleep <secs>"
1135 return 0
1136
1137 try:
1138 time.sleep(float(args[1]))
1139 except:
1140 # to allow sleep interrupt
1141 pass
1142 return 0
1143
1144
1145def shellCmd(ctx, args):
1146 if (len(args) < 2):
1147 print "usage: shell <commands>"
1148 return 0
1149 cmd = ' '.join(args[1:])
1150 try:
1151 os.system(cmd)
1152 except KeyboardInterrupt:
1153 # to allow shell command interruption
1154 pass
1155 return 0
1156
1157
1158def connectCmd(ctx, args):
1159 if (len(args) > 4):
1160 print "usage: connect [url] [username] [passwd]"
1161 return 0
1162
1163 if ctx['vb'] is not None:
1164 print "Already connected, disconnect first..."
1165 return 0
1166
1167 if (len(args) > 1):
1168 url = args[1]
1169 else:
1170 url = None
1171
1172 if (len(args) > 2):
1173 user = args[2]
1174 else:
1175 user = ""
1176
1177 if (len(args) > 3):
1178 passwd = args[3]
1179 else:
1180 passwd = ""
1181
1182 vbox = ctx['global'].platform.connect(url, user, passwd)
1183 ctx['vb'] = vbox
1184 print "Running VirtualBox version %s" %(vbox.version)
1185 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1186 return 0
1187
1188def disconnectCmd(ctx, args):
1189 if (len(args) != 1):
1190 print "usage: disconnect"
1191 return 0
1192
1193 if ctx['vb'] is None:
1194 print "Not connected yet."
1195 return 0
1196
1197 try:
1198 ctx['global'].platform.disconnect()
1199 except:
1200 ctx['vb'] = None
1201 raise
1202
1203 ctx['vb'] = None
1204 return 0
1205
1206def exportVMCmd(ctx, args):
1207 import sys
1208
1209 if len(args) < 3:
1210 print "usage: exportVm <machine> <path> <format> <license>"
1211 return 0
1212 mach = ctx['machById'](args[1])
1213 if mach is None:
1214 return 0
1215 path = args[2]
1216 if (len(args) > 3):
1217 format = args[3]
1218 else:
1219 format = "ovf-1.0"
1220 if (len(args) > 4):
1221 license = args[4]
1222 else:
1223 license = "GPL"
1224
1225 app = ctx['vb'].createAppliance()
1226 desc = mach.export(app)
1227 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1228 p = app.write(format, path)
1229 progressBar(ctx, p)
1230 print "Exported to %s in format %s" %(path, format)
1231 return 0
1232
1233aliases = {'s':'start',
1234 'i':'info',
1235 'l':'list',
1236 'h':'help',
1237 'a':'alias',
1238 'q':'quit', 'exit':'quit',
1239 'v':'verbose'}
1240
1241commands = {'help':['Prints help information', helpCmd, 0],
1242 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
1243 'create':['Create virtual machine', createCmd, 0],
1244 'remove':['Remove virtual machine', removeCmd, 0],
1245 'pause':['Pause virtual machine', pauseCmd, 0],
1246 'resume':['Resume virtual machine', resumeCmd, 0],
1247 'save':['Save execution state of virtual machine', saveCmd, 0],
1248 'stats':['Stats for virtual machine', statsCmd, 0],
1249 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1250 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1251 'list':['Shows known virtual machines', listCmd, 0],
1252 'info':['Shows info on machine', infoCmd, 0],
1253 'alias':['Control aliases', aliasCmd, 0],
1254 'verbose':['Toggle verbosity', verboseCmd, 0],
1255 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1256 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1257 'quit':['Exits', quitCmd, 0],
1258 'host':['Show host information', hostCmd, 0],
1259 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
1260 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1261 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1262 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1263 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1264 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1265 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1266 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1267 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1268 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
1269 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1270 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
1271 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
1272 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
1273 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
1274 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
1275 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
1276 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
1277 'unplugcpu':['Remove a CPU from a running VM: plugcpu Win 1', unplugcpuCmd, 0],
1278 }
1279
1280def runCommandArgs(ctx, args):
1281 c = args[0]
1282 if aliases.get(c, None) != None:
1283 c = aliases[c]
1284 ci = commands.get(c,None)
1285 if ci == None:
1286 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
1287 return 0
1288 return ci[1](ctx, args)
1289
1290
1291def runCommand(ctx, cmd):
1292 if len(cmd) == 0: return 0
1293 args = split_no_quotes(cmd)
1294 if len(args) == 0: return 0
1295 return runCommandArgs(ctx, args)
1296
1297#
1298# To write your own custom commands to vboxshell, create
1299# file ~/.VirtualBox/shellext.py with content like
1300#
1301# def runTestCmd(ctx, args):
1302# print "Testy test", ctx['vb']
1303# return 0
1304#
1305# commands = {
1306# 'test': ['Test help', runTestCmd]
1307# }
1308# and issue reloadExt shell command.
1309# This file also will be read automatically on startup or 'reloadExt'.
1310#
1311# Also one can put shell extensions into ~/.VirtualBox/shexts and
1312# they will also be picked up, so this way one can exchange
1313# shell extensions easily.
1314def addExtsFromFile(ctx, cmds, file):
1315 if not os.path.isfile(file):
1316 return
1317 d = {}
1318 try:
1319 execfile(file, d, d)
1320 for (k,v) in d['commands'].items():
1321 if g_verbose:
1322 print "customize: adding \"%s\" - %s" %(k, v[0])
1323 cmds[k] = [v[0], v[1], file]
1324 except:
1325 print "Error loading user extensions from %s" %(file)
1326 traceback.print_exc()
1327
1328
1329def checkUserExtensions(ctx, cmds, folder):
1330 folder = str(folder)
1331 name = os.path.join(folder, "shellext.py")
1332 addExtsFromFile(ctx, cmds, name)
1333 # also check 'exts' directory for all files
1334 shextdir = os.path.join(folder, "shexts")
1335 if not os.path.isdir(shextdir):
1336 return
1337 exts = os.listdir(shextdir)
1338 for e in exts:
1339 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
1340
1341def getHomeFolder(ctx):
1342 if ctx['remote'] or ctx['vb'] is None:
1343 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
1344 else:
1345 return ctx['vb'].homeFolder
1346
1347def interpret(ctx):
1348 if ctx['remote']:
1349 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
1350 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
1351
1352 vbox = ctx['vb']
1353
1354 if vbox is not None:
1355 print "Running VirtualBox version %s" %(vbox.version)
1356 ctx['perf'] = ctx['global'].getPerfCollector(vbox)
1357 else:
1358 ctx['perf'] = None
1359
1360 home = getHomeFolder(ctx)
1361 checkUserExtensions(ctx, commands, home)
1362
1363 autoCompletion(commands, ctx)
1364
1365 # to allow to print actual host information, we collect info for
1366 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
1367 if ctx['perf']:
1368 try:
1369 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
1370 except:
1371 pass
1372
1373 while True:
1374 try:
1375 cmd = raw_input("vbox> ")
1376 done = runCommand(ctx, cmd)
1377 if done != 0: break
1378 except KeyboardInterrupt:
1379 print '====== You can type quit or q to leave'
1380 break
1381 except EOFError:
1382 break;
1383 except Exception,e:
1384 print e
1385 if g_verbose:
1386 traceback.print_exc()
1387 ctx['global'].waitForEvents(0)
1388 try:
1389 # There is no need to disable metric collection. This is just an example.
1390 if ct['perf']:
1391 ctx['perf'].disable(['*'], [vbox.host])
1392 except:
1393 pass
1394
1395def runCommandCb(ctx, cmd, args):
1396 args.insert(0, cmd)
1397 return runCommandArgs(ctx, args)
1398
1399def main(argv):
1400 style = None
1401 autopath = False
1402 argv.pop(0)
1403 while len(argv) > 0:
1404 if argv[0] == "-w":
1405 style = "WEBSERVICE"
1406 if argv[0] == "-a":
1407 autopath = True
1408 argv.pop(0)
1409
1410 if autopath:
1411 cwd = os.getcwd()
1412 vpp = os.environ.get("VBOX_PROGRAM_PATH")
1413 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
1414 vpp = cwd
1415 print "Autodetected VBOX_PROGRAM_PATH as",vpp
1416 os.environ["VBOX_PROGRAM_PATH"] = cwd
1417 sys.path.append(os.path.join(vpp, "sdk", "installer"))
1418
1419 from vboxapi import VirtualBoxManager
1420 g_virtualBoxManager = VirtualBoxManager(style, None)
1421 ctx = {'global':g_virtualBoxManager,
1422 'mgr':g_virtualBoxManager.mgr,
1423 'vb':g_virtualBoxManager.vbox,
1424 'ifaces':g_virtualBoxManager.constants,
1425 'remote':g_virtualBoxManager.remote,
1426 'type':g_virtualBoxManager.type,
1427 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1428 'machById': lambda id: machById(ctx,id),
1429 'argsToMach': lambda args: argsToMach(ctx,args),
1430 'progressBar': lambda p: progressBar(ctx,p),
1431 '_machlist':None
1432 }
1433 interpret(ctx)
1434 g_virtualBoxManager.deinit()
1435 del g_virtualBoxManager
1436
1437if __name__ == '__main__':
1438 main(sys.argv)
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette