VirtualBox

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

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

VBoxShell: no colors on Windows

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