VirtualBox

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

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

python: WS bits

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