VirtualBox

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

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

vboxshell: handy function for exts to run command with guest

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 44.4 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.virtualbox.org. 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 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
452 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
453 'save': lambda: progressBar(ctx,console.saveState()),
454 'screenshot': lambda: takeScreenshot(ctx,console,args),
455 'teleport': lambda: teleport(ctx,session,console,args),
456 'gueststats': lambda: guestStats(ctx, console, args),
457 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
458 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
459 }
460 try:
461 ops[cmd]()
462 except Exception, e:
463 print 'failed: ',e
464 if g_verbose:
465 traceback.print_exc()
466
467 session.close()
468
469def machById(ctx,id):
470 mach = None
471 for m in getMachines(ctx):
472 if m.name == id:
473 mach = m
474 break
475 mid = str(m.id)
476 if mid[0] == '{':
477 mid = mid[1:-1]
478 if mid == id:
479 mach = m
480 break
481 return mach
482
483def argsToMach(ctx,args):
484 if len(args) < 2:
485 print "usage: %s [vmname|uuid]" %(args[0])
486 return None
487 id = args[1]
488 m = machById(ctx, id)
489 if m == None:
490 print "Machine '%s' is unknown, use list command to find available machines" %(id)
491 return m
492
493def helpSingleCmd(cmd,h,sp):
494 if sp != 0:
495 spec = " [ext from "+sp+"]"
496 else:
497 spec = ""
498 print " %s: %s%s" %(cmd,h,spec)
499
500def helpCmd(ctx, args):
501 if len(args) == 1:
502 print "Help page:"
503 names = commands.keys()
504 names.sort()
505 for i in names:
506 helpSingleCmd(i, commands[i][0], commands[i][2])
507 else:
508 cmd = args[1]
509 c = commands.get(cmd)
510 if c == None:
511 print "Command '%s' not known" %(cmd)
512 else:
513 helpSingleCmd(cmd, c[0], c[2])
514 return 0
515
516def listCmd(ctx, args):
517 for m in getMachines(ctx, True):
518 if m.teleporterEnabled:
519 tele = "[T] "
520 else:
521 tele = " "
522 print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,m.sessionState)
523 return 0
524
525def getControllerType(type):
526 if type == 0:
527 return "Null"
528 elif type == 1:
529 return "LsiLogic"
530 elif type == 2:
531 return "BusLogic"
532 elif type == 3:
533 return "IntelAhci"
534 elif type == 4:
535 return "PIIX3"
536 elif type == 5:
537 return "PIIX4"
538 elif type == 6:
539 return "ICH6"
540 else:
541 return "Unknown"
542
543def getFirmwareType(type):
544 if type == 0:
545 return "invalid"
546 elif type == 1:
547 return "bios"
548 elif type == 2:
549 return "efi"
550 elif type == 3:
551 return "efi64"
552 elif type == 4:
553 return "efidual"
554 else:
555 return "Unknown"
556
557
558def asEnumElem(ctx,enum,elem):
559 all = ctx['ifaces'].all_values(enum)
560 for e in all.keys():
561 if elem == all[e]:
562 return e
563 return "<unknown>"
564
565def infoCmd(ctx,args):
566 if (len(args) < 2):
567 print "usage: info [vmname|uuid]"
568 return 0
569 mach = argsToMach(ctx,args)
570 if mach == None:
571 return 0
572 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
573 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
574 print " Name [name]: %s" %(mach.name)
575 print " ID [n/a]: %s" %(mach.id)
576 print " OS Type [n/a]: %s" %(os.description)
577 print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
578 print
579 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
580 print " RAM [memorySize]: %dM" %(mach.memorySize)
581 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
582 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
583 print
584 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
585 print " Machine status [n/a]: %d" % (mach.sessionState)
586 print
587 if mach.teleporterEnabled:
588 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
589 print
590 bios = mach.BIOSSettings
591 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
592 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
593 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
594 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
595 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
596 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
597 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
598 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
599
600 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
601 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
602
603 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
604 print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
605
606 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
607 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
608 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
609 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
610
611 controllers = ctx['global'].getArray(mach, 'storageControllers')
612 if controllers:
613 print
614 print " Controllers:"
615 for controller in controllers:
616 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
617
618 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
619 if attaches:
620 print
621 print " Mediums:"
622 for a in attaches:
623 print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
624 m = a.medium
625 if a.type == ctx['global'].constants.DeviceType_HardDisk:
626 print " HDD:"
627 print " Id: %s" %(m.id)
628 print " Location: %s" %(m.location)
629 print " Name: %s" %(m.name)
630 print " Format: %s" %(m.format)
631
632 if a.type == ctx['global'].constants.DeviceType_DVD:
633 print " DVD:"
634 if m:
635 print " Id: %s" %(m.id)
636 print " Name: %s" %(m.name)
637 if m.hostDrive:
638 print " Host DVD %s" %(m.location)
639 if a.passthrough:
640 print " [passthrough mode]"
641 else:
642 print " Virtual image at %s" %(m.location)
643 print " Size: %s" %(m.size)
644
645 if a.type == ctx['global'].constants.DeviceType_Floppy:
646 print " Floppy:"
647 if m:
648 print " Id: %s" %(m.id)
649 print " Name: %s" %(m.name)
650 if m.hostDrive:
651 print " Host floppy %s" %(m.location)
652 else:
653 print " Virtual image at %s" %(m.location)
654 print " Size: %s" %(m.size)
655
656 return 0
657
658def startCmd(ctx, args):
659 mach = argsToMach(ctx,args)
660 if mach == None:
661 return 0
662 if len(args) > 2:
663 type = args[2]
664 else:
665 type = "gui"
666 startVm(ctx, mach, type)
667 return 0
668
669def createCmd(ctx, args):
670 if (len(args) < 3 or len(args) > 4):
671 print "usage: create name ostype <basefolder>"
672 return 0
673 name = args[1]
674 oskind = args[2]
675 if len(args) == 4:
676 base = args[3]
677 else:
678 base = ''
679 try:
680 ctx['vb'].getGuestOSType(oskind)
681 except Exception, e:
682 print 'Unknown OS type:',oskind
683 return 0
684 createVm(ctx, name, oskind, base)
685 return 0
686
687def removeCmd(ctx, args):
688 mach = argsToMach(ctx,args)
689 if mach == None:
690 return 0
691 removeVm(ctx, mach)
692 return 0
693
694def pauseCmd(ctx, args):
695 mach = argsToMach(ctx,args)
696 if mach == None:
697 return 0
698 cmdExistingVm(ctx, mach, 'pause', '')
699 return 0
700
701def powerdownCmd(ctx, args):
702 mach = argsToMach(ctx,args)
703 if mach == None:
704 return 0
705 cmdExistingVm(ctx, mach, 'powerdown', '')
706 return 0
707
708def powerbuttonCmd(ctx, args):
709 mach = argsToMach(ctx,args)
710 if mach == None:
711 return 0
712 cmdExistingVm(ctx, mach, 'powerbutton', '')
713 return 0
714
715def resumeCmd(ctx, args):
716 mach = argsToMach(ctx,args)
717 if mach == None:
718 return 0
719 cmdExistingVm(ctx, mach, 'resume', '')
720 return 0
721
722def saveCmd(ctx, args):
723 mach = argsToMach(ctx,args)
724 if mach == None:
725 return 0
726 cmdExistingVm(ctx, mach, 'save', '')
727 return 0
728
729def statsCmd(ctx, args):
730 mach = argsToMach(ctx,args)
731 if mach == None:
732 return 0
733 cmdExistingVm(ctx, mach, 'stats', '')
734 return 0
735
736def guestCmd(ctx, args):
737 if (len(args) < 3):
738 print "usage: guest name commands"
739 return 0
740 mach = argsToMach(ctx,args)
741 if mach == None:
742 return 0
743 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
744 return 0
745
746def screenshotCmd(ctx, args):
747 if (len(args) < 3):
748 print "usage: screenshot name file <width> <height>"
749 return 0
750 mach = argsToMach(ctx,args)
751 if mach == None:
752 return 0
753 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
754 return 0
755
756def teleportCmd(ctx, args):
757 if (len(args) < 3):
758 print "usage: teleport name host:port <password>"
759 return 0
760 mach = argsToMach(ctx,args)
761 if mach == None:
762 return 0
763 cmdExistingVm(ctx, mach, 'teleport', args[2:])
764 return 0
765
766def openportalCmd(ctx, args):
767 if (len(args) < 3):
768 print "usage: openportal name port <password>"
769 return 0
770 mach = argsToMach(ctx,args)
771 if mach == None:
772 return 0
773 port = int(args[2])
774 if (len(args) > 3):
775 passwd = args[3]
776 else:
777 passwd = ""
778 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
779 session = ctx['global'].openMachineSession(mach.id)
780 mach1 = session.machine
781 mach1.teleporterEnabled = True
782 mach1.teleporterPort = port
783 mach1.teleporterPassword = passwd
784 mach1.saveSettings()
785 session.close()
786 startVm(ctx, mach, "gui")
787 return 0
788
789def closeportalCmd(ctx, args):
790 if (len(args) < 2):
791 print "usage: closeportal name"
792 return 0
793 mach = argsToMach(ctx,args)
794 if mach == None:
795 return 0
796 if mach.teleporterEnabled:
797 session = ctx['global'].openMachineSession(mach.id)
798 mach1 = session.machine
799 mach1.teleporterEnabled = False
800 mach1.saveSettings()
801 session.close()
802 return 0
803
804def gueststatsCmd(ctx, args):
805 if (len(args) < 2):
806 print "usage: gueststats name <check interval>"
807 return 0
808 mach = argsToMach(ctx,args)
809 if mach == None:
810 return 0
811 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
812 return 0
813
814def plugcpuCmd(ctx, args):
815 if (len(args) < 2):
816 print "usage: plugcpu name cpuid"
817 return 0
818 mach = argsToMach(ctx,args)
819 if mach == None:
820 return 0
821 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
822 if mach.CPUHotPlugEnabled:
823 session = ctx['global'].openMachineSession(mach.id)
824 try:
825 mach1 = session.machine
826 cpu = int(args[2])
827 print "Adding CPU %d..." %(cpu)
828 mach1.hotPlugCPU(cpu)
829 mach1.saveSettings()
830 except:
831 session.close()
832 raise
833 session.close()
834 else:
835 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
836 return 0
837
838def unplugcpuCmd(ctx, args):
839 if (len(args) < 2):
840 print "usage: unplugcpu name cpuid"
841 return 0
842 mach = argsToMach(ctx,args)
843 if mach == None:
844 return 0
845 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
846 if mach.CPUHotPlugEnabled:
847 session = ctx['global'].openMachineSession(mach.id)
848 try:
849 mach1 = session.machine
850 cpu = int(args[2])
851 print "Removing CPU %d..." %(cpu)
852 mach1.hotUnplugCPU(cpu)
853 mach1.saveSettings()
854 except:
855 session.close()
856 raise
857 session.close()
858 else:
859 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
860 return 0
861
862def setvarCmd(ctx, args):
863 if (len(args) < 4):
864 print "usage: setvar [vmname|uuid] expr value"
865 return 0
866 mach = argsToMach(ctx,args)
867 if mach == None:
868 return 0
869 session = ctx['global'].openMachineSession(mach.id)
870 mach = session.machine
871 expr = 'mach.'+args[2]+' = '+args[3]
872 print "Executing",expr
873 try:
874 exec expr
875 except Exception, e:
876 print 'failed: ',e
877 if g_verbose:
878 traceback.print_exc()
879 mach.saveSettings()
880 session.close()
881 return 0
882
883
884def setExtraDataCmd(ctx, args):
885 if (len(args) < 3):
886 print "usage: setextra [vmname|uuid|global] key <value>"
887 return 0
888 key = args[2]
889 if len(args) == 4:
890 value = args[3]
891 else:
892 value = None
893 if args[1] == 'global':
894 ctx['vb'].setExtraData(key, value)
895 return 0
896
897 mach = argsToMach(ctx,args)
898 if mach == None:
899 return 0
900 session = ctx['global'].openMachineSession(mach.id)
901 mach = session.machine
902 mach.setExtraData(key, value)
903 mach.saveSettings()
904 session.close()
905 return 0
906
907def printExtraKey(obj, key, value):
908 print "%s: '%s' = '%s'" %(obj, key, value)
909
910def getExtraDataCmd(ctx, args):
911 if (len(args) < 2):
912 print "usage: getextra [vmname|uuid|global] <key>"
913 return 0
914 if len(args) == 3:
915 key = args[2]
916 else:
917 key = None
918
919 if args[1] == 'global':
920 obj = ctx['vb']
921 else:
922 obj = argsToMach(ctx,args)
923 if obj == None:
924 return 0
925
926 if key == None:
927 keys = obj.getExtraDataKeys()
928 else:
929 keys = [ key ]
930 for k in keys:
931 printExtraKey(args[1], k, ctx['vb'].getExtraData(k))
932
933 return 0
934
935def quitCmd(ctx, args):
936 return 1
937
938def aliasCmd(ctx, args):
939 if (len(args) == 3):
940 aliases[args[1]] = args[2]
941 return 0
942
943 for (k,v) in aliases.items():
944 print "'%s' is an alias for '%s'" %(k,v)
945 return 0
946
947def verboseCmd(ctx, args):
948 global g_verbose
949 g_verbose = not g_verbose
950 return 0
951
952def getUSBStateString(state):
953 if state == 0:
954 return "NotSupported"
955 elif state == 1:
956 return "Unavailable"
957 elif state == 2:
958 return "Busy"
959 elif state == 3:
960 return "Available"
961 elif state == 4:
962 return "Held"
963 elif state == 5:
964 return "Captured"
965 else:
966 return "Unknown"
967
968def hostCmd(ctx, args):
969 host = ctx['vb'].host
970 cnt = host.processorCount
971 print "Processor count:",cnt
972 for i in range(0,cnt):
973 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
974
975 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
976 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
977 if host.Acceleration3DAvailable:
978 print "3D acceleration available"
979 else:
980 print "3D acceleration NOT available"
981
982 print "Network interfaces:"
983 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
984 print " %s (%s)" %(ni.name, ni.IPAddress)
985
986 print "DVD drives:"
987 for dd in ctx['global'].getArray(host, 'DVDDrives'):
988 print " %s - %s" %(dd.name, dd.description)
989
990 print "USB devices:"
991 for ud in ctx['global'].getArray(host, 'USBDevices'):
992 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
993
994 if ctx['perf']:
995 for metric in ctx['perf'].query(["*"], [host]):
996 print metric['name'], metric['values_as_string']
997
998 return 0
999
1000def monitorGuestCmd(ctx, args):
1001 if (len(args) < 2):
1002 print "usage: monitorGuest name (duration)"
1003 return 0
1004 mach = argsToMach(ctx,args)
1005 if mach == None:
1006 return 0
1007 dur = 5
1008 if len(args) > 2:
1009 dur = float(args[2])
1010 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1011 return 0
1012
1013def monitorVBoxCmd(ctx, args):
1014 if (len(args) > 2):
1015 print "usage: monitorVBox (duration)"
1016 return 0
1017 dur = 5
1018 if len(args) > 1:
1019 dur = float(args[1])
1020 monitorVBox(ctx, dur)
1021 return 0
1022
1023def getAdapterType(ctx, type):
1024 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1025 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1026 return "pcnet"
1027 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1028 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1029 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1030 return "e1000"
1031 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1032 return "virtio"
1033 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1034 return None
1035 else:
1036 raise Exception("Unknown adapter type: "+type)
1037
1038
1039def portForwardCmd(ctx, args):
1040 if (len(args) != 5):
1041 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1042 return 0
1043 mach = argsToMach(ctx,args)
1044 if mach == None:
1045 return 0
1046 adapterNum = int(args[2])
1047 hostPort = int(args[3])
1048 guestPort = int(args[4])
1049 proto = "TCP"
1050 session = ctx['global'].openMachineSession(mach.id)
1051 mach = session.machine
1052
1053 adapter = mach.getNetworkAdapter(adapterNum)
1054 adapterType = getAdapterType(ctx, adapter.adapterType)
1055
1056 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1057 config = "VBoxInternal/Devices/" + adapterType + "/"
1058 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1059
1060 mach.setExtraData(config + "/Protocol", proto)
1061 mach.setExtraData(config + "/HostPort", str(hostPort))
1062 mach.setExtraData(config + "/GuestPort", str(guestPort))
1063
1064 mach.saveSettings()
1065 session.close()
1066
1067 return 0
1068
1069
1070def showLogCmd(ctx, args):
1071 if (len(args) < 2):
1072 print "usage: showLog <vm> <num>"
1073 return 0
1074 mach = argsToMach(ctx,args)
1075 if mach == None:
1076 return 0
1077
1078 log = "VBox.log"
1079 if (len(args) > 2):
1080 log += "."+args[2]
1081 fileName = os.path.join(mach.logFolder, log)
1082
1083 try:
1084 lf = open(fileName, 'r')
1085 except IOError,e:
1086 print "cannot open: ",e
1087 return 0
1088
1089 for line in lf:
1090 print line,
1091 lf.close()
1092
1093 return 0
1094
1095def evalCmd(ctx, args):
1096 expr = ' '.join(args[1:])
1097 try:
1098 exec expr
1099 except Exception, e:
1100 print 'failed: ',e
1101 if g_verbose:
1102 traceback.print_exc()
1103 return 0
1104
1105def reloadExtCmd(ctx, args):
1106 # maybe will want more args smartness
1107 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1108 autoCompletion(commands, ctx)
1109 return 0
1110
1111
1112def runScriptCmd(ctx, args):
1113 if (len(args) != 2):
1114 print "usage: runScript <script>"
1115 return 0
1116 try:
1117 lf = open(args[1], 'r')
1118 except IOError,e:
1119 print "cannot open:",args[1], ":",e
1120 return 0
1121
1122 try:
1123 for line in lf:
1124 done = runCommand(ctx, line)
1125 if done != 0: break
1126 except Exception,e:
1127 print "error:",e
1128 if g_verbose:
1129 traceback.print_exc()
1130 lf.close()
1131 return 0
1132
1133def sleepCmd(ctx, args):
1134 if (len(args) != 2):
1135 print "usage: sleep <secs>"
1136 return 0
1137
1138 try:
1139 time.sleep(float(args[1]))
1140 except:
1141 # to allow sleep interrupt
1142 pass
1143 return 0
1144
1145
1146def shellCmd(ctx, args):
1147 if (len(args) < 2):
1148 print "usage: shell <commands>"
1149 return 0
1150 cmd = ' '.join(args[1:])
1151 try:
1152 os.system(cmd)
1153 except KeyboardInterrupt:
1154 # to allow shell command interruption
1155 pass
1156 return 0
1157
1158
1159def connectCmd(ctx, args):
1160 if (len(args) > 4):
1161 print "usage: connect [url] [username] [passwd]"
1162 return 0
1163
1164 if ctx['vb'] is not None:
1165 print "Already connected, disconnect first..."
1166 return 0
1167
1168 if (len(args) > 1):
1169 url = args[1]
1170 else:
1171 url = None
1172
1173 if (len(args) > 2):
1174 user = args[2]
1175 else:
1176 user = ""
1177
1178 if (len(args) > 3):
1179 passwd = args[3]
1180 else:
1181 passwd = ""
1182
1183 vbox = ctx['global'].platform.connect(url, user, passwd)
1184 ctx['vb'] = vbox
1185 print "Running VirtualBox version %s" %(vbox.version)
1186 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1187 return 0
1188
1189def disconnectCmd(ctx, args):
1190 if (len(args) != 1):
1191 print "usage: disconnect"
1192 return 0
1193
1194 if ctx['vb'] is None:
1195 print "Not connected yet."
1196 return 0
1197
1198 try:
1199 ctx['global'].platform.disconnect()
1200 except:
1201 ctx['vb'] = None
1202 raise
1203
1204 ctx['vb'] = None
1205 return 0
1206
1207def exportVMCmd(ctx, args):
1208 import sys
1209
1210 if len(args) < 3:
1211 print "usage: exportVm <machine> <path> <format> <license>"
1212 return 0
1213 mach = ctx['machById'](args[1])
1214 if mach is None:
1215 return 0
1216 path = args[2]
1217 if (len(args) > 3):
1218 format = args[3]
1219 else:
1220 format = "ovf-1.0"
1221 if (len(args) > 4):
1222 license = args[4]
1223 else:
1224 license = "GPL"
1225
1226 app = ctx['vb'].createAppliance()
1227 desc = mach.export(app)
1228 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1229 p = app.write(format, path)
1230 progressBar(ctx, p)
1231 print "Exported to %s in format %s" %(path, format)
1232 return 0
1233
1234aliases = {'s':'start',
1235 'i':'info',
1236 'l':'list',
1237 'h':'help',
1238 'a':'alias',
1239 'q':'quit', 'exit':'quit',
1240 'v':'verbose'}
1241
1242commands = {'help':['Prints help information', helpCmd, 0],
1243 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
1244 'create':['Create virtual machine', createCmd, 0],
1245 'remove':['Remove virtual machine', removeCmd, 0],
1246 'pause':['Pause virtual machine', pauseCmd, 0],
1247 'resume':['Resume virtual machine', resumeCmd, 0],
1248 'save':['Save execution state of virtual machine', saveCmd, 0],
1249 'stats':['Stats for virtual machine', statsCmd, 0],
1250 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1251 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1252 'list':['Shows known virtual machines', listCmd, 0],
1253 'info':['Shows info on machine', infoCmd, 0],
1254 'alias':['Control aliases', aliasCmd, 0],
1255 'verbose':['Toggle verbosity', verboseCmd, 0],
1256 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1257 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1258 'quit':['Exits', quitCmd, 0],
1259 'host':['Show host information', hostCmd, 0],
1260 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
1261 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1262 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1263 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1264 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1265 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1266 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1267 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1268 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1269 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
1270 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1271 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
1272 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
1273 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
1274 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
1275 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
1276 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
1277 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
1278 'unplugcpu':['Remove a CPU from a running VM: plugcpu Win 1', unplugcpuCmd, 0],
1279 }
1280
1281def runCommandArgs(ctx, args):
1282 c = args[0]
1283 if aliases.get(c, None) != None:
1284 c = aliases[c]
1285 ci = commands.get(c,None)
1286 if ci == None:
1287 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
1288 return 0
1289 return ci[1](ctx, args)
1290
1291
1292def runCommand(ctx, cmd):
1293 if len(cmd) == 0: return 0
1294 args = split_no_quotes(cmd)
1295 if len(args) == 0: return 0
1296 return runCommandArgs(ctx, args)
1297
1298#
1299# To write your own custom commands to vboxshell, create
1300# file ~/.VirtualBox/shellext.py with content like
1301#
1302# def runTestCmd(ctx, args):
1303# print "Testy test", ctx['vb']
1304# return 0
1305#
1306# commands = {
1307# 'test': ['Test help', runTestCmd]
1308# }
1309# and issue reloadExt shell command.
1310# This file also will be read automatically on startup or 'reloadExt'.
1311#
1312# Also one can put shell extensions into ~/.VirtualBox/shexts and
1313# they will also be picked up, so this way one can exchange
1314# shell extensions easily.
1315def addExtsFromFile(ctx, cmds, file):
1316 if not os.path.isfile(file):
1317 return
1318 d = {}
1319 try:
1320 execfile(file, d, d)
1321 for (k,v) in d['commands'].items():
1322 if g_verbose:
1323 print "customize: adding \"%s\" - %s" %(k, v[0])
1324 cmds[k] = [v[0], v[1], file]
1325 except:
1326 print "Error loading user extensions from %s" %(file)
1327 traceback.print_exc()
1328
1329
1330def checkUserExtensions(ctx, cmds, folder):
1331 folder = str(folder)
1332 name = os.path.join(folder, "shellext.py")
1333 addExtsFromFile(ctx, cmds, name)
1334 # also check 'exts' directory for all files
1335 shextdir = os.path.join(folder, "shexts")
1336 if not os.path.isdir(shextdir):
1337 return
1338 exts = os.listdir(shextdir)
1339 for e in exts:
1340 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
1341
1342def getHomeFolder(ctx):
1343 if ctx['remote'] or ctx['vb'] is None:
1344 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
1345 else:
1346 return ctx['vb'].homeFolder
1347
1348def interpret(ctx):
1349 if ctx['remote']:
1350 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
1351 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
1352
1353 vbox = ctx['vb']
1354
1355 if vbox is not None:
1356 print "Running VirtualBox version %s" %(vbox.version)
1357 ctx['perf'] = ctx['global'].getPerfCollector(vbox)
1358 else:
1359 ctx['perf'] = None
1360
1361 home = getHomeFolder(ctx)
1362 checkUserExtensions(ctx, commands, home)
1363
1364 autoCompletion(commands, ctx)
1365
1366 # to allow to print actual host information, we collect info for
1367 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
1368 if ctx['perf']:
1369 try:
1370 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
1371 except:
1372 pass
1373
1374 while True:
1375 try:
1376 cmd = raw_input("vbox> ")
1377 done = runCommand(ctx, cmd)
1378 if done != 0: break
1379 except KeyboardInterrupt:
1380 print '====== You can type quit or q to leave'
1381 break
1382 except EOFError:
1383 break;
1384 except Exception,e:
1385 print e
1386 if g_verbose:
1387 traceback.print_exc()
1388 ctx['global'].waitForEvents(0)
1389 try:
1390 # There is no need to disable metric collection. This is just an example.
1391 if ct['perf']:
1392 ctx['perf'].disable(['*'], [vbox.host])
1393 except:
1394 pass
1395
1396def runCommandCb(ctx, cmd, args):
1397 args.insert(0, cmd)
1398 return runCommandArgs(ctx, args)
1399
1400def runGuestCommandCb(ctx, id, guestLambda, args):
1401 mach = machById(ctx,id)
1402 if mach == None:
1403 return 0
1404 args.insert(0, guestLambda)
1405 cmdExistingVm(ctx, mach, 'guestlambda', args)
1406 return 0
1407
1408def main(argv):
1409 style = None
1410 autopath = False
1411 argv.pop(0)
1412 while len(argv) > 0:
1413 if argv[0] == "-w":
1414 style = "WEBSERVICE"
1415 if argv[0] == "-a":
1416 autopath = True
1417 argv.pop(0)
1418
1419 if autopath:
1420 cwd = os.getcwd()
1421 vpp = os.environ.get("VBOX_PROGRAM_PATH")
1422 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
1423 vpp = cwd
1424 print "Autodetected VBOX_PROGRAM_PATH as",vpp
1425 os.environ["VBOX_PROGRAM_PATH"] = cwd
1426 sys.path.append(os.path.join(vpp, "sdk", "installer"))
1427
1428 from vboxapi import VirtualBoxManager
1429 g_virtualBoxManager = VirtualBoxManager(style, None)
1430 ctx = {'global':g_virtualBoxManager,
1431 'mgr':g_virtualBoxManager.mgr,
1432 'vb':g_virtualBoxManager.vbox,
1433 'ifaces':g_virtualBoxManager.constants,
1434 'remote':g_virtualBoxManager.remote,
1435 'type':g_virtualBoxManager.type,
1436 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1437 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
1438 'machById': lambda id: machById(ctx,id),
1439 'argsToMach': lambda args: argsToMach(ctx,args),
1440 'progressBar': lambda p: progressBar(ctx,p),
1441 '_machlist':None
1442 }
1443 interpret(ctx)
1444 g_virtualBoxManager.deinit()
1445 del g_virtualBoxManager
1446
1447if __name__ == '__main__':
1448 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