VirtualBox

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

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

VBoxShell: Windows-friendly history, style

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