VirtualBox

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

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

grammar, show VM state as well

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