VirtualBox

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

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

python: API to figuire out install directory

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 66.0 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
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):
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
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 guest = console.guest
748 if len(args) > 1:
749 gargs = args[1:]
750 else:
751 gargs = []
752 print "executing %s with args %s" %(args[0], gargs)
753 (progress, pid) = guest.executeProcess(args[0], 0, gargs, [], "", "", "", user, passwd, tmo)
754 print "executed with pid %d" %(pid)
755 if pid != 0:
756 try:
757 while not progress.completed:
758 data = None #guest.getProcessOutput(pid, 0, 1, 4096)
759 if data and len(data) > 0:
760 sys.stdout.write(data)
761 progress.waitForCompletion(100)
762 ctx['global'].waitForEvents(0)
763 except KeyboardInterrupt:
764 print "Interrupted."
765 if progress.cancelable:
766 progress.cancel()
767 return 0
768 else:
769 reportError(ctx, progress)
770
771def gexecCmd(ctx,args):
772 if (len(args) < 2):
773 print "usage: gexec [vmname|uuid] command args"
774 return 0
775 mach = argsToMach(ctx,args)
776 if mach == None:
777 return 0
778 gargs = args[2:]
779 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args))
780 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
781 return 0
782
783def gcatCmd(ctx,args):
784 if (len(args) < 2):
785 print "usage: gcat [vmname|uuid] local_file | guestProgram, such as gcat linux /home/nike/.bashrc | sh -c 'cat >'"
786 return 0
787 mach = argsToMach(ctx,args)
788 if mach == None:
789 return 0
790 gargs = args[2:]
791 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args))
792 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
793 return 0
794
795
796def removeVmCmd(ctx, args):
797 mach = argsToMach(ctx,args)
798 if mach == None:
799 return 0
800 removeVm(ctx, mach)
801 return 0
802
803def pauseCmd(ctx, args):
804 mach = argsToMach(ctx,args)
805 if mach == None:
806 return 0
807 cmdExistingVm(ctx, mach, 'pause', '')
808 return 0
809
810def powerdownCmd(ctx, args):
811 mach = argsToMach(ctx,args)
812 if mach == None:
813 return 0
814 cmdExistingVm(ctx, mach, 'powerdown', '')
815 return 0
816
817def powerbuttonCmd(ctx, args):
818 mach = argsToMach(ctx,args)
819 if mach == None:
820 return 0
821 cmdExistingVm(ctx, mach, 'powerbutton', '')
822 return 0
823
824def resumeCmd(ctx, args):
825 mach = argsToMach(ctx,args)
826 if mach == None:
827 return 0
828 cmdExistingVm(ctx, mach, 'resume', '')
829 return 0
830
831def saveCmd(ctx, args):
832 mach = argsToMach(ctx,args)
833 if mach == None:
834 return 0
835 cmdExistingVm(ctx, mach, 'save', '')
836 return 0
837
838def statsCmd(ctx, args):
839 mach = argsToMach(ctx,args)
840 if mach == None:
841 return 0
842 cmdExistingVm(ctx, mach, 'stats', '')
843 return 0
844
845def guestCmd(ctx, args):
846 if (len(args) < 3):
847 print "usage: guest name commands"
848 return 0
849 mach = argsToMach(ctx,args)
850 if mach == None:
851 return 0
852 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
853 return 0
854
855def screenshotCmd(ctx, args):
856 if (len(args) < 2):
857 print "usage: screenshot vm <file> <width> <height> <monitor>"
858 return 0
859 mach = argsToMach(ctx,args)
860 if mach == None:
861 return 0
862 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
863 return 0
864
865def teleportCmd(ctx, args):
866 if (len(args) < 3):
867 print "usage: teleport name host:port <password>"
868 return 0
869 mach = argsToMach(ctx,args)
870 if mach == None:
871 return 0
872 cmdExistingVm(ctx, mach, 'teleport', args[2:])
873 return 0
874
875def portalsettings(ctx,mach,args):
876 enabled = args[0]
877 mach.teleporterEnabled = enabled
878 if enabled:
879 port = args[1]
880 passwd = args[2]
881 mach.teleporterPort = port
882 mach.teleporterPassword = passwd
883
884def openportalCmd(ctx, args):
885 if (len(args) < 3):
886 print "usage: openportal name port <password>"
887 return 0
888 mach = argsToMach(ctx,args)
889 if mach == None:
890 return 0
891 port = int(args[2])
892 if (len(args) > 3):
893 passwd = args[3]
894 else:
895 passwd = ""
896 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
897 cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
898 startVm(ctx, mach, "gui")
899 return 0
900
901def closeportalCmd(ctx, args):
902 if (len(args) < 2):
903 print "usage: closeportal name"
904 return 0
905 mach = argsToMach(ctx,args)
906 if mach == None:
907 return 0
908 if mach.teleporterEnabled:
909 cmdClosedVm(ctx, mach, portalsettings, [False])
910 return 0
911
912def gueststatsCmd(ctx, args):
913 if (len(args) < 2):
914 print "usage: gueststats name <check interval>"
915 return 0
916 mach = argsToMach(ctx,args)
917 if mach == None:
918 return 0
919 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
920 return 0
921
922def plugcpu(ctx,mach,args):
923 plug = args[0]
924 cpu = args[1]
925 if plug:
926 print "Adding CPU %d..." %(cpu)
927 mach.hotPlugCPU(cpu)
928 else:
929 print "Removing CPU %d..." %(cpu)
930 mach.hotUnplugCPU(cpu)
931
932def plugcpuCmd(ctx, args):
933 if (len(args) < 2):
934 print "usage: plugcpu name cpuid"
935 return 0
936 mach = argsToMach(ctx,args)
937 if mach == None:
938 return 0
939 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
940 if mach.CPUHotPlugEnabled:
941 cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
942 else:
943 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
944 return 0
945
946def unplugcpuCmd(ctx, args):
947 if (len(args) < 2):
948 print "usage: unplugcpu name cpuid"
949 return 0
950 mach = argsToMach(ctx,args)
951 if mach == None:
952 return 0
953 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
954 if mach.CPUHotPlugEnabled:
955 cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
956 else:
957 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
958 return 0
959
960def setvar(ctx,mach,args):
961 expr = 'mach.'+args[0]+' = '+args[1]
962 print "Executing",expr
963 exec expr
964
965def setvarCmd(ctx, args):
966 if (len(args) < 4):
967 print "usage: setvar [vmname|uuid] expr value"
968 return 0
969 mach = argsToMach(ctx,args)
970 if mach == None:
971 return 0
972 cmdClosedVm(ctx, mach, setvar, args[2:])
973 return 0
974
975def setvmextra(ctx,mach,args):
976 key = args[0]
977 value = args[1]
978 print "%s: setting %s to %s" %(mach.name, key, value)
979 mach.setExtraData(key, value)
980
981def setExtraDataCmd(ctx, args):
982 if (len(args) < 3):
983 print "usage: setextra [vmname|uuid|global] key <value>"
984 return 0
985 key = args[2]
986 if len(args) == 4:
987 value = args[3]
988 else:
989 value = None
990 if args[1] == 'global':
991 ctx['vb'].setExtraData(key, value)
992 return 0
993
994 mach = argsToMach(ctx,args)
995 if mach == None:
996 return 0
997 cmdClosedVm(ctx, mach, setvmextra, [key, value])
998 return 0
999
1000def printExtraKey(obj, key, value):
1001 print "%s: '%s' = '%s'" %(obj, key, value)
1002
1003def getExtraDataCmd(ctx, args):
1004 if (len(args) < 2):
1005 print "usage: getextra [vmname|uuid|global] <key>"
1006 return 0
1007 if len(args) == 3:
1008 key = args[2]
1009 else:
1010 key = None
1011
1012 if args[1] == 'global':
1013 obj = ctx['vb']
1014 else:
1015 obj = argsToMach(ctx,args)
1016 if obj == None:
1017 return 0
1018
1019 if key == None:
1020 keys = obj.getExtraDataKeys()
1021 else:
1022 keys = [ key ]
1023 for k in keys:
1024 printExtraKey(args[1], k, obj.getExtraData(k))
1025
1026 return 0
1027
1028def quitCmd(ctx, args):
1029 return 1
1030
1031def aliasCmd(ctx, args):
1032 if (len(args) == 3):
1033 aliases[args[1]] = args[2]
1034 return 0
1035
1036 for (k,v) in aliases.items():
1037 print "'%s' is an alias for '%s'" %(k,v)
1038 return 0
1039
1040def verboseCmd(ctx, args):
1041 global g_verbose
1042 g_verbose = not g_verbose
1043 return 0
1044
1045def getUSBStateString(state):
1046 if state == 0:
1047 return "NotSupported"
1048 elif state == 1:
1049 return "Unavailable"
1050 elif state == 2:
1051 return "Busy"
1052 elif state == 3:
1053 return "Available"
1054 elif state == 4:
1055 return "Held"
1056 elif state == 5:
1057 return "Captured"
1058 else:
1059 return "Unknown"
1060
1061def hostCmd(ctx, args):
1062 host = ctx['vb'].host
1063 cnt = host.processorCount
1064 print "Processors available/online: %d/%d " %(cnt,host.processorOnlineCount)
1065 for i in range(0,cnt):
1066 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
1067
1068 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
1069 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
1070 if host.Acceleration3DAvailable:
1071 print "3D acceleration available"
1072 else:
1073 print "3D acceleration NOT available"
1074
1075 print "Network interfaces:"
1076 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
1077 print " %s (%s)" %(ni.name, ni.IPAddress)
1078
1079 print "DVD drives:"
1080 for dd in ctx['global'].getArray(host, 'DVDDrives'):
1081 print " %s - %s" %(dd.name, dd.description)
1082
1083 print "Floppy drives:"
1084 for dd in ctx['global'].getArray(host, 'floppyDrives'):
1085 print " %s - %s" %(dd.name, dd.description)
1086
1087 print "USB devices:"
1088 for ud in ctx['global'].getArray(host, 'USBDevices'):
1089 printUsbHostDev(ctx,ud)
1090
1091 if ctx['perf']:
1092 for metric in ctx['perf'].query(["*"], [host]):
1093 print metric['name'], metric['values_as_string']
1094
1095 return 0
1096
1097def monitorGuestCmd(ctx, args):
1098 if (len(args) < 2):
1099 print "usage: monitorGuest name (duration)"
1100 return 0
1101 mach = argsToMach(ctx,args)
1102 if mach == None:
1103 return 0
1104 dur = 5
1105 if len(args) > 2:
1106 dur = float(args[2])
1107 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1108 return 0
1109
1110def monitorVBoxCmd(ctx, args):
1111 if (len(args) > 2):
1112 print "usage: monitorVBox (duration)"
1113 return 0
1114 dur = 5
1115 if len(args) > 1:
1116 dur = float(args[1])
1117 monitorVBox(ctx, dur)
1118 return 0
1119
1120def getAdapterType(ctx, type):
1121 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1122 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1123 return "pcnet"
1124 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1125 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1126 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1127 return "e1000"
1128 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1129 return "virtio"
1130 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1131 return None
1132 else:
1133 raise Exception("Unknown adapter type: "+type)
1134
1135
1136def portForwardCmd(ctx, args):
1137 if (len(args) != 5):
1138 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1139 return 0
1140 mach = argsToMach(ctx,args)
1141 if mach == None:
1142 return 0
1143 adapterNum = int(args[2])
1144 hostPort = int(args[3])
1145 guestPort = int(args[4])
1146 proto = "TCP"
1147 session = ctx['global'].openMachineSession(mach.id)
1148 mach = session.machine
1149
1150 adapter = mach.getNetworkAdapter(adapterNum)
1151 adapterType = getAdapterType(ctx, adapter.adapterType)
1152
1153 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1154 config = "VBoxInternal/Devices/" + adapterType + "/"
1155 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1156
1157 mach.setExtraData(config + "/Protocol", proto)
1158 mach.setExtraData(config + "/HostPort", str(hostPort))
1159 mach.setExtraData(config + "/GuestPort", str(guestPort))
1160
1161 mach.saveSettings()
1162 session.close()
1163
1164 return 0
1165
1166
1167def showLogCmd(ctx, args):
1168 if (len(args) < 2):
1169 print "usage: showLog <vm> <num>"
1170 return 0
1171 mach = argsToMach(ctx,args)
1172 if mach == None:
1173 return 0
1174
1175 log = 0;
1176 if (len(args) > 2):
1177 log = args[2];
1178
1179 uOffset = 0;
1180 while True:
1181 data = mach.readLog(log, uOffset, 1024*1024)
1182 if (len(data) == 0):
1183 break
1184 # print adds either NL or space to chunks not ending with a NL
1185 sys.stdout.write(data)
1186 uOffset += len(data)
1187
1188 return 0
1189
1190def evalCmd(ctx, args):
1191 expr = ' '.join(args[1:])
1192 try:
1193 exec expr
1194 except Exception, e:
1195 print 'failed: ',e
1196 if g_verbose:
1197 traceback.print_exc()
1198 return 0
1199
1200def reloadExtCmd(ctx, args):
1201 # maybe will want more args smartness
1202 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1203 autoCompletion(commands, ctx)
1204 return 0
1205
1206
1207def runScriptCmd(ctx, args):
1208 if (len(args) != 2):
1209 print "usage: runScript <script>"
1210 return 0
1211 try:
1212 lf = open(args[1], 'r')
1213 except IOError,e:
1214 print "cannot open:",args[1], ":",e
1215 return 0
1216
1217 try:
1218 for line in lf:
1219 done = runCommand(ctx, line)
1220 if done != 0: break
1221 except Exception,e:
1222 print "error:",e
1223 if g_verbose:
1224 traceback.print_exc()
1225 lf.close()
1226 return 0
1227
1228def sleepCmd(ctx, args):
1229 if (len(args) != 2):
1230 print "usage: sleep <secs>"
1231 return 0
1232
1233 try:
1234 time.sleep(float(args[1]))
1235 except:
1236 # to allow sleep interrupt
1237 pass
1238 return 0
1239
1240
1241def shellCmd(ctx, args):
1242 if (len(args) < 2):
1243 print "usage: shell <commands>"
1244 return 0
1245 cmd = ' '.join(args[1:])
1246
1247 try:
1248 os.system(cmd)
1249 except KeyboardInterrupt:
1250 # to allow shell command interruption
1251 pass
1252 return 0
1253
1254
1255def connectCmd(ctx, args):
1256 if (len(args) > 4):
1257 print "usage: connect [url] [username] [passwd]"
1258 return 0
1259
1260 if ctx['vb'] is not None:
1261 print "Already connected, disconnect first..."
1262 return 0
1263
1264 if (len(args) > 1):
1265 url = args[1]
1266 else:
1267 url = None
1268
1269 if (len(args) > 2):
1270 user = args[2]
1271 else:
1272 user = ""
1273
1274 if (len(args) > 3):
1275 passwd = args[3]
1276 else:
1277 passwd = ""
1278
1279 vbox = ctx['global'].platform.connect(url, user, passwd)
1280 ctx['vb'] = vbox
1281 print "Running VirtualBox version %s" %(vbox.version)
1282 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1283 return 0
1284
1285def disconnectCmd(ctx, args):
1286 if (len(args) != 1):
1287 print "usage: disconnect"
1288 return 0
1289
1290 if ctx['vb'] is None:
1291 print "Not connected yet."
1292 return 0
1293
1294 try:
1295 ctx['global'].platform.disconnect()
1296 except:
1297 ctx['vb'] = None
1298 raise
1299
1300 ctx['vb'] = None
1301 return 0
1302
1303def exportVMCmd(ctx, args):
1304 import sys
1305
1306 if len(args) < 3:
1307 print "usage: exportVm <machine> <path> <format> <license>"
1308 return 0
1309 mach = argsToMach(ctx,args)
1310 if mach is None:
1311 return 0
1312 path = args[2]
1313 if (len(args) > 3):
1314 format = args[3]
1315 else:
1316 format = "ovf-1.0"
1317 if (len(args) > 4):
1318 license = args[4]
1319 else:
1320 license = "GPL"
1321
1322 app = ctx['vb'].createAppliance()
1323 desc = mach.export(app)
1324 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1325 p = app.write(format, path)
1326 if (progressBar(ctx, p) and int(p.resultCode) == 0):
1327 print "Exported to %s in format %s" %(path, format)
1328 else:
1329 reportError(ctx,p)
1330 return 0
1331
1332# PC XT scancodes
1333scancodes = {
1334 'a': 0x1e,
1335 'b': 0x30,
1336 'c': 0x2e,
1337 'd': 0x20,
1338 'e': 0x12,
1339 'f': 0x21,
1340 'g': 0x22,
1341 'h': 0x23,
1342 'i': 0x17,
1343 'j': 0x24,
1344 'k': 0x25,
1345 'l': 0x26,
1346 'm': 0x32,
1347 'n': 0x31,
1348 'o': 0x18,
1349 'p': 0x19,
1350 'q': 0x10,
1351 'r': 0x13,
1352 's': 0x1f,
1353 't': 0x14,
1354 'u': 0x16,
1355 'v': 0x2f,
1356 'w': 0x11,
1357 'x': 0x2d,
1358 'y': 0x15,
1359 'z': 0x2c,
1360 '0': 0x0b,
1361 '1': 0x02,
1362 '2': 0x03,
1363 '3': 0x04,
1364 '4': 0x05,
1365 '5': 0x06,
1366 '6': 0x07,
1367 '7': 0x08,
1368 '8': 0x09,
1369 '9': 0x0a,
1370 ' ': 0x39,
1371 '-': 0xc,
1372 '=': 0xd,
1373 '[': 0x1a,
1374 ']': 0x1b,
1375 ';': 0x27,
1376 '\'': 0x28,
1377 ',': 0x33,
1378 '.': 0x34,
1379 '/': 0x35,
1380 '\t': 0xf,
1381 '\n': 0x1c,
1382 '`': 0x29
1383};
1384
1385extScancodes = {
1386 'ESC' : [0x01],
1387 'BKSP': [0xe],
1388 'SPACE': [0x39],
1389 'TAB': [0x0f],
1390 'CAPS': [0x3a],
1391 'ENTER': [0x1c],
1392 'LSHIFT': [0x2a],
1393 'RSHIFT': [0x36],
1394 'INS': [0xe0, 0x52],
1395 'DEL': [0xe0, 0x53],
1396 'END': [0xe0, 0x4f],
1397 'HOME': [0xe0, 0x47],
1398 'PGUP': [0xe0, 0x49],
1399 'PGDOWN': [0xe0, 0x51],
1400 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
1401 'RGUI': [0xe0, 0x5c],
1402 'LCTR': [0x1d],
1403 'RCTR': [0xe0, 0x1d],
1404 'LALT': [0x38],
1405 'RALT': [0xe0, 0x38],
1406 'APPS': [0xe0, 0x5d],
1407 'F1': [0x3b],
1408 'F2': [0x3c],
1409 'F3': [0x3d],
1410 'F4': [0x3e],
1411 'F5': [0x3f],
1412 'F6': [0x40],
1413 'F7': [0x41],
1414 'F8': [0x42],
1415 'F9': [0x43],
1416 'F10': [0x44 ],
1417 'F11': [0x57],
1418 'F12': [0x58],
1419 'UP': [0xe0, 0x48],
1420 'LEFT': [0xe0, 0x4b],
1421 'DOWN': [0xe0, 0x50],
1422 'RIGHT': [0xe0, 0x4d],
1423};
1424
1425def keyDown(ch):
1426 code = scancodes.get(ch, 0x0)
1427 if code != 0:
1428 return [code]
1429 extCode = extScancodes.get(ch, [])
1430 if len(extCode) == 0:
1431 print "bad ext",ch
1432 return extCode
1433
1434def keyUp(ch):
1435 codes = keyDown(ch)[:] # make a copy
1436 if len(codes) > 0:
1437 codes[len(codes)-1] += 0x80
1438 return codes
1439
1440def typeInGuest(console, text, delay):
1441 import time
1442 pressed = []
1443 group = False
1444 modGroupEnd = True
1445 i = 0
1446 while i < len(text):
1447 ch = text[i]
1448 i = i+1
1449 if ch == '{':
1450 # start group, all keys to be pressed at the same time
1451 group = True
1452 continue
1453 if ch == '}':
1454 # end group, release all keys
1455 for c in pressed:
1456 console.keyboard.putScancodes(keyUp(c))
1457 pressed = []
1458 group = False
1459 continue
1460 if ch == 'W':
1461 # just wait a bit
1462 time.sleep(0.3)
1463 continue
1464 if ch == '^' or ch == '|' or ch == '$' or ch == '_':
1465 if ch == '^':
1466 ch = 'LCTR'
1467 if ch == '|':
1468 ch = 'LSHIFT'
1469 if ch == '_':
1470 ch = 'LALT'
1471 if ch == '$':
1472 ch = 'LGUI'
1473 if not group:
1474 modGroupEnd = False
1475 else:
1476 if ch == '\\':
1477 if i < len(text):
1478 ch = text[i]
1479 i = i+1
1480 if ch == 'n':
1481 ch = '\n'
1482 elif ch == '&':
1483 combo = ""
1484 while i < len(text):
1485 ch = text[i]
1486 i = i+1
1487 if ch == ';':
1488 break
1489 combo += ch
1490 ch = combo
1491 modGroupEnd = True
1492 console.keyboard.putScancodes(keyDown(ch))
1493 pressed.insert(0, ch)
1494 if not group and modGroupEnd:
1495 for c in pressed:
1496 console.keyboard.putScancodes(keyUp(c))
1497 pressed = []
1498 modGroupEnd = True
1499 time.sleep(delay)
1500
1501def typeGuestCmd(ctx, args):
1502 import sys
1503
1504 if len(args) < 3:
1505 print "usage: typeGuest <machine> <text> <charDelay>"
1506 return 0
1507 mach = argsToMach(ctx,args)
1508 if mach is None:
1509 return 0
1510
1511 text = args[2]
1512
1513 if len(args) > 3:
1514 delay = float(args[3])
1515 else:
1516 delay = 0.1
1517
1518 gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
1519 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1520
1521 return 0
1522
1523def optId(verbose,id):
1524 if verbose:
1525 return ": "+id
1526 else:
1527 return ""
1528
1529def asSize(val,inBytes):
1530 if inBytes:
1531 return int(val)/(1024*1024)
1532 else:
1533 return int(val)
1534
1535def listMediumsCmd(ctx,args):
1536 if len(args) > 1:
1537 verbose = int(args[1])
1538 else:
1539 verbose = False
1540 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
1541 print "Hard disks:"
1542 for hdd in hdds:
1543 if hdd.state != ctx['global'].constants.MediumState_Created:
1544 hdd.refreshState()
1545 print " %s (%s)%s %dM [logical %dM]" %(hdd.location, hdd.format, optId(verbose,hdd.id),asSize(hdd.size, True), asSize(hdd.logicalSize, False))
1546
1547 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
1548 print "CD/DVD disks:"
1549 for dvd in dvds:
1550 if dvd.state != ctx['global'].constants.MediumState_Created:
1551 dvd.refreshState()
1552 print " %s (%s)%s %dM" %(dvd.location, dvd.format,optId(verbose,hdd.id),asSize(hdd.size, True))
1553
1554 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
1555 print "Floopy disks:"
1556 for floppy in floppys:
1557 if floppy.state != ctx['global'].constants.MediumState_Created:
1558 floppy.refreshState()
1559 print " %s (%s)%s %dM" %(floppy.location, floppy.format,optId(verbose,hdd.id), asSize(hdd.size, True))
1560
1561 return 0
1562
1563def listUsbCmd(ctx,args):
1564 if (len(args) > 1):
1565 print "usage: listUsb"
1566 return 0
1567
1568 host = ctx['vb'].host
1569 for ud in ctx['global'].getArray(host, 'USBDevices'):
1570 printHostUsbDev(ctx,ud)
1571
1572 return 0
1573
1574def findDevOfType(ctx,mach,type):
1575 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1576 for a in atts:
1577 if a.type == type:
1578 return [a.controller, a.port, a.device]
1579 return [None, 0, 0]
1580
1581def createHddCmd(ctx,args):
1582 if (len(args) < 3):
1583 print "usage: createHdd sizeM location type"
1584 return 0
1585
1586 size = int(args[1])
1587 loc = args[2]
1588 if len(args) > 3:
1589 format = args[3]
1590 else:
1591 format = "vdi"
1592
1593 hdd = ctx['vb'].createHardDisk(format, loc)
1594 progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
1595 if progressBar(ctx,progress) and hdd.id:
1596 print "created HDD at %s as %s" %(hdd.location, hdd.id)
1597 else:
1598 print "cannot create disk (file %s exist?)" %(loc)
1599 reportError(ctx,progress)
1600 return 0
1601
1602 return 0
1603
1604def registerHddCmd(ctx,args):
1605 if (len(args) < 2):
1606 print "usage: registerHdd location"
1607 return 0
1608
1609 vb = ctx['vb']
1610 loc = args[1]
1611 setImageId = False
1612 imageId = ""
1613 setParentId = False
1614 parentId = ""
1615 hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
1616 print "registered HDD as %s" %(hdd.id)
1617 return 0
1618
1619def controldevice(ctx,mach,args):
1620 [ctr,port,slot,type,id] = args
1621 mach.attachDevice(ctr, port, slot,type,id)
1622
1623def attachHddCmd(ctx,args):
1624 if (len(args) < 3):
1625 print "usage: attachHdd vm hdd controller port:slot"
1626 return 0
1627
1628 mach = argsToMach(ctx,args)
1629 if mach is None:
1630 return 0
1631 vb = ctx['vb']
1632 loc = args[2]
1633 try:
1634 hdd = vb.findHardDisk(loc)
1635 except:
1636 print "no HDD with path %s registered" %(loc)
1637 return 0
1638 if len(args) > 3:
1639 ctr = args[3]
1640 (port,slot) = args[4].split(":")
1641 else:
1642 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
1643
1644 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
1645 return 0
1646
1647def detachVmDevice(ctx,mach,args):
1648 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1649 hid = args[0]
1650 for a in atts:
1651 if a.medium:
1652 if hid == "ALL" or a.medium.id == hid:
1653 mach.detachDevice(a.controller, a.port, a.device)
1654
1655def detachMedium(ctx,mid,medium):
1656 cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
1657
1658def detachHddCmd(ctx,args):
1659 if (len(args) < 3):
1660 print "usage: detachHdd vm hdd"
1661 return 0
1662
1663 mach = argsToMach(ctx,args)
1664 if mach is None:
1665 return 0
1666 vb = ctx['vb']
1667 loc = args[2]
1668 try:
1669 hdd = vb.findHardDisk(loc)
1670 except:
1671 print "no HDD with path %s registered" %(loc)
1672 return 0
1673
1674 detachMedium(ctx,mach.id,hdd)
1675 return 0
1676
1677def unregisterHddCmd(ctx,args):
1678 if (len(args) < 2):
1679 print "usage: unregisterHdd path <vmunreg>"
1680 return 0
1681
1682 vb = ctx['vb']
1683 loc = args[1]
1684 if (len(args) > 2):
1685 vmunreg = int(args[2])
1686 else:
1687 vmunreg = 0
1688 try:
1689 hdd = vb.findHardDisk(loc)
1690 except:
1691 print "no HDD with path %s registered" %(loc)
1692 return 0
1693
1694 if vmunreg != 0:
1695 machs = ctx['global'].getArray(hdd, 'machineIds')
1696 try:
1697 for m in machs:
1698 print "Trying to detach from %s" %(m)
1699 detachMedium(ctx,m,hdd)
1700 except Exception, e:
1701 print 'failed: ',e
1702 return 0
1703 hdd.close()
1704 return 0
1705
1706def removeHddCmd(ctx,args):
1707 if (len(args) != 2):
1708 print "usage: removeHdd path"
1709 return 0
1710
1711 vb = ctx['vb']
1712 loc = args[1]
1713 try:
1714 hdd = vb.findHardDisk(loc)
1715 except:
1716 print "no HDD with path %s registered" %(loc)
1717 return 0
1718
1719 progress = hdd.deleteStorage()
1720 progressBar(ctx,progress)
1721
1722 return 0
1723
1724def registerIsoCmd(ctx,args):
1725 if (len(args) < 2):
1726 print "usage: registerIso location"
1727 return 0
1728 vb = ctx['vb']
1729 loc = args[1]
1730 id = ""
1731 iso = vb.openDVDImage(loc, id)
1732 print "registered ISO as %s" %(iso.id)
1733 return 0
1734
1735def unregisterIsoCmd(ctx,args):
1736 if (len(args) != 2):
1737 print "usage: unregisterIso path"
1738 return 0
1739
1740 vb = ctx['vb']
1741 loc = args[1]
1742 try:
1743 dvd = vb.findDVDImage(loc)
1744 except:
1745 print "no DVD with path %s registered" %(loc)
1746 return 0
1747
1748 progress = dvd.close()
1749 print "Unregistered ISO at %s" %(dvd.location)
1750
1751 return 0
1752
1753def removeIsoCmd(ctx,args):
1754 if (len(args) != 2):
1755 print "usage: removeIso path"
1756 return 0
1757
1758 vb = ctx['vb']
1759 loc = args[1]
1760 try:
1761 dvd = vb.findDVDImage(loc)
1762 except:
1763 print "no DVD with path %s registered" %(loc)
1764 return 0
1765
1766 progress = dvd.deleteStorage()
1767 if progressBar(ctx,progress):
1768 print "Removed ISO at %s" %(dvd.location)
1769 else:
1770 reportError(ctx,progress)
1771 return 0
1772
1773def attachIsoCmd(ctx,args):
1774 if (len(args) < 3):
1775 print "usage: attachIso vm iso controller port:slot"
1776 return 0
1777
1778 mach = argsToMach(ctx,args)
1779 if mach is None:
1780 return 0
1781 vb = ctx['vb']
1782 loc = args[2]
1783 try:
1784 dvd = vb.findDVDImage(loc)
1785 except:
1786 print "no DVD with path %s registered" %(loc)
1787 return 0
1788 if len(args) > 3:
1789 ctr = args[3]
1790 (port,slot) = args[4].split(":")
1791 else:
1792 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1793 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
1794 return 0
1795
1796def detachIsoCmd(ctx,args):
1797 if (len(args) < 3):
1798 print "usage: detachIso vm iso"
1799 return 0
1800
1801 mach = argsToMach(ctx,args)
1802 if mach is None:
1803 return 0
1804 vb = ctx['vb']
1805 loc = args[2]
1806 try:
1807 dvd = vb.findDVDImage(loc)
1808 except:
1809 print "no DVD with path %s registered" %(loc)
1810 return 0
1811
1812 detachMedium(ctx,mach.id,dvd)
1813 return 0
1814
1815def mountIsoCmd(ctx,args):
1816 if (len(args) < 3):
1817 print "usage: mountIso vm iso controller port:slot"
1818 return 0
1819
1820 mach = argsToMach(ctx,args)
1821 if mach is None:
1822 return 0
1823 vb = ctx['vb']
1824 loc = args[2]
1825 try:
1826 dvd = vb.findDVDImage(loc)
1827 except:
1828 print "no DVD with path %s registered" %(loc)
1829 return 0
1830
1831 if len(args) > 3:
1832 ctr = args[3]
1833 (port,slot) = args[4].split(":")
1834 else:
1835 # autodetect controller and location, just find first controller with media == DVD
1836 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1837
1838 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
1839
1840 return 0
1841
1842def unmountIsoCmd(ctx,args):
1843 if (len(args) < 2):
1844 print "usage: unmountIso vm controller port:slot"
1845 return 0
1846
1847 mach = argsToMach(ctx,args)
1848 if mach is None:
1849 return 0
1850 vb = ctx['vb']
1851
1852 if len(args) > 2:
1853 ctr = args[2]
1854 (port,slot) = args[3].split(":")
1855 else:
1856 # autodetect controller and location, just find first controller with media == DVD
1857 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1858
1859 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
1860
1861 return 0
1862
1863def attachCtr(ctx,mach,args):
1864 [name, bus, type] = args
1865 ctr = mach.addStorageController(name, bus)
1866 if type != None:
1867 ctr.controllerType = type
1868
1869def attachCtrCmd(ctx,args):
1870 if (len(args) < 4):
1871 print "usage: attachCtr vm cname bus <type>"
1872 return 0
1873
1874 if len(args) > 4:
1875 type = enumFromString(ctx,'StorageControllerType', args[4])
1876 if type == None:
1877 print "Controller type %s unknown" %(args[4])
1878 return 0
1879 else:
1880 type = None
1881
1882 mach = argsToMach(ctx,args)
1883 if mach is None:
1884 return 0
1885 bus = enumFromString(ctx,'StorageBus', args[3])
1886 if bus is None:
1887 print "Bus type %s unknown" %(args[3])
1888 return 0
1889 name = args[2]
1890 cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
1891 return 0
1892
1893def detachCtrCmd(ctx,args):
1894 if (len(args) < 3):
1895 print "usage: detachCtr vm name"
1896 return 0
1897
1898 mach = argsToMach(ctx,args)
1899 if mach is None:
1900 return 0
1901 ctr = args[2]
1902 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
1903 return 0
1904
1905def usbctr(ctx,mach,console,args):
1906 if (args[0]):
1907 console.attachUSBDevice(args[1])
1908 else:
1909 console.detachUSBDevice(args[1])
1910
1911def attachUsbCmd(ctx,args):
1912 if (len(args) < 3):
1913 print "usage: attachUsb vm deviceuid"
1914 return 0
1915
1916 mach = argsToMach(ctx,args)
1917 if mach is None:
1918 return 0
1919 dev = args[2]
1920 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
1921 return 0
1922
1923def detachUsbCmd(ctx,args):
1924 if (len(args) < 3):
1925 print "usage: detachUsb vm deviceuid"
1926 return 0
1927
1928 mach = argsToMach(ctx,args)
1929 if mach is None:
1930 return 0
1931 dev = args[2]
1932 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
1933 return 0
1934
1935
1936def guiCmd(ctx,args):
1937 if (len(args) > 1):
1938 print "usage: gui"
1939 return 0
1940
1941 binDir = ctx['global'].getBinDir()
1942
1943 vbox = os.path.join(binDir, 'VirtualBox')
1944 try:
1945 os.system(vbox)
1946 except KeyboardInterrupt:
1947 # to allow interruption
1948 pass
1949 return 0
1950
1951aliases = {'s':'start',
1952 'i':'info',
1953 'l':'list',
1954 'h':'help',
1955 'a':'alias',
1956 'q':'quit', 'exit':'quit',
1957 'tg': 'typeGuest',
1958 'v':'verbose'}
1959
1960commands = {'help':['Prints help information', helpCmd, 0],
1961 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
1962 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
1963 'removeVm':['Remove virtual machine', removeVmCmd, 0],
1964 'pause':['Pause virtual machine', pauseCmd, 0],
1965 'resume':['Resume virtual machine', resumeCmd, 0],
1966 'save':['Save execution state of virtual machine', saveCmd, 0],
1967 'stats':['Stats for virtual machine', statsCmd, 0],
1968 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1969 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1970 'list':['Shows known virtual machines', listCmd, 0],
1971 'info':['Shows info on machine', infoCmd, 0],
1972 'ginfo':['Shows info on guest', ginfoCmd, 0],
1973 'gexec':['Executes program in the guest', gexecCmd, 0],
1974 'alias':['Control aliases', aliasCmd, 0],
1975 'verbose':['Toggle verbosity', verboseCmd, 0],
1976 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1977 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1978 'quit':['Exits', quitCmd, 0],
1979 'host':['Show host information', hostCmd, 0],
1980 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
1981 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1982 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1983 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1984 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1985 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1986 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1987 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1988 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1989 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
1990 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1991 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
1992 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
1993 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
1994 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
1995 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
1996 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
1997 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
1998 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
1999 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
2000 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
2001 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
2002 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
2003 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
2004 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
2005 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
2006 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
2007 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
2008 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
2009 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
2010 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
2011 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
2012 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
2013 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
2014 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
2015 'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
2016 'detachUsb': ['Detach USB device from the VM: detachUsb win uui', detachUsbCmd, 0],
2017 'listMediums': ['List mediums known to this VBox instance', listMediumsCmd, 0],
2018 'listUsb': ['List known USB devices', listUsbCmd, 0],
2019 'gui': ['Start GUI frontend', guiCmd, 0]
2020 }
2021
2022def runCommandArgs(ctx, args):
2023 c = args[0]
2024 if aliases.get(c, None) != None:
2025 c = aliases[c]
2026 ci = commands.get(c,None)
2027 if ci == None:
2028 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
2029 return 0
2030 return ci[1](ctx, args)
2031
2032
2033def runCommand(ctx, cmd):
2034 if len(cmd) == 0: return 0
2035 args = split_no_quotes(cmd)
2036 if len(args) == 0: return 0
2037 return runCommandArgs(ctx, args)
2038
2039#
2040# To write your own custom commands to vboxshell, create
2041# file ~/.VirtualBox/shellext.py with content like
2042#
2043# def runTestCmd(ctx, args):
2044# print "Testy test", ctx['vb']
2045# return 0
2046#
2047# commands = {
2048# 'test': ['Test help', runTestCmd]
2049# }
2050# and issue reloadExt shell command.
2051# This file also will be read automatically on startup or 'reloadExt'.
2052#
2053# Also one can put shell extensions into ~/.VirtualBox/shexts and
2054# they will also be picked up, so this way one can exchange
2055# shell extensions easily.
2056def addExtsFromFile(ctx, cmds, file):
2057 if not os.path.isfile(file):
2058 return
2059 d = {}
2060 try:
2061 execfile(file, d, d)
2062 for (k,v) in d['commands'].items():
2063 if g_verbose:
2064 print "customize: adding \"%s\" - %s" %(k, v[0])
2065 cmds[k] = [v[0], v[1], file]
2066 except:
2067 print "Error loading user extensions from %s" %(file)
2068 traceback.print_exc()
2069
2070
2071def checkUserExtensions(ctx, cmds, folder):
2072 folder = str(folder)
2073 name = os.path.join(folder, "shellext.py")
2074 addExtsFromFile(ctx, cmds, name)
2075 # also check 'exts' directory for all files
2076 shextdir = os.path.join(folder, "shexts")
2077 if not os.path.isdir(shextdir):
2078 return
2079 exts = os.listdir(shextdir)
2080 for e in exts:
2081 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
2082
2083def getHomeFolder(ctx):
2084 if ctx['remote'] or ctx['vb'] is None:
2085 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
2086 else:
2087 return ctx['vb'].homeFolder
2088
2089def interpret(ctx):
2090 if ctx['remote']:
2091 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
2092 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
2093
2094 vbox = ctx['vb']
2095
2096 if vbox is not None:
2097 print "Running VirtualBox version %s" %(vbox.version)
2098 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
2099 else:
2100 ctx['perf'] = None
2101
2102 home = getHomeFolder(ctx)
2103 checkUserExtensions(ctx, commands, home)
2104
2105 hist_file=os.path.join(home, ".vboxshellhistory")
2106 autoCompletion(commands, ctx)
2107
2108 if g_hasreadline and os.path.exists(hist_file):
2109 readline.read_history_file(hist_file)
2110
2111 # to allow to print actual host information, we collect info for
2112 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
2113 if ctx['perf']:
2114 try:
2115 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
2116 except:
2117 pass
2118
2119 while True:
2120 try:
2121 cmd = raw_input("vbox> ")
2122 done = runCommand(ctx, cmd)
2123 if done != 0: break
2124 except KeyboardInterrupt:
2125 print '====== You can type quit or q to leave'
2126 break
2127 except EOFError:
2128 break;
2129 except Exception,e:
2130 print e
2131 if g_verbose:
2132 traceback.print_exc()
2133 ctx['global'].waitForEvents(0)
2134 try:
2135 # There is no need to disable metric collection. This is just an example.
2136 if ct['perf']:
2137 ctx['perf'].disable(['*'], [vbox.host])
2138 except:
2139 pass
2140 if g_hasreadline:
2141 readline.write_history_file(hist_file)
2142
2143def runCommandCb(ctx, cmd, args):
2144 args.insert(0, cmd)
2145 return runCommandArgs(ctx, args)
2146
2147def runGuestCommandCb(ctx, id, guestLambda, args):
2148 mach = machById(ctx,id)
2149 if mach == None:
2150 return 0
2151 args.insert(0, guestLambda)
2152 cmdExistingVm(ctx, mach, 'guestlambda', args)
2153 return 0
2154
2155def main(argv):
2156 style = None
2157 autopath = False
2158 argv.pop(0)
2159 while len(argv) > 0:
2160 if argv[0] == "-w":
2161 style = "WEBSERVICE"
2162 if argv[0] == "-a":
2163 autopath = True
2164 argv.pop(0)
2165
2166 if autopath:
2167 cwd = os.getcwd()
2168 vpp = os.environ.get("VBOX_PROGRAM_PATH")
2169 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
2170 vpp = cwd
2171 print "Autodetected VBOX_PROGRAM_PATH as",vpp
2172 os.environ["VBOX_PROGRAM_PATH"] = cwd
2173 sys.path.append(os.path.join(vpp, "sdk", "installer"))
2174
2175 from vboxapi import VirtualBoxManager
2176 g_virtualBoxManager = VirtualBoxManager(style, None)
2177 ctx = {'global':g_virtualBoxManager,
2178 'mgr':g_virtualBoxManager.mgr,
2179 'vb':g_virtualBoxManager.vbox,
2180 'ifaces':g_virtualBoxManager.constants,
2181 'remote':g_virtualBoxManager.remote,
2182 'type':g_virtualBoxManager.type,
2183 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
2184 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
2185 'machById': lambda id: machById(ctx,id),
2186 'argsToMach': lambda args: argsToMach(ctx,args),
2187 'progressBar': lambda p: progressBar(ctx,p),
2188 'typeInGuest': typeInGuest,
2189 '_machlist':None
2190 }
2191 interpret(ctx)
2192 g_virtualBoxManager.deinit()
2193 del g_virtualBoxManager
2194
2195if __name__ == '__main__':
2196 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