VirtualBox

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

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

python shell: better progress handling

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