VirtualBox

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

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

VBoxShell: WS-compatible screenshotting

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