VirtualBox

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

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

vbox shell: usb control, cancellation

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.8 KB
Line 
1#!/usr/bin/python
2#
3# Copyright (C) 2009-2010 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, supports TAB-completion and #
23# history if you have Python readline installed. #
24# #
25# Finally, shell allows arbitrary custom extensions, just create #
26# .VirtualBox/shexts/ and drop your extensions there. #
27# Enjoy. #
28################################################################################
29
30import os,sys
31import traceback
32import shlex
33import time
34import re
35
36HISTORY_FILENAME=os.path.join(os.environ["HOME"], ".vboxshell_history")
37
38# Simple implementation of IConsoleCallback, one can use it as skeleton
39# for custom implementations
40class GuestMonitor:
41 def __init__(self, mach):
42 self.mach = mach
43
44 def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
45 print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
46 def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
47 print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, needsHostCursor)
48
49 def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
50 print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
51
52 def onStateChange(self, state):
53 print "%s: onStateChange state=%d" %(self.mach.name, state)
54
55 def onAdditionsStateChange(self):
56 print "%s: onAdditionsStateChange" %(self.mach.name)
57
58 def onNetworkAdapterChange(self, adapter):
59 print "%s: onNetworkAdapterChange" %(self.mach.name)
60
61 def onSerialPortChange(self, port):
62 print "%s: onSerialPortChange" %(self.mach.name)
63
64 def onParallelPortChange(self, port):
65 print "%s: onParallelPortChange" %(self.mach.name)
66
67 def onStorageControllerChange(self):
68 print "%s: onStorageControllerChange" %(self.mach.name)
69
70 def onMediumChange(self, attachment):
71 print "%s: onMediumChange" %(self.mach.name)
72
73 def onVRDPServerChange(self):
74 print "%s: onVRDPServerChange" %(self.mach.name)
75
76 def onUSBControllerChange(self):
77 print "%s: onUSBControllerChange" %(self.mach.name)
78
79 def onUSBDeviceStateChange(self, device, attached, error):
80 print "%s: onUSBDeviceStateChange" %(self.mach.name)
81
82 def onSharedFolderChange(self, scope):
83 print "%s: onSharedFolderChange" %(self.mach.name)
84
85 def onRuntimeError(self, fatal, id, message):
86 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
87
88 def onCanShowWindow(self):
89 print "%s: onCanShowWindow" %(self.mach.name)
90 return True
91
92 def onShowWindow(self, winId):
93 print "%s: onShowWindow: %d" %(self.mach.name, winId)
94
95class VBoxMonitor:
96 def __init__(self, params):
97 self.vbox = params[0]
98 self.isMscom = params[1]
99 pass
100
101 def onMachineStateChange(self, id, state):
102 print "onMachineStateChange: %s %d" %(id, state)
103
104 def onMachineDataChange(self,id):
105 print "onMachineDataChange: %s" %(id)
106
107 def onExtraDataCanChange(self, id, key, value):
108 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
109 # Witty COM bridge thinks if someone wishes to return tuple, hresult
110 # is one of values we want to return
111 if self.isMscom:
112 return "", 0, True
113 else:
114 return True, ""
115
116 def onExtraDataChange(self, id, key, value):
117 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
118
119 def onMediaRegistered(self, id, type, registered):
120 print "onMediaRegistered: %s" %(id)
121
122 def onMachineRegistered(self, id, registred):
123 print "onMachineRegistered: %s" %(id)
124
125 def onSessionStateChange(self, id, state):
126 print "onSessionStateChange: %s %d" %(id, state)
127
128 def onSnapshotTaken(self, mach, id):
129 print "onSnapshotTaken: %s %s" %(mach, id)
130
131 def onSnapshotDeleted(self, mach, id):
132 print "onSnapshotDeleted: %s %s" %(mach, id)
133
134 def onSnapshotChange(self, mach, id):
135 print "onSnapshotChange: %s %s" %(mach, id)
136
137 def onGuestPropertyChange(self, id, name, newValue, flags):
138 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
139
140g_hasreadline = 1
141try:
142 import readline
143 import rlcompleter
144except:
145 g_hasreadline = 0
146
147
148if g_hasreadline:
149 class CompleterNG(rlcompleter.Completer):
150 def __init__(self, dic, ctx):
151 self.ctx = ctx
152 return rlcompleter.Completer.__init__(self,dic)
153
154 def complete(self, text, state):
155 """
156 taken from:
157 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
158 """
159 if text == "":
160 return ['\t',None][state]
161 else:
162 return rlcompleter.Completer.complete(self,text,state)
163
164 def global_matches(self, text):
165 """
166 Compute matches when text is a simple name.
167 Return a list of all names currently defined
168 in self.namespace that match.
169 """
170
171 matches = []
172 n = len(text)
173
174 for list in [ self.namespace ]:
175 for word in list:
176 if word[:n] == text:
177 matches.append(word)
178
179
180 try:
181 for m in getMachines(self.ctx):
182 # although it has autoconversion, we need to cast
183 # explicitly for subscripts to work
184 word = re.sub("(?<!\\\\) ", "\\ ", str(m.name))
185 if word[:n] == text:
186 matches.append(word)
187 word = str(m.id)
188 if word[0] == '{':
189 word = word[1:-1]
190 if word[:n] == text:
191 matches.append(word)
192 except Exception,e:
193 traceback.print_exc()
194 print e
195
196 return matches
197
198def autoCompletion(commands, ctx):
199 import platform
200 if not g_hasreadline:
201 return
202
203 comps = {}
204 for (k,v) in commands.items():
205 comps[k] = None
206 completer = CompleterNG(comps, ctx)
207 readline.set_completer(completer.complete)
208 delims = readline.get_completer_delims()
209 readline.set_completer_delims(re.sub("[\\.]", "", delims)) # remove some of the delimiters
210 # OSX need it
211 if platform.system() == 'Darwin':
212 readline.parse_and_bind ("bind ^I rl_complete")
213 readline.parse_and_bind("tab: complete")
214
215g_verbose = True
216
217def split_no_quotes(s):
218 return shlex.split(s)
219
220def progressBar(ctx,p,wait=1000):
221 try:
222 while not p.completed:
223 print "%d %%\r" %(p.percent),
224 sys.stdout.flush()
225 p.waitForCompletion(wait)
226 ctx['global'].waitForEvents(0)
227 return 0
228 except KeyboardInterrupt:
229 print "Interrupted."
230 if p.cancelable:
231 print "Canceling task..."
232 p.cancel()
233 return 1
234
235
236
237def reportError(ctx,session,rc):
238 if not ctx['remote']:
239 print session.QueryErrorObject(rc)
240
241
242def createVm(ctx,name,kind,base):
243 mgr = ctx['mgr']
244 vb = ctx['vb']
245 mach = vb.createMachine(name, kind, base, "", False)
246 mach.saveSettings()
247 print "created machine with UUID",mach.id
248 vb.registerMachine(mach)
249 # update cache
250 getMachines(ctx, True)
251
252def removeVm(ctx,mach):
253 mgr = ctx['mgr']
254 vb = ctx['vb']
255 id = mach.id
256 print "removing machine ",mach.name,"with UUID",id
257 cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
258 mach = vb.unregisterMachine(id)
259 if mach:
260 mach.deleteSettings()
261 # update cache
262 getMachines(ctx, True)
263
264def startVm(ctx,mach,type):
265 mgr = ctx['mgr']
266 vb = ctx['vb']
267 perf = ctx['perf']
268 session = mgr.getSessionObject(vb)
269 uuid = mach.id
270 progress = vb.openRemoteSession(session, uuid, type, "")
271 progressBar(ctx, progress, 100)
272 completed = progress.completed
273 rc = int(progress.resultCode)
274 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
275 if rc == 0:
276 # we ignore exceptions to allow starting VM even if
277 # perf collector cannot be started
278 if perf:
279 try:
280 perf.setup(['*'], [mach], 10, 15)
281 except Exception,e:
282 print e
283 if g_verbose:
284 traceback.print_exc()
285 # if session not opened, close doesn't make sense
286 session.close()
287 else:
288 reportError(ctx,session,rc)
289
290def getMachines(ctx, invalidate = False):
291 if ctx['vb'] is not None:
292 if ctx['_machlist'] is None or invalidate:
293 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
294 return ctx['_machlist']
295 else:
296 return []
297
298def asState(var):
299 if var:
300 return 'on'
301 else:
302 return 'off'
303
304def asFlag(var):
305 if var:
306 return 'yes'
307 else:
308 return 'no'
309
310def perfStats(ctx,mach):
311 if not ctx['perf']:
312 return
313 for metric in ctx['perf'].query(["*"], [mach]):
314 print metric['name'], metric['values_as_string']
315
316def guestExec(ctx, machine, console, cmds):
317 exec cmds
318
319def monitorGuest(ctx, machine, console, dur):
320 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
321 console.registerCallback(cb)
322 if dur == -1:
323 # not infinity, but close enough
324 dur = 100000
325 try:
326 end = time.time() + dur
327 while time.time() < end:
328 ctx['global'].waitForEvents(500)
329 # We need to catch all exceptions here, otherwise callback will never be unregistered
330 except:
331 pass
332 console.unregisterCallback(cb)
333
334
335def monitorVBox(ctx, dur):
336 vbox = ctx['vb']
337 isMscom = (ctx['global'].type == 'MSCOM')
338 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
339 vbox.registerCallback(cb)
340 if dur == -1:
341 # not infinity, but close enough
342 dur = 100000
343 try:
344 end = time.time() + dur
345 while time.time() < end:
346 ctx['global'].waitForEvents(500)
347 # We need to catch all exceptions here, otherwise callback will never be unregistered
348 except:
349 pass
350 vbox.unregisterCallback(cb)
351
352
353def takeScreenshot(ctx,console,args):
354 from PIL import Image
355 display = console.display
356 if len(args) > 0:
357 f = args[0]
358 else:
359 f = "/tmp/screenshot.png"
360 if len(args) > 3:
361 screen = int(args[3])
362 else:
363 screen = 0
364 (fb,xorig,yorig) = display.getFramebuffer(screen)
365 if len(args) > 1:
366 w = int(args[1])
367 else:
368 w = fb.width
369 if len(args) > 2:
370 h = int(args[2])
371 else:
372 h = fb.height
373
374 print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
375 data = display.takeScreenShotToArray(screen, w,h)
376 size = (w,h)
377 mode = "RGBA"
378 im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
379 im.save(f, "PNG")
380
381
382def teleport(ctx,session,console,args):
383 if args[0].find(":") == -1:
384 print "Use host:port format for teleport target"
385 return
386 (host,port) = args[0].split(":")
387 if len(args) > 1:
388 passwd = args[1]
389 else:
390 passwd = ""
391
392 if len(args) > 2:
393 maxDowntime = int(args[2])
394 else:
395 maxDowntime = 250
396
397 port = int(port)
398 print "Teleporting to %s:%d..." %(host,port)
399 progress = console.teleport(host, port, passwd, maxDowntime)
400 progressBar(ctx, progress, 100)
401 completed = progress.completed
402 rc = int(progress.resultCode)
403 if rc == 0:
404 print "Success!"
405 else:
406 reportError(ctx,session,rc)
407
408
409def guestStats(ctx,console,args):
410 guest = console.guest
411 # we need to set up guest statistics
412 if len(args) > 0 :
413 update = args[0]
414 else:
415 update = 1
416 if guest.statisticsUpdateInterval != update:
417 guest.statisticsUpdateInterval = update
418 try:
419 time.sleep(float(update)+0.1)
420 except:
421 # to allow sleep interruption
422 pass
423 all_stats = ctx['ifaces'].all_values('GuestStatisticType')
424 cpu = 0
425 for s in all_stats.keys():
426 try:
427 val = guest.getStatistic( cpu, all_stats[s])
428 print "%s: %d" %(s, val)
429 except:
430 # likely not implemented
431 pass
432
433def plugCpu(ctx,machine,session,args):
434 cpu = int(args[0])
435 print "Adding CPU %d..." %(cpu)
436 machine.hotPlugCPU(cpu)
437
438def unplugCpu(ctx,machine,session,args):
439 cpu = int(args[0])
440 print "Removing CPU %d..." %(cpu)
441 machine.hotUnplugCPU(cpu)
442
443def mountIso(ctx,machine,session,args):
444 machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
445 machine.saveSettings()
446
447def cond(c,v1,v2):
448 if c:
449 return v1
450 else:
451 return v2
452
453def printHostUsbDev(ctx,ud):
454 print " %s: %s (vendorId=%d productId=%d serial=%s) %s" %(ud.id, ud.product, ud.vendorId, ud.productId, ud.serialNumber,getUSBStateString(ud.state))
455
456def printUsbDev(ctx,ud):
457 print " %s: %s (vendorId=%d productId=%d serial=%s)" %(ud.id, ud.product, ud.vendorId, ud.productId, ud.serialNumber)
458
459def printSf(ctx,sf):
460 print "name=%s host=%s %s %s" %(sf.name, sf.hostPath, cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))
461
462def ginfo(ctx,console, args):
463 guest = console.guest
464 if guest.additionsActive:
465 vers = int(guest.additionsVersion)
466 print "Additions active, version %d.%d" %(vers >> 16, vers & 0xffff)
467 print "Support seamless: %s" %(asFlag(guest.supportsSeamless))
468 print "Support graphics: %s" %(asFlag(guest.supportsGraphics))
469 print "Baloon size: %d" %(guest.memoryBalloonSize)
470 print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
471 else:
472 print "No additions"
473 usbs = ctx['global'].getArray(console, 'USBDevices')
474 print "Attached USB:"
475 for ud in usbs:
476 printUsbDev(ctx,ud)
477 rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
478 print "Remote USB:"
479 for ud in rusbs:
480 printHostUsbDev(ctx,ud)
481 print "Transient shared folders:"
482 sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
483 for sf in sfs:
484 printSf(ctx,sf)
485
486def cmdExistingVm(ctx,mach,cmd,args):
487 mgr=ctx['mgr']
488 vb=ctx['vb']
489 session = mgr.getSessionObject(vb)
490 uuid = mach.id
491 try:
492 progress = vb.openExistingSession(session, uuid)
493 except Exception,e:
494 print "Session to '%s' not open: %s" %(mach.name,e)
495 if g_verbose:
496 traceback.print_exc()
497 return
498 if str(session.state) != str(ctx['ifaces'].SessionState_Open):
499 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
500 return
501 # this could be an example how to handle local only (i.e. unavailable
502 # in Webservices) functionality
503 if ctx['remote'] and cmd == 'some_local_only_command':
504 print 'Trying to use local only functionality, ignored'
505 return
506 console=session.console
507 ops={'pause': lambda: console.pause(),
508 'resume': lambda: console.resume(),
509 'powerdown': lambda: console.powerDown(),
510 'powerbutton': lambda: console.powerButton(),
511 'stats': lambda: perfStats(ctx, mach),
512 'guest': lambda: guestExec(ctx, mach, console, args),
513 'ginfo': lambda: ginfo(ctx, console, args),
514 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
515 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
516 'save': lambda: progressBar(ctx,console.saveState()),
517 'screenshot': lambda: takeScreenshot(ctx,console,args),
518 'teleport': lambda: teleport(ctx,session,console,args),
519 'gueststats': lambda: guestStats(ctx, console, args),
520 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
521 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
522 'mountiso': lambda: mountIso(ctx, session.machine, session, args),
523 }
524 try:
525 ops[cmd]()
526 except Exception, e:
527 print 'failed: ',e
528 if g_verbose:
529 traceback.print_exc()
530
531 session.close()
532
533
534def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
535 session = ctx['global'].openMachineSession(mach.id)
536 mach = session.machine
537 try:
538 cmd(ctx, mach, args)
539 except Exception, e:
540 print 'failed: ',e
541 if g_verbose:
542 traceback.print_exc()
543 if save:
544 mach.saveSettings()
545 session.close()
546
547def machById(ctx,id):
548 mach = None
549 for m in getMachines(ctx):
550 if m.name == id:
551 mach = m
552 break
553 mid = str(m.id)
554 if mid[0] == '{':
555 mid = mid[1:-1]
556 if mid == id:
557 mach = m
558 break
559 return mach
560
561def argsToMach(ctx,args):
562 if len(args) < 2:
563 print "usage: %s [vmname|uuid]" %(args[0])
564 return None
565 id = args[1]
566 m = machById(ctx, id)
567 if m == None:
568 print "Machine '%s' is unknown, use list command to find available machines" %(id)
569 return m
570
571def helpSingleCmd(cmd,h,sp):
572 if sp != 0:
573 spec = " [ext from "+sp+"]"
574 else:
575 spec = ""
576 print " %s: %s%s" %(cmd,h,spec)
577
578def helpCmd(ctx, args):
579 if len(args) == 1:
580 print "Help page:"
581 names = commands.keys()
582 names.sort()
583 for i in names:
584 helpSingleCmd(i, commands[i][0], commands[i][2])
585 else:
586 cmd = args[1]
587 c = commands.get(cmd)
588 if c == None:
589 print "Command '%s' not known" %(cmd)
590 else:
591 helpSingleCmd(cmd, c[0], c[2])
592 return 0
593
594def asEnumElem(ctx,enum,elem):
595 all = ctx['ifaces'].all_values(enum)
596 for e in all.keys():
597 if str(elem) == str(all[e]):
598 return e
599 return "<unknown>"
600
601def enumFromString(ctx,enum,str):
602 all = ctx['ifaces'].all_values(enum)
603 return all.get(str, None)
604
605def listCmd(ctx, args):
606 for m in getMachines(ctx, True):
607 if m.teleporterEnabled:
608 tele = "[T] "
609 else:
610 tele = " "
611 print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,asEnumElem(ctx,"SessionState", m.sessionState))
612 return 0
613
614def infoCmd(ctx,args):
615 if (len(args) < 2):
616 print "usage: info [vmname|uuid]"
617 return 0
618 mach = argsToMach(ctx,args)
619 if mach == None:
620 return 0
621 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
622 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
623 print " Name [name]: %s" %(mach.name)
624 print " Description [description]: %s" %(mach.description)
625 print " ID [n/a]: %s" %(mach.id)
626 print " OS Type [via OSTypeId]: %s" %(os.description)
627 print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
628 print
629 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
630 print " RAM [memorySize]: %dM" %(mach.memorySize)
631 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
632 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
633 print
634 print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
635 print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
636 print
637 if mach.teleporterEnabled:
638 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
639 print
640 bios = mach.BIOSSettings
641 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
642 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
643 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
644 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
645 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
646 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
647 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
648 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
649
650 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
651 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
652
653 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
654 if mach.audioAdapter.enabled:
655 print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
656 if mach.USBController.enabled:
657 print " USB [via USBController]: high speed %s" %(asState(mach.USBController.enabledEhci))
658 print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
659
660 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
661 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
662 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
663 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
664
665 controllers = ctx['global'].getArray(mach, 'storageControllers')
666 if controllers:
667 print
668 print " Controllers:"
669 for controller in controllers:
670 print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
671
672 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
673 if attaches:
674 print
675 print " Mediums:"
676 for a in attaches:
677 print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
678 m = a.medium
679 if a.type == ctx['global'].constants.DeviceType_HardDisk:
680 print " HDD:"
681 print " Id: %s" %(m.id)
682 print " Location: %s" %(m.location)
683 print " Name: %s" %(m.name)
684 print " Format: %s" %(m.format)
685
686 if a.type == ctx['global'].constants.DeviceType_DVD:
687 print " DVD:"
688 if m:
689 print " Id: %s" %(m.id)
690 print " Name: %s" %(m.name)
691 if m.hostDrive:
692 print " Host DVD %s" %(m.location)
693 if a.passthrough:
694 print " [passthrough mode]"
695 else:
696 print " Virtual image at %s" %(m.location)
697 print " Size: %s" %(m.size)
698
699 if a.type == ctx['global'].constants.DeviceType_Floppy:
700 print " Floppy:"
701 if m:
702 print " Id: %s" %(m.id)
703 print " Name: %s" %(m.name)
704 if m.hostDrive:
705 print " Host floppy %s" %(m.location)
706 else:
707 print " Virtual image at %s" %(m.location)
708 print " Size: %s" %(m.size)
709
710 return 0
711
712def startCmd(ctx, args):
713 mach = argsToMach(ctx,args)
714 if mach == None:
715 return 0
716 if len(args) > 2:
717 type = args[2]
718 else:
719 type = "gui"
720 startVm(ctx, mach, type)
721 return 0
722
723def createVmCmd(ctx, args):
724 if (len(args) < 3 or len(args) > 4):
725 print "usage: createvm name ostype <basefolder>"
726 return 0
727 name = args[1]
728 oskind = args[2]
729 if len(args) == 4:
730 base = args[3]
731 else:
732 base = ''
733 try:
734 ctx['vb'].getGuestOSType(oskind)
735 except Exception, e:
736 print 'Unknown OS type:',oskind
737 return 0
738 createVm(ctx, name, oskind, base)
739 return 0
740
741def ginfoCmd(ctx,args):
742 if (len(args) < 2):
743 print "usage: ginfo [vmname|uuid]"
744 return 0
745 mach = argsToMach(ctx,args)
746 if mach == None:
747 return 0
748 cmdExistingVm(ctx, mach, 'ginfo', '')
749 return 0
750
751def execInGuest(ctx,console,args):
752 if len(args) < 1:
753 print "exec in guest needs at least program name"
754 return
755 user = ""
756 passwd = ""
757 tmo = 0
758 print "executing %s with %s" %(args[0], args[1:])
759 (progress, pid) = console.guest.executeProcess(args[0], 0, args[1:], [], "", "", "", user, passwd, tmo)
760 print "executed with pid %d" %(pid)
761
762def gexecCmd(ctx,args):
763 if (len(args) < 2):
764 print "usage: gexec [vmname|uuid] command args"
765 return 0
766 mach = argsToMach(ctx,args)
767 if mach == None:
768 return 0
769 gargs = args[2:]
770 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args))
771 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
772 return 0
773
774def removeVmCmd(ctx, args):
775 mach = argsToMach(ctx,args)
776 if mach == None:
777 return 0
778 removeVm(ctx, mach)
779 return 0
780
781def pauseCmd(ctx, args):
782 mach = argsToMach(ctx,args)
783 if mach == None:
784 return 0
785 cmdExistingVm(ctx, mach, 'pause', '')
786 return 0
787
788def powerdownCmd(ctx, args):
789 mach = argsToMach(ctx,args)
790 if mach == None:
791 return 0
792 cmdExistingVm(ctx, mach, 'powerdown', '')
793 return 0
794
795def powerbuttonCmd(ctx, args):
796 mach = argsToMach(ctx,args)
797 if mach == None:
798 return 0
799 cmdExistingVm(ctx, mach, 'powerbutton', '')
800 return 0
801
802def resumeCmd(ctx, args):
803 mach = argsToMach(ctx,args)
804 if mach == None:
805 return 0
806 cmdExistingVm(ctx, mach, 'resume', '')
807 return 0
808
809def saveCmd(ctx, args):
810 mach = argsToMach(ctx,args)
811 if mach == None:
812 return 0
813 cmdExistingVm(ctx, mach, 'save', '')
814 return 0
815
816def statsCmd(ctx, args):
817 mach = argsToMach(ctx,args)
818 if mach == None:
819 return 0
820 cmdExistingVm(ctx, mach, 'stats', '')
821 return 0
822
823def guestCmd(ctx, args):
824 if (len(args) < 3):
825 print "usage: guest name commands"
826 return 0
827 mach = argsToMach(ctx,args)
828 if mach == None:
829 return 0
830 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
831 return 0
832
833def screenshotCmd(ctx, args):
834 if (len(args) < 2):
835 print "usage: screenshot vm <file> <width> <height> <monitor>"
836 return 0
837 mach = argsToMach(ctx,args)
838 if mach == None:
839 return 0
840 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
841 return 0
842
843def teleportCmd(ctx, args):
844 if (len(args) < 3):
845 print "usage: teleport name host:port <password>"
846 return 0
847 mach = argsToMach(ctx,args)
848 if mach == None:
849 return 0
850 cmdExistingVm(ctx, mach, 'teleport', args[2:])
851 return 0
852
853def portalsettings(ctx,mach,args):
854 enabled = args[0]
855 mach.teleporterEnabled = enabled
856 if enabled:
857 port = args[1]
858 passwd = args[2]
859 mach.teleporterPort = port
860 mach.teleporterPassword = passwd
861
862def openportalCmd(ctx, args):
863 if (len(args) < 3):
864 print "usage: openportal name port <password>"
865 return 0
866 mach = argsToMach(ctx,args)
867 if mach == None:
868 return 0
869 port = int(args[2])
870 if (len(args) > 3):
871 passwd = args[3]
872 else:
873 passwd = ""
874 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
875 cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
876 startVm(ctx, mach, "gui")
877 return 0
878
879def closeportalCmd(ctx, args):
880 if (len(args) < 2):
881 print "usage: closeportal name"
882 return 0
883 mach = argsToMach(ctx,args)
884 if mach == None:
885 return 0
886 if mach.teleporterEnabled:
887 cmdClosedVm(ctx, mach, portalsettings, [False])
888 return 0
889
890def gueststatsCmd(ctx, args):
891 if (len(args) < 2):
892 print "usage: gueststats name <check interval>"
893 return 0
894 mach = argsToMach(ctx,args)
895 if mach == None:
896 return 0
897 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
898 return 0
899
900def plugcpu(ctx,mach,args):
901 plug = args[0]
902 cpu = args[1]
903 if plug:
904 print "Adding CPU %d..." %(cpu)
905 mach.hotPlugCPU(cpu)
906 else:
907 print "Removing CPU %d..." %(cpu)
908 mach.hotUnplugCPU(cpu)
909
910def plugcpuCmd(ctx, args):
911 if (len(args) < 2):
912 print "usage: plugcpu name cpuid"
913 return 0
914 mach = argsToMach(ctx,args)
915 if mach == None:
916 return 0
917 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
918 if mach.CPUHotPlugEnabled:
919 cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
920 else:
921 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
922 return 0
923
924def unplugcpuCmd(ctx, args):
925 if (len(args) < 2):
926 print "usage: unplugcpu name cpuid"
927 return 0
928 mach = argsToMach(ctx,args)
929 if mach == None:
930 return 0
931 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
932 if mach.CPUHotPlugEnabled:
933 cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
934 else:
935 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
936 return 0
937
938def setvar(ctx,mach,args):
939 expr = 'mach.'+args[0]+' = '+args[1]
940 print "Executing",expr
941 exec expr
942
943def setvarCmd(ctx, args):
944 if (len(args) < 4):
945 print "usage: setvar [vmname|uuid] expr value"
946 return 0
947 mach = argsToMach(ctx,args)
948 if mach == None:
949 return 0
950 cmdClosedVm(ctx, mach, setvar, args[2:])
951 return 0
952
953def setvmextra(ctx,mach,args):
954 key = args[0]
955 value = args[1]
956 print "%s: setting %s to %s" %(mach.name, key, value)
957 mach.setExtraData(key, value)
958
959def setExtraDataCmd(ctx, args):
960 if (len(args) < 3):
961 print "usage: setextra [vmname|uuid|global] key <value>"
962 return 0
963 key = args[2]
964 if len(args) == 4:
965 value = args[3]
966 else:
967 value = None
968 if args[1] == 'global':
969 ctx['vb'].setExtraData(key, value)
970 return 0
971
972 mach = argsToMach(ctx,args)
973 if mach == None:
974 return 0
975 cmdClosedVm(ctx, mach, setvmextra, [key, value])
976 return 0
977
978def printExtraKey(obj, key, value):
979 print "%s: '%s' = '%s'" %(obj, key, value)
980
981def getExtraDataCmd(ctx, args):
982 if (len(args) < 2):
983 print "usage: getextra [vmname|uuid|global] <key>"
984 return 0
985 if len(args) == 3:
986 key = args[2]
987 else:
988 key = None
989
990 if args[1] == 'global':
991 obj = ctx['vb']
992 else:
993 obj = argsToMach(ctx,args)
994 if obj == None:
995 return 0
996
997 if key == None:
998 keys = obj.getExtraDataKeys()
999 else:
1000 keys = [ key ]
1001 for k in keys:
1002 printExtraKey(args[1], k, obj.getExtraData(k))
1003
1004 return 0
1005
1006def quitCmd(ctx, args):
1007 return 1
1008
1009def aliasCmd(ctx, args):
1010 if (len(args) == 3):
1011 aliases[args[1]] = args[2]
1012 return 0
1013
1014 for (k,v) in aliases.items():
1015 print "'%s' is an alias for '%s'" %(k,v)
1016 return 0
1017
1018def verboseCmd(ctx, args):
1019 global g_verbose
1020 g_verbose = not g_verbose
1021 return 0
1022
1023def getUSBStateString(state):
1024 if state == 0:
1025 return "NotSupported"
1026 elif state == 1:
1027 return "Unavailable"
1028 elif state == 2:
1029 return "Busy"
1030 elif state == 3:
1031 return "Available"
1032 elif state == 4:
1033 return "Held"
1034 elif state == 5:
1035 return "Captured"
1036 else:
1037 return "Unknown"
1038
1039def hostCmd(ctx, args):
1040 host = ctx['vb'].host
1041 cnt = host.processorCount
1042 print "Processors available/online: %d/%d " %(cnt,host.processorOnlineCount)
1043 for i in range(0,cnt):
1044 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
1045
1046 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
1047 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
1048 if host.Acceleration3DAvailable:
1049 print "3D acceleration available"
1050 else:
1051 print "3D acceleration NOT available"
1052
1053 print "Network interfaces:"
1054 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
1055 print " %s (%s)" %(ni.name, ni.IPAddress)
1056
1057 print "DVD drives:"
1058 for dd in ctx['global'].getArray(host, 'DVDDrives'):
1059 print " %s - %s" %(dd.name, dd.description)
1060
1061 print "Floppy drives:"
1062 for dd in ctx['global'].getArray(host, 'floppyDrives'):
1063 print " %s - %s" %(dd.name, dd.description)
1064
1065 print "USB devices:"
1066 for ud in ctx['global'].getArray(host, 'USBDevices'):
1067 printUsbHostDev(ctx,ud)
1068
1069 if ctx['perf']:
1070 for metric in ctx['perf'].query(["*"], [host]):
1071 print metric['name'], metric['values_as_string']
1072
1073 return 0
1074
1075def monitorGuestCmd(ctx, args):
1076 if (len(args) < 2):
1077 print "usage: monitorGuest name (duration)"
1078 return 0
1079 mach = argsToMach(ctx,args)
1080 if mach == None:
1081 return 0
1082 dur = 5
1083 if len(args) > 2:
1084 dur = float(args[2])
1085 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1086 return 0
1087
1088def monitorVBoxCmd(ctx, args):
1089 if (len(args) > 2):
1090 print "usage: monitorVBox (duration)"
1091 return 0
1092 dur = 5
1093 if len(args) > 1:
1094 dur = float(args[1])
1095 monitorVBox(ctx, dur)
1096 return 0
1097
1098def getAdapterType(ctx, type):
1099 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1100 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1101 return "pcnet"
1102 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1103 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1104 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1105 return "e1000"
1106 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1107 return "virtio"
1108 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1109 return None
1110 else:
1111 raise Exception("Unknown adapter type: "+type)
1112
1113
1114def portForwardCmd(ctx, args):
1115 if (len(args) != 5):
1116 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1117 return 0
1118 mach = argsToMach(ctx,args)
1119 if mach == None:
1120 return 0
1121 adapterNum = int(args[2])
1122 hostPort = int(args[3])
1123 guestPort = int(args[4])
1124 proto = "TCP"
1125 session = ctx['global'].openMachineSession(mach.id)
1126 mach = session.machine
1127
1128 adapter = mach.getNetworkAdapter(adapterNum)
1129 adapterType = getAdapterType(ctx, adapter.adapterType)
1130
1131 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1132 config = "VBoxInternal/Devices/" + adapterType + "/"
1133 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1134
1135 mach.setExtraData(config + "/Protocol", proto)
1136 mach.setExtraData(config + "/HostPort", str(hostPort))
1137 mach.setExtraData(config + "/GuestPort", str(guestPort))
1138
1139 mach.saveSettings()
1140 session.close()
1141
1142 return 0
1143
1144
1145def showLogCmd(ctx, args):
1146 if (len(args) < 2):
1147 print "usage: showLog <vm> <num>"
1148 return 0
1149 mach = argsToMach(ctx,args)
1150 if mach == None:
1151 return 0
1152
1153 log = 0;
1154 if (len(args) > 2):
1155 log = args[2];
1156
1157 uOffset = 0;
1158 while True:
1159 data = mach.readLog(log, uOffset, 1024*1024)
1160 if (len(data) == 0):
1161 break
1162 # print adds either NL or space to chunks not ending with a NL
1163 sys.stdout.write(data)
1164 uOffset += len(data)
1165
1166 return 0
1167
1168def evalCmd(ctx, args):
1169 expr = ' '.join(args[1:])
1170 try:
1171 exec expr
1172 except Exception, e:
1173 print 'failed: ',e
1174 if g_verbose:
1175 traceback.print_exc()
1176 return 0
1177
1178def reloadExtCmd(ctx, args):
1179 # maybe will want more args smartness
1180 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1181 autoCompletion(commands, ctx)
1182 return 0
1183
1184
1185def runScriptCmd(ctx, args):
1186 if (len(args) != 2):
1187 print "usage: runScript <script>"
1188 return 0
1189 try:
1190 lf = open(args[1], 'r')
1191 except IOError,e:
1192 print "cannot open:",args[1], ":",e
1193 return 0
1194
1195 try:
1196 for line in lf:
1197 done = runCommand(ctx, line)
1198 if done != 0: break
1199 except Exception,e:
1200 print "error:",e
1201 if g_verbose:
1202 traceback.print_exc()
1203 lf.close()
1204 return 0
1205
1206def sleepCmd(ctx, args):
1207 if (len(args) != 2):
1208 print "usage: sleep <secs>"
1209 return 0
1210
1211 try:
1212 time.sleep(float(args[1]))
1213 except:
1214 # to allow sleep interrupt
1215 pass
1216 return 0
1217
1218
1219def shellCmd(ctx, args):
1220 if (len(args) < 2):
1221 print "usage: shell <commands>"
1222 return 0
1223 cmd = ' '.join(args[1:])
1224 try:
1225 os.system(cmd)
1226 except KeyboardInterrupt:
1227 # to allow shell command interruption
1228 pass
1229 return 0
1230
1231
1232def connectCmd(ctx, args):
1233 if (len(args) > 4):
1234 print "usage: connect [url] [username] [passwd]"
1235 return 0
1236
1237 if ctx['vb'] is not None:
1238 print "Already connected, disconnect first..."
1239 return 0
1240
1241 if (len(args) > 1):
1242 url = args[1]
1243 else:
1244 url = None
1245
1246 if (len(args) > 2):
1247 user = args[2]
1248 else:
1249 user = ""
1250
1251 if (len(args) > 3):
1252 passwd = args[3]
1253 else:
1254 passwd = ""
1255
1256 vbox = ctx['global'].platform.connect(url, user, passwd)
1257 ctx['vb'] = vbox
1258 print "Running VirtualBox version %s" %(vbox.version)
1259 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1260 return 0
1261
1262def disconnectCmd(ctx, args):
1263 if (len(args) != 1):
1264 print "usage: disconnect"
1265 return 0
1266
1267 if ctx['vb'] is None:
1268 print "Not connected yet."
1269 return 0
1270
1271 try:
1272 ctx['global'].platform.disconnect()
1273 except:
1274 ctx['vb'] = None
1275 raise
1276
1277 ctx['vb'] = None
1278 return 0
1279
1280def exportVMCmd(ctx, args):
1281 import sys
1282
1283 if len(args) < 3:
1284 print "usage: exportVm <machine> <path> <format> <license>"
1285 return 0
1286 mach = argsToMach(ctx,args)
1287 if mach is None:
1288 return 0
1289 path = args[2]
1290 if (len(args) > 3):
1291 format = args[3]
1292 else:
1293 format = "ovf-1.0"
1294 if (len(args) > 4):
1295 license = args[4]
1296 else:
1297 license = "GPL"
1298
1299 app = ctx['vb'].createAppliance()
1300 desc = mach.export(app)
1301 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1302 p = app.write(format, path)
1303 progressBar(ctx, p)
1304 if (p.completed and int(p.resultCode) == 0):
1305 print "Exported to %s in format %s" %(path, format)
1306 return 0
1307
1308# PC XT scancodes
1309scancodes = {
1310 'a': 0x1e,
1311 'b': 0x30,
1312 'c': 0x2e,
1313 'd': 0x20,
1314 'e': 0x12,
1315 'f': 0x21,
1316 'g': 0x22,
1317 'h': 0x23,
1318 'i': 0x17,
1319 'j': 0x24,
1320 'k': 0x25,
1321 'l': 0x26,
1322 'm': 0x32,
1323 'n': 0x31,
1324 'o': 0x18,
1325 'p': 0x19,
1326 'q': 0x10,
1327 'r': 0x13,
1328 's': 0x1f,
1329 't': 0x14,
1330 'u': 0x16,
1331 'v': 0x2f,
1332 'w': 0x11,
1333 'x': 0x2d,
1334 'y': 0x15,
1335 'z': 0x2c,
1336 '0': 0x0b,
1337 '1': 0x02,
1338 '2': 0x03,
1339 '3': 0x04,
1340 '4': 0x05,
1341 '5': 0x06,
1342 '6': 0x07,
1343 '7': 0x08,
1344 '8': 0x09,
1345 '9': 0x0a,
1346 ' ': 0x39,
1347 '-': 0xc,
1348 '=': 0xd,
1349 '[': 0x1a,
1350 ']': 0x1b,
1351 ';': 0x27,
1352 '\'': 0x28,
1353 ',': 0x33,
1354 '.': 0x34,
1355 '/': 0x35,
1356 '\t': 0xf,
1357 '\n': 0x1c,
1358 '`': 0x29
1359};
1360
1361extScancodes = {
1362 'ESC' : [0x01],
1363 'BKSP': [0xe],
1364 'SPACE': [0x39],
1365 'TAB': [0x0f],
1366 'CAPS': [0x3a],
1367 'ENTER': [0x1c],
1368 'LSHIFT': [0x2a],
1369 'RSHIFT': [0x36],
1370 'INS': [0xe0, 0x52],
1371 'DEL': [0xe0, 0x53],
1372 'END': [0xe0, 0x4f],
1373 'HOME': [0xe0, 0x47],
1374 'PGUP': [0xe0, 0x49],
1375 'PGDOWN': [0xe0, 0x51],
1376 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
1377 'RGUI': [0xe0, 0x5c],
1378 'LCTR': [0x1d],
1379 'RCTR': [0xe0, 0x1d],
1380 'LALT': [0x38],
1381 'RALT': [0xe0, 0x38],
1382 'APPS': [0xe0, 0x5d],
1383 'F1': [0x3b],
1384 'F2': [0x3c],
1385 'F3': [0x3d],
1386 'F4': [0x3e],
1387 'F5': [0x3f],
1388 'F6': [0x40],
1389 'F7': [0x41],
1390 'F8': [0x42],
1391 'F9': [0x43],
1392 'F10': [0x44 ],
1393 'F11': [0x57],
1394 'F12': [0x58],
1395 'UP': [0xe0, 0x48],
1396 'LEFT': [0xe0, 0x4b],
1397 'DOWN': [0xe0, 0x50],
1398 'RIGHT': [0xe0, 0x4d],
1399};
1400
1401def keyDown(ch):
1402 code = scancodes.get(ch, 0x0)
1403 if code != 0:
1404 return [code]
1405 extCode = extScancodes.get(ch, [])
1406 if len(extCode) == 0:
1407 print "bad ext",ch
1408 return extCode
1409
1410def keyUp(ch):
1411 codes = keyDown(ch)[:] # make a copy
1412 if len(codes) > 0:
1413 codes[len(codes)-1] += 0x80
1414 return codes
1415
1416def typeInGuest(console, text, delay):
1417 import time
1418 pressed = []
1419 group = False
1420 modGroupEnd = True
1421 i = 0
1422 while i < len(text):
1423 ch = text[i]
1424 i = i+1
1425 if ch == '{':
1426 # start group, all keys to be pressed at the same time
1427 group = True
1428 continue
1429 if ch == '}':
1430 # end group, release all keys
1431 for c in pressed:
1432 console.keyboard.putScancodes(keyUp(c))
1433 pressed = []
1434 group = False
1435 continue
1436 if ch == 'W':
1437 # just wait a bit
1438 time.sleep(0.3)
1439 continue
1440 if ch == '^' or ch == '|' or ch == '$' or ch == '_':
1441 if ch == '^':
1442 ch = 'LCTR'
1443 if ch == '|':
1444 ch = 'LSHIFT'
1445 if ch == '_':
1446 ch = 'LALT'
1447 if ch == '$':
1448 ch = 'LGUI'
1449 if not group:
1450 modGroupEnd = False
1451 else:
1452 if ch == '\\':
1453 if i < len(text):
1454 ch = text[i]
1455 i = i+1
1456 if ch == 'n':
1457 ch = '\n'
1458 elif ch == '&':
1459 combo = ""
1460 while i < len(text):
1461 ch = text[i]
1462 i = i+1
1463 if ch == ';':
1464 break
1465 combo += ch
1466 ch = combo
1467 modGroupEnd = True
1468 console.keyboard.putScancodes(keyDown(ch))
1469 pressed.insert(0, ch)
1470 if not group and modGroupEnd:
1471 for c in pressed:
1472 console.keyboard.putScancodes(keyUp(c))
1473 pressed = []
1474 modGroupEnd = True
1475 time.sleep(delay)
1476
1477def typeGuestCmd(ctx, args):
1478 import sys
1479
1480 if len(args) < 3:
1481 print "usage: typeGuest <machine> <text> <charDelay>"
1482 return 0
1483 mach = argsToMach(ctx,args)
1484 if mach is None:
1485 return 0
1486
1487 text = args[2]
1488
1489 if len(args) > 3:
1490 delay = float(args[3])
1491 else:
1492 delay = 0.1
1493
1494 gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
1495 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1496
1497 return 0
1498
1499def optId(verbose,id):
1500 if verbose:
1501 return ": "+id
1502 else:
1503 return ""
1504
1505def asSize(val,inBytes):
1506 if inBytes:
1507 return int(val)/(1024*1024)
1508 else:
1509 return int(val)
1510
1511def listMediumsCmd(ctx,args):
1512 if len(args) > 1:
1513 verbose = int(args[1])
1514 else:
1515 verbose = False
1516 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
1517 print "Hard disks:"
1518 for hdd in hdds:
1519 if hdd.state != ctx['global'].constants.MediumState_Created:
1520 hdd.refreshState()
1521 print " %s (%s)%s %dM [logical %dM]" %(hdd.location, hdd.format, optId(verbose,hdd.id),asSize(hdd.size, True), asSize(hdd.logicalSize, False))
1522
1523 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
1524 print "CD/DVD disks:"
1525 for dvd in dvds:
1526 if dvd.state != ctx['global'].constants.MediumState_Created:
1527 dvd.refreshState()
1528 print " %s (%s)%s %dM" %(dvd.location, dvd.format,optId(verbose,hdd.id),asSize(hdd.size, True))
1529
1530 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
1531 print "Floopy disks:"
1532 for floppy in floppys:
1533 if floppy.state != ctx['global'].constants.MediumState_Created:
1534 floppy.refreshState()
1535 print " %s (%s)%s %dM" %(floppy.location, floppy.format,optId(verbose,hdd.id), asSize(hdd.size, True))
1536
1537 return 0
1538
1539def listUsbCmd(ctx,args):
1540 if (len(args) > 1):
1541 print "usage: listUsb"
1542 return 0
1543
1544 host = ctx['vb'].host
1545 for ud in ctx['global'].getArray(host, 'USBDevices'):
1546 printHostUsbDev(ctx,ud)
1547
1548 return 0
1549
1550def createHddCmd(ctx,args):
1551 if (len(args) < 3):
1552 print "usage: createHdd sizeM location type"
1553 return 0
1554
1555 size = int(args[1])
1556 loc = args[2]
1557 if len(args) > 3:
1558 format = args[3]
1559 else:
1560 format = "vdi"
1561
1562 hdd = ctx['vb'].createHardDisk(format, loc)
1563 progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
1564 ctx['progressBar'](progress)
1565
1566 if not hdd.id:
1567 print "cannot create disk (file %s exist?)" %(loc)
1568 return 0
1569
1570 print "created HDD at %s as %s" %(hdd.location, hdd.id)
1571
1572 return 0
1573
1574def registerHddCmd(ctx,args):
1575 if (len(args) < 2):
1576 print "usage: registerHdd location"
1577 return 0
1578
1579 vb = ctx['vb']
1580 loc = args[1]
1581 setImageId = False
1582 imageId = ""
1583 setParentId = False
1584 parentId = ""
1585 hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
1586 print "registered HDD as %s" %(hdd.id)
1587 return 0
1588
1589def controldevice(ctx,mach,args):
1590 [ctr,port,slot,type,id] = args
1591 mach.attachDevice(ctr, port, slot,type,id)
1592
1593def attachHddCmd(ctx,args):
1594 if (len(args) < 4):
1595 print "usage: attachHdd vm hdd controller port:slot"
1596 return 0
1597
1598 mach = argsToMach(ctx,args)
1599 if mach is None:
1600 return 0
1601 vb = ctx['vb']
1602 loc = args[2]
1603 try:
1604 hdd = vb.findHardDisk(loc)
1605 except:
1606 print "no HDD with path %s registered" %(loc)
1607 return 0
1608 ctr = args[3]
1609 (port,slot) = args[4].split(":")
1610 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
1611 return 0
1612
1613def detachVmDevice(ctx,mach,args):
1614 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1615 hid = args[0]
1616 for a in atts:
1617 if a.medium:
1618 if hid == "ALL" or a.medium.id == hid:
1619 mach.detachDevice(a.controller, a.port, a.device)
1620
1621def detachMedium(ctx,mid,medium):
1622 cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
1623
1624def detachHddCmd(ctx,args):
1625 if (len(args) < 3):
1626 print "usage: detachHdd vm hdd"
1627 return 0
1628
1629 mach = argsToMach(ctx,args)
1630 if mach is None:
1631 return 0
1632 vb = ctx['vb']
1633 loc = args[2]
1634 try:
1635 hdd = vb.findHardDisk(loc)
1636 except:
1637 print "no HDD with path %s registered" %(loc)
1638 return 0
1639
1640 detachMedium(ctx,mach.id,hdd)
1641 return 0
1642
1643def unregisterHddCmd(ctx,args):
1644 if (len(args) < 2):
1645 print "usage: unregisterHdd path <vmunreg>"
1646 return 0
1647
1648 vb = ctx['vb']
1649 loc = args[1]
1650 if (len(args) > 2):
1651 vmunreg = int(args[2])
1652 else:
1653 vmunreg = 0
1654 try:
1655 hdd = vb.findHardDisk(loc)
1656 except:
1657 print "no HDD with path %s registered" %(loc)
1658 return 0
1659
1660 if vmunreg != 0:
1661 machs = ctx['global'].getArray(hdd, 'machineIds')
1662 try:
1663 for m in machs:
1664 print "Trying to detach from %s" %(m)
1665 detachMedium(ctx,m,hdd)
1666 except Exception, e:
1667 print 'failed: ',e
1668 return 0
1669 hdd.close()
1670 return 0
1671
1672def removeHddCmd(ctx,args):
1673 if (len(args) != 2):
1674 print "usage: removeHdd path"
1675 return 0
1676
1677 vb = ctx['vb']
1678 loc = args[1]
1679 try:
1680 hdd = vb.findHardDisk(loc)
1681 except:
1682 print "no HDD with path %s registered" %(loc)
1683 return 0
1684
1685 progress = hdd.deleteStorage()
1686 ctx['progressBar'](progress)
1687
1688 return 0
1689
1690def registerIsoCmd(ctx,args):
1691 if (len(args) < 2):
1692 print "usage: registerIso location"
1693 return 0
1694 vb = ctx['vb']
1695 loc = args[1]
1696 id = ""
1697 iso = vb.openDVDImage(loc, id)
1698 print "registered ISO as %s" %(iso.id)
1699 return 0
1700
1701def unregisterIsoCmd(ctx,args):
1702 if (len(args) != 2):
1703 print "usage: unregisterIso path"
1704 return 0
1705
1706 vb = ctx['vb']
1707 loc = args[1]
1708 try:
1709 dvd = vb.findDVDImage(loc)
1710 except:
1711 print "no DVD with path %s registered" %(loc)
1712 return 0
1713
1714 progress = dvd.close()
1715 print "Unregistered ISO at %s" %(dvd.location)
1716
1717 return 0
1718
1719def removeIsoCmd(ctx,args):
1720 if (len(args) != 2):
1721 print "usage: removeIso path"
1722 return 0
1723
1724 vb = ctx['vb']
1725 loc = args[1]
1726 try:
1727 dvd = vb.findDVDImage(loc)
1728 except:
1729 print "no DVD with path %s registered" %(loc)
1730 return 0
1731
1732 progress = dvd.deleteStorage()
1733 ctx['progressBar'](progress)
1734 print "Removed ISO at %s" %(dvd.location)
1735
1736 return 0
1737
1738def attachIsoCmd(ctx,args):
1739 if (len(args) < 5):
1740 print "usage: attachIso vm iso controller port:slot"
1741 return 0
1742
1743 mach = argsToMach(ctx,args)
1744 if mach is None:
1745 return 0
1746 vb = ctx['vb']
1747 loc = args[2]
1748 try:
1749 dvd = vb.findDVDImage(loc)
1750 except:
1751 print "no DVD with path %s registered" %(loc)
1752 return 0
1753 ctr = args[3]
1754 (port,slot) = args[4].split(":")
1755 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
1756 return 0
1757
1758def detachIsoCmd(ctx,args):
1759 if (len(args) < 3):
1760 print "usage: detachIso vm iso"
1761 return 0
1762
1763 mach = argsToMach(ctx,args)
1764 if mach is None:
1765 return 0
1766 vb = ctx['vb']
1767 loc = args[2]
1768 try:
1769 dvd = vb.findDVDImage(loc)
1770 except:
1771 print "no DVD with path %s registered" %(loc)
1772 return 0
1773
1774 detachMedium(ctx,mach.id,dvd)
1775 return 0
1776
1777def mountIsoCmd(ctx,args):
1778 if (len(args) < 5):
1779 print "usage: mountIso vm iso controller port:slot"
1780 return 0
1781
1782 mach = argsToMach(ctx,args)
1783 if mach is None:
1784 return 0
1785 vb = ctx['vb']
1786 loc = args[2]
1787 try:
1788 dvd = vb.findDVDImage(loc)
1789 except:
1790 print "no DVD with path %s registered" %(loc)
1791 return 0
1792
1793 ctr = args[3]
1794 (port,slot) = args[4].split(":")
1795
1796 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
1797
1798 return 0
1799
1800def unmountIsoCmd(ctx,args):
1801 if (len(args) < 4):
1802 print "usage: unmountIso vm controller port:slot"
1803 return 0
1804
1805 mach = argsToMach(ctx,args)
1806 if mach is None:
1807 return 0
1808 vb = ctx['vb']
1809
1810 ctr = args[2]
1811 (port,slot) = args[3].split(":")
1812
1813 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
1814
1815 return 0
1816
1817def attachCtr(ctx,mach,args):
1818 [name, bus, type] = args
1819 ctr = mach.addStorageController(name, bus)
1820 if type != None:
1821 ctr.controllerType = type
1822
1823def attachCtrCmd(ctx,args):
1824 if (len(args) < 4):
1825 print "usage: attachCtr vm cname bus <type>"
1826 return 0
1827
1828 if len(args) > 4:
1829 type = enumFromString(ctx,'StorageControllerType', args[4])
1830 if type == None:
1831 print "Controller type %s unknown" %(args[4])
1832 return 0
1833 else:
1834 type = None
1835
1836 mach = argsToMach(ctx,args)
1837 if mach is None:
1838 return 0
1839 bus = enumFromString(ctx,'StorageBus', args[3])
1840 if bus is None:
1841 print "Bus type %s unknown" %(args[3])
1842 return 0
1843 name = args[2]
1844 cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
1845 return 0
1846
1847def detachCtrCmd(ctx,args):
1848 if (len(args) < 3):
1849 print "usage: detachCtr vm name"
1850 return 0
1851
1852 mach = argsToMach(ctx,args)
1853 if mach is None:
1854 return 0
1855 ctr = args[2]
1856 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
1857 return 0
1858
1859def usbctr(ctx,mach,console,args):
1860 if (args[0]):
1861 console.attachUSBDevice(args[1])
1862 else:
1863 console.detachUSBDevice(args[1])
1864
1865def attachUsbCmd(ctx,args):
1866 if (len(args) < 3):
1867 print "usage: attachUsb vm deviceuid"
1868 return 0
1869
1870 mach = argsToMach(ctx,args)
1871 if mach is None:
1872 return 0
1873 dev = args[2]
1874 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
1875 return 0
1876
1877def detachUsbCmd(ctx,args):
1878 if (len(args) < 3):
1879 print "usage: detachUsb vm deviceuid"
1880 return 0
1881
1882 mach = argsToMach(ctx,args)
1883 if mach is None:
1884 return 0
1885 dev = args[2]
1886 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
1887 return 0
1888
1889aliases = {'s':'start',
1890 'i':'info',
1891 'l':'list',
1892 'h':'help',
1893 'a':'alias',
1894 'q':'quit', 'exit':'quit',
1895 'tg': 'typeGuest',
1896 'v':'verbose'}
1897
1898commands = {'help':['Prints help information', helpCmd, 0],
1899 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
1900 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
1901 'removeVm':['Remove virtual machine', removeVmCmd, 0],
1902 'pause':['Pause virtual machine', pauseCmd, 0],
1903 'resume':['Resume virtual machine', resumeCmd, 0],
1904 'save':['Save execution state of virtual machine', saveCmd, 0],
1905 'stats':['Stats for virtual machine', statsCmd, 0],
1906 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1907 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1908 'list':['Shows known virtual machines', listCmd, 0],
1909 'info':['Shows info on machine', infoCmd, 0],
1910 'ginfo':['Shows info on guest', ginfoCmd, 0],
1911 'gexec':['Executes program in the guest', gexecCmd, 0],
1912 'alias':['Control aliases', aliasCmd, 0],
1913 'verbose':['Toggle verbosity', verboseCmd, 0],
1914 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1915 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1916 'quit':['Exits', quitCmd, 0],
1917 'host':['Show host information', hostCmd, 0],
1918 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
1919 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1920 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1921 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1922 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1923 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1924 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1925 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1926 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1927 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
1928 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1929 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
1930 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
1931 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
1932 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
1933 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
1934 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
1935 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
1936 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
1937 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
1938 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
1939 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
1940 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
1941 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
1942 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
1943 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
1944 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
1945 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
1946 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
1947 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
1948 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
1949 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
1950 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
1951 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
1952 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
1953 'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
1954 'detachUsb': ['Detach USB device from the VM: detachUsb win uui', detachUsbCmd, 0],
1955 'listMediums': ['List mediums known to this VBox instance', listMediumsCmd, 0],
1956 'listUsb': ['List known USB devices', listUsbCmd, 0]
1957 }
1958
1959def runCommandArgs(ctx, args):
1960 c = args[0]
1961 if aliases.get(c, None) != None:
1962 c = aliases[c]
1963 ci = commands.get(c,None)
1964 if ci == None:
1965 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
1966 return 0
1967 return ci[1](ctx, args)
1968
1969
1970def runCommand(ctx, cmd):
1971 if len(cmd) == 0: return 0
1972 args = split_no_quotes(cmd)
1973 if len(args) == 0: return 0
1974 return runCommandArgs(ctx, args)
1975
1976#
1977# To write your own custom commands to vboxshell, create
1978# file ~/.VirtualBox/shellext.py with content like
1979#
1980# def runTestCmd(ctx, args):
1981# print "Testy test", ctx['vb']
1982# return 0
1983#
1984# commands = {
1985# 'test': ['Test help', runTestCmd]
1986# }
1987# and issue reloadExt shell command.
1988# This file also will be read automatically on startup or 'reloadExt'.
1989#
1990# Also one can put shell extensions into ~/.VirtualBox/shexts and
1991# they will also be picked up, so this way one can exchange
1992# shell extensions easily.
1993def addExtsFromFile(ctx, cmds, file):
1994 if not os.path.isfile(file):
1995 return
1996 d = {}
1997 try:
1998 execfile(file, d, d)
1999 for (k,v) in d['commands'].items():
2000 if g_verbose:
2001 print "customize: adding \"%s\" - %s" %(k, v[0])
2002 cmds[k] = [v[0], v[1], file]
2003 except:
2004 print "Error loading user extensions from %s" %(file)
2005 traceback.print_exc()
2006
2007
2008def checkUserExtensions(ctx, cmds, folder):
2009 folder = str(folder)
2010 name = os.path.join(folder, "shellext.py")
2011 addExtsFromFile(ctx, cmds, name)
2012 # also check 'exts' directory for all files
2013 shextdir = os.path.join(folder, "shexts")
2014 if not os.path.isdir(shextdir):
2015 return
2016 exts = os.listdir(shextdir)
2017 for e in exts:
2018 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
2019
2020def getHomeFolder(ctx):
2021 if ctx['remote'] or ctx['vb'] is None:
2022 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
2023 else:
2024 return ctx['vb'].homeFolder
2025
2026def interpret(ctx):
2027 if ctx['remote']:
2028 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
2029 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
2030
2031 vbox = ctx['vb']
2032
2033 if vbox is not None:
2034 print "Running VirtualBox version %s" %(vbox.version)
2035 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
2036 else:
2037 ctx['perf'] = None
2038
2039 home = getHomeFolder(ctx)
2040 checkUserExtensions(ctx, commands, home)
2041
2042 autoCompletion(commands, ctx)
2043
2044 if g_hasreadline and os.path.exists(HISTORY_FILENAME):
2045 readline.read_history_file(HISTORY_FILENAME)
2046
2047 # to allow to print actual host information, we collect info for
2048 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
2049 if ctx['perf']:
2050 try:
2051 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
2052 except:
2053 pass
2054
2055 while True:
2056 try:
2057 cmd = raw_input("vbox> ")
2058 done = runCommand(ctx, cmd)
2059 if done != 0: break
2060 except KeyboardInterrupt:
2061 print '====== You can type quit or q to leave'
2062 break
2063 except EOFError:
2064 break;
2065 except Exception,e:
2066 print e
2067 if g_verbose:
2068 traceback.print_exc()
2069 ctx['global'].waitForEvents(0)
2070 try:
2071 # There is no need to disable metric collection. This is just an example.
2072 if ct['perf']:
2073 ctx['perf'].disable(['*'], [vbox.host])
2074 except:
2075 pass
2076 if g_hasreadline:
2077 readline.write_history_file(HISTORY_FILENAME)
2078
2079def runCommandCb(ctx, cmd, args):
2080 args.insert(0, cmd)
2081 return runCommandArgs(ctx, args)
2082
2083def runGuestCommandCb(ctx, id, guestLambda, args):
2084 mach = machById(ctx,id)
2085 if mach == None:
2086 return 0
2087 args.insert(0, guestLambda)
2088 cmdExistingVm(ctx, mach, 'guestlambda', args)
2089 return 0
2090
2091def main(argv):
2092 style = None
2093 autopath = False
2094 argv.pop(0)
2095 while len(argv) > 0:
2096 if argv[0] == "-w":
2097 style = "WEBSERVICE"
2098 if argv[0] == "-a":
2099 autopath = True
2100 argv.pop(0)
2101
2102 if autopath:
2103 cwd = os.getcwd()
2104 vpp = os.environ.get("VBOX_PROGRAM_PATH")
2105 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
2106 vpp = cwd
2107 print "Autodetected VBOX_PROGRAM_PATH as",vpp
2108 os.environ["VBOX_PROGRAM_PATH"] = cwd
2109 sys.path.append(os.path.join(vpp, "sdk", "installer"))
2110
2111 from vboxapi import VirtualBoxManager
2112 g_virtualBoxManager = VirtualBoxManager(style, None)
2113 ctx = {'global':g_virtualBoxManager,
2114 'mgr':g_virtualBoxManager.mgr,
2115 'vb':g_virtualBoxManager.vbox,
2116 'ifaces':g_virtualBoxManager.constants,
2117 'remote':g_virtualBoxManager.remote,
2118 'type':g_virtualBoxManager.type,
2119 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
2120 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
2121 'machById': lambda id: machById(ctx,id),
2122 'argsToMach': lambda args: argsToMach(ctx,args),
2123 'progressBar': lambda p: progressBar(ctx,p),
2124 'typeInGuest': typeInGuest,
2125 '_machlist':None
2126 }
2127 interpret(ctx)
2128 g_virtualBoxManager.deinit()
2129 del g_virtualBoxManager
2130
2131if __name__ == '__main__':
2132 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