VirtualBox

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

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

vboxshell: more WS stuff

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 71.0 KB
Line 
1#!/usr/bin/python
2#
3# Copyright (C) 2009-2010 Sun Microsystems, Inc.
4#
5# This file is part of VirtualBox Open Source Edition (OSE), as
6# available from http://www.215389.xyz. This file is free software;
7# you can redistribute it and/or modify it under the terms of the GNU
8# General Public License (GPL) as published by the Free Software
9# Foundation, in version 2 as it comes in the "COPYING" file of the
10# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
11# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
12#
13# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
14# Clara, CA 95054 USA or visit http://www.sun.com if you need
15# additional information or have any questions.
16#
17#################################################################################
18# This program is a simple interactive shell for VirtualBox. You can query #
19# information and issue commands from a simple command line. #
20# #
21# It also provides you with examples on how to use VirtualBox's Python API. #
22# This shell is even somewhat documented, supports TAB-completion and #
23# history if you have Python readline installed. #
24# #
25# Finally, shell allows arbitrary custom extensions, just create #
26# .VirtualBox/shexts/ and drop your extensions there. #
27# Enjoy. #
28################################################################################
29
30import os,sys
31import traceback
32import shlex
33import time
34import re
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(string,color):
156 if not g_hascolors:
157 return string
158 global term_colors
159 col = term_colors.get(color,None)
160 if col:
161 return col+str(string)+'\033[0m'
162 else:
163 return string
164
165if g_hasreadline:
166 class CompleterNG(rlcompleter.Completer):
167 def __init__(self, dic, ctx):
168 self.ctx = ctx
169 return rlcompleter.Completer.__init__(self,dic)
170
171 def complete(self, text, state):
172 """
173 taken from:
174 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
175 """
176 if text == "":
177 return ['\t',None][state]
178 else:
179 return rlcompleter.Completer.complete(self,text,state)
180
181 def global_matches(self, text):
182 """
183 Compute matches when text is a simple name.
184 Return a list of all names currently defined
185 in self.namespace that match.
186 """
187
188 matches = []
189 n = len(text)
190
191 for list in [ self.namespace ]:
192 for word in list:
193 if word[:n] == text:
194 matches.append(word)
195
196
197 try:
198 for m in getMachines(self.ctx, False, True):
199 # although it has autoconversion, we need to cast
200 # explicitly for subscripts to work
201 word = re.sub("(?<!\\\\) ", "\\ ", str(m.name))
202 if word[:n] == text:
203 matches.append(word)
204 word = str(m.id)
205 if word[0] == '{':
206 word = word[1:-1]
207 if word[:n] == text:
208 matches.append(word)
209 except Exception,e:
210 printErr(e)
211 if g_verbose:
212 traceback.print_exc()
213
214 return matches
215
216def autoCompletion(commands, ctx):
217 if not g_hasreadline:
218 return
219
220 comps = {}
221 for (k,v) in commands.items():
222 comps[k] = None
223 completer = CompleterNG(comps, ctx)
224 readline.set_completer(completer.complete)
225 delims = readline.get_completer_delims()
226 readline.set_completer_delims(re.sub("[\\.]", "", delims)) # remove some of the delimiters
227 # OSX need it
228 readline.parse_and_bind("set editing-mode emacs")
229 if platform.system() == 'Darwin':
230 # see http://www.certif.com/spec_help/readline.html
231 readline.parse_and_bind ("bind ^I rl_complete")
232 readline.parse_and_bind ("bind ^W ed-delete-prev-word")
233 # Doesn't work well
234 # readline.parse_and_bind ("bind ^R em-inc-search-prev")
235 readline.parse_and_bind("tab: complete")
236
237
238g_verbose = False
239
240def split_no_quotes(s):
241 return shlex.split(s)
242
243def progressBar(ctx,p,wait=1000):
244 try:
245 while not p.completed:
246 print "%s %%\r" %(colored(str(p.percent),'red')),
247 sys.stdout.flush()
248 p.waitForCompletion(wait)
249 ctx['global'].waitForEvents(0)
250 return 1
251 except KeyboardInterrupt:
252 print "Interrupted."
253 if p.cancelable:
254 print "Canceling task..."
255 p.cancel()
256 return 0
257
258def printErr(ctx,e):
259 print colored(str(e), 'red')
260
261def reportError(ctx,progress):
262 ei = progress.errorInfo
263 if ei:
264 print colored("Error in %s: %s" %(ei.component, ei.text), 'red')
265
266def colCat(ctx,str):
267 return colored(str, 'magenta')
268
269def colVm(ctx,vm):
270 return colored(vm, 'blue')
271
272def createVm(ctx,name,kind,base):
273 mgr = ctx['mgr']
274 vb = ctx['vb']
275 mach = vb.createMachine(name, kind, base, "", False)
276 mach.saveSettings()
277 print "created machine with UUID",mach.id
278 vb.registerMachine(mach)
279 # update cache
280 getMachines(ctx, True)
281
282def removeVm(ctx,mach):
283 mgr = ctx['mgr']
284 vb = ctx['vb']
285 id = mach.id
286 print "removing machine ",mach.name,"with UUID",id
287 cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
288 mach = vb.unregisterMachine(id)
289 if mach:
290 mach.deleteSettings()
291 # update cache
292 getMachines(ctx, True)
293
294def startVm(ctx,mach,type):
295 mgr = ctx['mgr']
296 vb = ctx['vb']
297 perf = ctx['perf']
298 session = mgr.getSessionObject(vb)
299 uuid = mach.id
300 progress = vb.openRemoteSession(session, uuid, type, "")
301 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
302 # we ignore exceptions to allow starting VM even if
303 # perf collector cannot be started
304 if perf:
305 try:
306 perf.setup(['*'], [mach], 10, 15)
307 except Exception,e:
308 printErr(ctx, e)
309 if g_verbose:
310 traceback.print_exc()
311 # if session not opened, close doesn't make sense
312 session.close()
313 else:
314 reportError(ctx,progress)
315
316class CachedMach:
317 def __init__(self, mach):
318 self.name = mach.name
319 self.id = mach.id
320
321def cacheMachines(ctx,list):
322 result = []
323 for m in list:
324 elem = CachedMach(m)
325 result.append(elem)
326 return result
327
328def getMachines(ctx, invalidate = False, simple=False):
329 if ctx['vb'] is not None:
330 if ctx['_machlist'] is None or invalidate:
331 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
332 ctx['_machlistsimple'] = cacheMachines(ctx,ctx['_machlist'])
333 if simple:
334 return ctx['_machlistsimple']
335 else:
336 return ctx['_machlist']
337 else:
338 return []
339
340def asState(var):
341 if var:
342 return colored('on', 'green')
343 else:
344 return colored('off', 'green')
345
346def asFlag(var):
347 if var:
348 return 'yes'
349 else:
350 return 'no'
351
352def perfStats(ctx,mach):
353 if not ctx['perf']:
354 return
355 for metric in ctx['perf'].query(["*"], [mach]):
356 print metric['name'], metric['values_as_string']
357
358def guestExec(ctx, machine, console, cmds):
359 exec cmds
360
361def monitorGuest(ctx, machine, console, dur):
362 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
363 console.registerCallback(cb)
364 if dur == -1:
365 # not infinity, but close enough
366 dur = 100000
367 try:
368 end = time.time() + dur
369 while time.time() < end:
370 ctx['global'].waitForEvents(500)
371 # We need to catch all exceptions here, otherwise callback will never be unregistered
372 except:
373 pass
374 console.unregisterCallback(cb)
375
376
377def monitorVBox(ctx, dur):
378 vbox = ctx['vb']
379 isMscom = (ctx['global'].type == 'MSCOM')
380 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
381 vbox.registerCallback(cb)
382 if dur == -1:
383 # not infinity, but close enough
384 dur = 100000
385 try:
386 end = time.time() + dur
387 while time.time() < end:
388 ctx['global'].waitForEvents(500)
389 # We need to catch all exceptions here, otherwise callback will never be unregistered
390 except:
391 pass
392 vbox.unregisterCallback(cb)
393
394
395def takeScreenshot(ctx,console,args):
396 from PIL import Image
397 display = console.display
398 if len(args) > 0:
399 f = args[0]
400 else:
401 f = "/tmp/screenshot.png"
402 if len(args) > 3:
403 screen = int(args[3])
404 else:
405 screen = 0
406 (fbw, fbh, fbbpp) = display.getScreenResolution(screen)
407 if len(args) > 1:
408 w = int(args[1])
409 else:
410 w = fbw
411 if len(args) > 2:
412 h = int(args[2])
413 else:
414 h = fbh
415
416 print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
417 data = display.takeScreenShotToArray(screen, w,h)
418 size = (w,h)
419 mode = "RGBA"
420 im = Image.frombuffer(mode, size, str(data), "raw", mode, 0, 1)
421 im.save(f, "PNG")
422
423
424def teleport(ctx,session,console,args):
425 if args[0].find(":") == -1:
426 print "Use host:port format for teleport target"
427 return
428 (host,port) = args[0].split(":")
429 if len(args) > 1:
430 passwd = args[1]
431 else:
432 passwd = ""
433
434 if len(args) > 2:
435 maxDowntime = int(args[2])
436 else:
437 maxDowntime = 250
438
439 port = int(port)
440 print "Teleporting to %s:%d..." %(host,port)
441 progress = console.teleport(host, port, passwd, maxDowntime)
442 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
443 print "Success!"
444 else:
445 reportError(ctx,progress)
446
447
448def guestStats(ctx,console,args):
449 guest = console.guest
450 # we need to set up guest statistics
451 if len(args) > 0 :
452 update = args[0]
453 else:
454 update = 1
455 if guest.statisticsUpdateInterval != update:
456 guest.statisticsUpdateInterval = update
457 try:
458 time.sleep(float(update)+0.1)
459 except:
460 # to allow sleep interruption
461 pass
462 all_stats = ctx['ifaces'].all_values('GuestStatisticType')
463 cpu = 0
464 for s in all_stats.keys():
465 try:
466 val = guest.getStatistic( cpu, all_stats[s])
467 print "%s: %d" %(s, val)
468 except:
469 # likely not implemented
470 pass
471
472def plugCpu(ctx,machine,session,args):
473 cpu = int(args[0])
474 print "Adding CPU %d..." %(cpu)
475 machine.hotPlugCPU(cpu)
476
477def unplugCpu(ctx,machine,session,args):
478 cpu = int(args[0])
479 print "Removing CPU %d..." %(cpu)
480 machine.hotUnplugCPU(cpu)
481
482def mountIso(ctx,machine,session,args):
483 machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
484 machine.saveSettings()
485
486def cond(c,v1,v2):
487 if c:
488 return v1
489 else:
490 return v2
491
492def printHostUsbDev(ctx,ud):
493 print " %s: %s (vendorId=%d productId=%d serial=%s) %s" %(ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber,asEnumElem(ctx, 'USBDeviceState', ud.state))
494
495def printUsbDev(ctx,ud):
496 print " %s: %s (vendorId=%d productId=%d serial=%s)" %(ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber)
497
498def printSf(ctx,sf):
499 print " name=%s host=%s %s %s" %(sf.name, sf.hostPath, cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))
500
501def ginfo(ctx,console, args):
502 guest = console.guest
503 if guest.additionsActive:
504 vers = int(str(guest.additionsVersion))
505 print "Additions active, version %d.%d" %(vers >> 16, vers & 0xffff)
506 print "Support seamless: %s" %(asFlag(guest.supportsSeamless))
507 print "Support graphics: %s" %(asFlag(guest.supportsGraphics))
508 print "Baloon size: %d" %(guest.memoryBalloonSize)
509 print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
510 else:
511 print "No additions"
512 usbs = ctx['global'].getArray(console, 'USBDevices')
513 print "Attached USB:"
514 for ud in usbs:
515 printUsbDev(ctx,ud)
516 rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
517 print "Remote USB:"
518 for ud in rusbs:
519 printHostUsbDev(ctx,ud)
520 print "Transient shared folders:"
521 sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
522 for sf in sfs:
523 printSf(ctx,sf)
524
525def cmdExistingVm(ctx,mach,cmd,args):
526 mgr=ctx['mgr']
527 vb=ctx['vb']
528 session = mgr.getSessionObject(vb)
529 uuid = mach.id
530 try:
531 progress = vb.openExistingSession(session, uuid)
532 except Exception,e:
533 printErr(ctx, "Session to '%s' not open: %s" %(mach.name,str(e)))
534 if g_verbose:
535 traceback.print_exc()
536 return
537 if str(session.state) != str(ctx['ifaces'].SessionState_Open):
538 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
539 return
540 # this could be an example how to handle local only (i.e. unavailable
541 # in Webservices) functionality
542 if ctx['remote'] and cmd == 'some_local_only_command':
543 print 'Trying to use local only functionality, ignored'
544 return
545 console=session.console
546 ops={'pause': lambda: console.pause(),
547 'resume': lambda: console.resume(),
548 'powerdown': lambda: console.powerDown(),
549 'powerbutton': lambda: console.powerButton(),
550 'stats': lambda: perfStats(ctx, mach),
551 'guest': lambda: guestExec(ctx, mach, console, args),
552 'ginfo': lambda: ginfo(ctx, console, args),
553 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
554 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
555 'save': lambda: progressBar(ctx,console.saveState()),
556 'screenshot': lambda: takeScreenshot(ctx,console,args),
557 'teleport': lambda: teleport(ctx,session,console,args),
558 'gueststats': lambda: guestStats(ctx, console, args),
559 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
560 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
561 'mountiso': lambda: mountIso(ctx, session.machine, session, args),
562 }
563 try:
564 ops[cmd]()
565 except Exception, e:
566 printErr(ctx,e)
567 if g_verbose:
568 traceback.print_exc()
569
570 session.close()
571
572
573def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
574 session = ctx['global'].openMachineSession(mach.id)
575 mach = session.machine
576 try:
577 cmd(ctx, mach, args)
578 except Exception, e:
579 printErr(ctx,e)
580 if g_verbose:
581 traceback.print_exc()
582 if save:
583 mach.saveSettings()
584 session.close()
585
586def machById(ctx,id):
587 mach = None
588 for m in getMachines(ctx):
589 if m.name == id:
590 mach = m
591 break
592 mid = str(m.id)
593 if mid[0] == '{':
594 mid = mid[1:-1]
595 if mid == id:
596 mach = m
597 break
598 return mach
599
600def argsToMach(ctx,args):
601 if len(args) < 2:
602 print "usage: %s [vmname|uuid]" %(args[0])
603 return None
604 id = args[1]
605 m = machById(ctx, id)
606 if m == None:
607 print "Machine '%s' is unknown, use list command to find available machines" %(id)
608 return m
609
610def helpSingleCmd(cmd,h,sp):
611 if sp != 0:
612 spec = " [ext from "+sp+"]"
613 else:
614 spec = ""
615 print " %s: %s%s" %(colored(cmd,'blue'),h,spec)
616
617def helpCmd(ctx, args):
618 if len(args) == 1:
619 print "Help page:"
620 names = commands.keys()
621 names.sort()
622 for i in names:
623 helpSingleCmd(i, commands[i][0], commands[i][2])
624 else:
625 cmd = args[1]
626 c = commands.get(cmd)
627 if c == None:
628 print "Command '%s' not known" %(cmd)
629 else:
630 helpSingleCmd(cmd, c[0], c[2])
631 return 0
632
633def asEnumElem(ctx,enum,elem):
634 all = ctx['ifaces'].all_values(enum)
635 for e in all.keys():
636 if str(elem) == str(all[e]):
637 return colored(e, 'green')
638 return colored("<unknown>", 'green')
639
640def enumFromString(ctx,enum,str):
641 all = ctx['ifaces'].all_values(enum)
642 return all.get(str, None)
643
644def listCmd(ctx, args):
645 for m in getMachines(ctx, True):
646 if m.teleporterEnabled:
647 tele = "[T] "
648 else:
649 tele = " "
650 print "%sMachine '%s' [%s], machineState=%s, sessionState=%s" %(tele,colVm(ctx,m.name),m.id,asEnumElem(ctx, "MachineState", m.state), asEnumElem(ctx,"SessionState", m.sessionState))
651 return 0
652
653def infoCmd(ctx,args):
654 if (len(args) < 2):
655 print "usage: info [vmname|uuid]"
656 return 0
657 mach = argsToMach(ctx,args)
658 if mach == None:
659 return 0
660 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
661 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
662 print " Name [name]: %s" %(colVm(ctx,mach.name))
663 print " Description [description]: %s" %(mach.description)
664 print " ID [n/a]: %s" %(mach.id)
665 print " OS Type [via OSTypeId]: %s" %(os.description)
666 print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
667 print
668 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
669 print " RAM [memorySize]: %dM" %(mach.memorySize)
670 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
671 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
672 print
673 print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
674 print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
675 print
676 if mach.teleporterEnabled:
677 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
678 print
679 bios = mach.BIOSSettings
680 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
681 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
682 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
683 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
684 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
685 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
686 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
687 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
688
689 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
690 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
691
692 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
693 if mach.audioAdapter.enabled:
694 print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
695 if mach.USBController.enabled:
696 print " USB [via USBController]: high speed %s" %(asState(mach.USBController.enabledEhci))
697 print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
698
699 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
700 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
701 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
702 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
703
704 controllers = ctx['global'].getArray(mach, 'storageControllers')
705 if controllers:
706 print
707 print colCat(ctx," Controllers:")
708 for controller in controllers:
709 print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
710
711 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
712 if attaches:
713 print
714 print colCat(ctx," Media:")
715 for a in attaches:
716 print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
717 m = a.medium
718 if a.type == ctx['global'].constants.DeviceType_HardDisk:
719 print " HDD:"
720 print " Id: %s" %(m.id)
721 print " Location: %s" %(m.location)
722 print " Name: %s" %(m.name)
723 print " Format: %s" %(m.format)
724
725 if a.type == ctx['global'].constants.DeviceType_DVD:
726 print " DVD:"
727 if m:
728 print " Id: %s" %(m.id)
729 print " Name: %s" %(m.name)
730 if m.hostDrive:
731 print " Host DVD %s" %(m.location)
732 if a.passthrough:
733 print " [passthrough mode]"
734 else:
735 print " Virtual image at %s" %(m.location)
736 print " Size: %s" %(m.size)
737
738 if a.type == ctx['global'].constants.DeviceType_Floppy:
739 print " Floppy:"
740 if m:
741 print " Id: %s" %(m.id)
742 print " Name: %s" %(m.name)
743 if m.hostDrive:
744 print " Host floppy %s" %(m.location)
745 else:
746 print " Virtual image at %s" %(m.location)
747 print " Size: %s" %(m.size)
748
749 print
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 ctx['wsinfo'] = [url, user, passwd]
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 reconnectCmd(ctx, args):
1385 if ctx['wsinfo'] is None:
1386 print "Never connected..."
1387 return 0
1388
1389 try:
1390 ctx['global'].platform.disconnect()
1391 except:
1392 pass
1393
1394 [url,user,passwd] = ctx['wsinfo']
1395 ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
1396 print "Running VirtualBox version %s" %(ctx['vb'].version)
1397 return 0
1398
1399def exportVMCmd(ctx, args):
1400 import sys
1401
1402 if len(args) < 3:
1403 print "usage: exportVm <machine> <path> <format> <license>"
1404 return 0
1405 mach = argsToMach(ctx,args)
1406 if mach is None:
1407 return 0
1408 path = args[2]
1409 if (len(args) > 3):
1410 format = args[3]
1411 else:
1412 format = "ovf-1.0"
1413 if (len(args) > 4):
1414 license = args[4]
1415 else:
1416 license = "GPL"
1417
1418 app = ctx['vb'].createAppliance()
1419 desc = mach.export(app)
1420 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1421 p = app.write(format, path)
1422 if (progressBar(ctx, p) and int(p.resultCode) == 0):
1423 print "Exported to %s in format %s" %(path, format)
1424 else:
1425 reportError(ctx,p)
1426 return 0
1427
1428# PC XT scancodes
1429scancodes = {
1430 'a': 0x1e,
1431 'b': 0x30,
1432 'c': 0x2e,
1433 'd': 0x20,
1434 'e': 0x12,
1435 'f': 0x21,
1436 'g': 0x22,
1437 'h': 0x23,
1438 'i': 0x17,
1439 'j': 0x24,
1440 'k': 0x25,
1441 'l': 0x26,
1442 'm': 0x32,
1443 'n': 0x31,
1444 'o': 0x18,
1445 'p': 0x19,
1446 'q': 0x10,
1447 'r': 0x13,
1448 's': 0x1f,
1449 't': 0x14,
1450 'u': 0x16,
1451 'v': 0x2f,
1452 'w': 0x11,
1453 'x': 0x2d,
1454 'y': 0x15,
1455 'z': 0x2c,
1456 '0': 0x0b,
1457 '1': 0x02,
1458 '2': 0x03,
1459 '3': 0x04,
1460 '4': 0x05,
1461 '5': 0x06,
1462 '6': 0x07,
1463 '7': 0x08,
1464 '8': 0x09,
1465 '9': 0x0a,
1466 ' ': 0x39,
1467 '-': 0xc,
1468 '=': 0xd,
1469 '[': 0x1a,
1470 ']': 0x1b,
1471 ';': 0x27,
1472 '\'': 0x28,
1473 ',': 0x33,
1474 '.': 0x34,
1475 '/': 0x35,
1476 '\t': 0xf,
1477 '\n': 0x1c,
1478 '`': 0x29
1479};
1480
1481extScancodes = {
1482 'ESC' : [0x01],
1483 'BKSP': [0xe],
1484 'SPACE': [0x39],
1485 'TAB': [0x0f],
1486 'CAPS': [0x3a],
1487 'ENTER': [0x1c],
1488 'LSHIFT': [0x2a],
1489 'RSHIFT': [0x36],
1490 'INS': [0xe0, 0x52],
1491 'DEL': [0xe0, 0x53],
1492 'END': [0xe0, 0x4f],
1493 'HOME': [0xe0, 0x47],
1494 'PGUP': [0xe0, 0x49],
1495 'PGDOWN': [0xe0, 0x51],
1496 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
1497 'RGUI': [0xe0, 0x5c],
1498 'LCTR': [0x1d],
1499 'RCTR': [0xe0, 0x1d],
1500 'LALT': [0x38],
1501 'RALT': [0xe0, 0x38],
1502 'APPS': [0xe0, 0x5d],
1503 'F1': [0x3b],
1504 'F2': [0x3c],
1505 'F3': [0x3d],
1506 'F4': [0x3e],
1507 'F5': [0x3f],
1508 'F6': [0x40],
1509 'F7': [0x41],
1510 'F8': [0x42],
1511 'F9': [0x43],
1512 'F10': [0x44 ],
1513 'F11': [0x57],
1514 'F12': [0x58],
1515 'UP': [0xe0, 0x48],
1516 'LEFT': [0xe0, 0x4b],
1517 'DOWN': [0xe0, 0x50],
1518 'RIGHT': [0xe0, 0x4d],
1519};
1520
1521def keyDown(ch):
1522 code = scancodes.get(ch, 0x0)
1523 if code != 0:
1524 return [code]
1525 extCode = extScancodes.get(ch, [])
1526 if len(extCode) == 0:
1527 print "bad ext",ch
1528 return extCode
1529
1530def keyUp(ch):
1531 codes = keyDown(ch)[:] # make a copy
1532 if len(codes) > 0:
1533 codes[len(codes)-1] += 0x80
1534 return codes
1535
1536def typeInGuest(console, text, delay):
1537 import time
1538 pressed = []
1539 group = False
1540 modGroupEnd = True
1541 i = 0
1542 while i < len(text):
1543 ch = text[i]
1544 i = i+1
1545 if ch == '{':
1546 # start group, all keys to be pressed at the same time
1547 group = True
1548 continue
1549 if ch == '}':
1550 # end group, release all keys
1551 for c in pressed:
1552 console.keyboard.putScancodes(keyUp(c))
1553 pressed = []
1554 group = False
1555 continue
1556 if ch == 'W':
1557 # just wait a bit
1558 time.sleep(0.3)
1559 continue
1560 if ch == '^' or ch == '|' or ch == '$' or ch == '_':
1561 if ch == '^':
1562 ch = 'LCTR'
1563 if ch == '|':
1564 ch = 'LSHIFT'
1565 if ch == '_':
1566 ch = 'LALT'
1567 if ch == '$':
1568 ch = 'LGUI'
1569 if not group:
1570 modGroupEnd = False
1571 else:
1572 if ch == '\\':
1573 if i < len(text):
1574 ch = text[i]
1575 i = i+1
1576 if ch == 'n':
1577 ch = '\n'
1578 elif ch == '&':
1579 combo = ""
1580 while i < len(text):
1581 ch = text[i]
1582 i = i+1
1583 if ch == ';':
1584 break
1585 combo += ch
1586 ch = combo
1587 modGroupEnd = True
1588 console.keyboard.putScancodes(keyDown(ch))
1589 pressed.insert(0, ch)
1590 if not group and modGroupEnd:
1591 for c in pressed:
1592 console.keyboard.putScancodes(keyUp(c))
1593 pressed = []
1594 modGroupEnd = True
1595 time.sleep(delay)
1596
1597def typeGuestCmd(ctx, args):
1598 import sys
1599
1600 if len(args) < 3:
1601 print "usage: typeGuest <machine> <text> <charDelay>"
1602 return 0
1603 mach = argsToMach(ctx,args)
1604 if mach is None:
1605 return 0
1606
1607 text = args[2]
1608
1609 if len(args) > 3:
1610 delay = float(args[3])
1611 else:
1612 delay = 0.1
1613
1614 gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
1615 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1616
1617 return 0
1618
1619def optId(verbose,id):
1620 if verbose:
1621 return ": "+id
1622 else:
1623 return ""
1624
1625def asSize(val,inBytes):
1626 if inBytes:
1627 return int(val)/(1024*1024)
1628 else:
1629 return int(val)
1630
1631def listMediaCmd(ctx,args):
1632 if len(args) > 1:
1633 verbose = int(args[1])
1634 else:
1635 verbose = False
1636 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
1637 print "Hard disks:"
1638 for hdd in hdds:
1639 if hdd.state != ctx['global'].constants.MediumState_Created:
1640 hdd.refreshState()
1641 print " %s (%s)%s %dM [logical %dM]" %(hdd.location, hdd.format, optId(verbose,hdd.id),asSize(hdd.size, True), asSize(hdd.logicalSize, False))
1642
1643 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
1644 print "CD/DVD disks:"
1645 for dvd in dvds:
1646 if dvd.state != ctx['global'].constants.MediumState_Created:
1647 dvd.refreshState()
1648 print " %s (%s)%s %dM" %(dvd.location, dvd.format,optId(verbose,hdd.id),asSize(hdd.size, True))
1649
1650 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
1651 print "Floopy disks:"
1652 for floppy in floppys:
1653 if floppy.state != ctx['global'].constants.MediumState_Created:
1654 floppy.refreshState()
1655 print " %s (%s)%s %dM" %(floppy.location, floppy.format,optId(verbose,hdd.id), asSize(hdd.size, True))
1656
1657 return 0
1658
1659def listUsbCmd(ctx,args):
1660 if (len(args) > 1):
1661 print "usage: listUsb"
1662 return 0
1663
1664 host = ctx['vb'].host
1665 for ud in ctx['global'].getArray(host, 'USBDevices'):
1666 printHostUsbDev(ctx,ud)
1667
1668 return 0
1669
1670def findDevOfType(ctx,mach,type):
1671 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1672 for a in atts:
1673 if a.type == type:
1674 return [a.controller, a.port, a.device]
1675 return [None, 0, 0]
1676
1677def createHddCmd(ctx,args):
1678 if (len(args) < 3):
1679 print "usage: createHdd sizeM location type"
1680 return 0
1681
1682 size = int(args[1])
1683 loc = args[2]
1684 if len(args) > 3:
1685 format = args[3]
1686 else:
1687 format = "vdi"
1688
1689 hdd = ctx['vb'].createHardDisk(format, loc)
1690 progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
1691 if progressBar(ctx,progress) and hdd.id:
1692 print "created HDD at %s as %s" %(hdd.location, hdd.id)
1693 else:
1694 print "cannot create disk (file %s exist?)" %(loc)
1695 reportError(ctx,progress)
1696 return 0
1697
1698 return 0
1699
1700def registerHddCmd(ctx,args):
1701 if (len(args) < 2):
1702 print "usage: registerHdd location"
1703 return 0
1704
1705 vb = ctx['vb']
1706 loc = args[1]
1707 setImageId = False
1708 imageId = ""
1709 setParentId = False
1710 parentId = ""
1711 hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
1712 print "registered HDD as %s" %(hdd.id)
1713 return 0
1714
1715def controldevice(ctx,mach,args):
1716 [ctr,port,slot,type,id] = args
1717 mach.attachDevice(ctr, port, slot,type,id)
1718
1719def attachHddCmd(ctx,args):
1720 if (len(args) < 3):
1721 print "usage: attachHdd vm hdd controller port:slot"
1722 return 0
1723
1724 mach = argsToMach(ctx,args)
1725 if mach is None:
1726 return 0
1727 vb = ctx['vb']
1728 loc = args[2]
1729 try:
1730 hdd = vb.findHardDisk(loc)
1731 except:
1732 print "no HDD with path %s registered" %(loc)
1733 return 0
1734 if len(args) > 3:
1735 ctr = args[3]
1736 (port,slot) = args[4].split(":")
1737 else:
1738 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
1739
1740 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
1741 return 0
1742
1743def detachVmDevice(ctx,mach,args):
1744 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1745 hid = args[0]
1746 for a in atts:
1747 if a.medium:
1748 if hid == "ALL" or a.medium.id == hid:
1749 mach.detachDevice(a.controller, a.port, a.device)
1750
1751def detachMedium(ctx,mid,medium):
1752 cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
1753
1754def detachHddCmd(ctx,args):
1755 if (len(args) < 3):
1756 print "usage: detachHdd vm hdd"
1757 return 0
1758
1759 mach = argsToMach(ctx,args)
1760 if mach is None:
1761 return 0
1762 vb = ctx['vb']
1763 loc = args[2]
1764 try:
1765 hdd = vb.findHardDisk(loc)
1766 except:
1767 print "no HDD with path %s registered" %(loc)
1768 return 0
1769
1770 detachMedium(ctx,mach.id,hdd)
1771 return 0
1772
1773def unregisterHddCmd(ctx,args):
1774 if (len(args) < 2):
1775 print "usage: unregisterHdd path <vmunreg>"
1776 return 0
1777
1778 vb = ctx['vb']
1779 loc = args[1]
1780 if (len(args) > 2):
1781 vmunreg = int(args[2])
1782 else:
1783 vmunreg = 0
1784 try:
1785 hdd = vb.findHardDisk(loc)
1786 except:
1787 print "no HDD with path %s registered" %(loc)
1788 return 0
1789
1790 if vmunreg != 0:
1791 machs = ctx['global'].getArray(hdd, 'machineIds')
1792 try:
1793 for m in machs:
1794 print "Trying to detach from %s" %(m)
1795 detachMedium(ctx,m,hdd)
1796 except Exception, e:
1797 print 'failed: ',e
1798 return 0
1799 hdd.close()
1800 return 0
1801
1802def removeHddCmd(ctx,args):
1803 if (len(args) != 2):
1804 print "usage: removeHdd path"
1805 return 0
1806
1807 vb = ctx['vb']
1808 loc = args[1]
1809 try:
1810 hdd = vb.findHardDisk(loc)
1811 except:
1812 print "no HDD with path %s registered" %(loc)
1813 return 0
1814
1815 progress = hdd.deleteStorage()
1816 progressBar(ctx,progress)
1817
1818 return 0
1819
1820def registerIsoCmd(ctx,args):
1821 if (len(args) < 2):
1822 print "usage: registerIso location"
1823 return 0
1824 vb = ctx['vb']
1825 loc = args[1]
1826 id = ""
1827 iso = vb.openDVDImage(loc, id)
1828 print "registered ISO as %s" %(iso.id)
1829 return 0
1830
1831def unregisterIsoCmd(ctx,args):
1832 if (len(args) != 2):
1833 print "usage: unregisterIso path"
1834 return 0
1835
1836 vb = ctx['vb']
1837 loc = args[1]
1838 try:
1839 dvd = vb.findDVDImage(loc)
1840 except:
1841 print "no DVD with path %s registered" %(loc)
1842 return 0
1843
1844 progress = dvd.close()
1845 print "Unregistered ISO at %s" %(dvd.location)
1846
1847 return 0
1848
1849def removeIsoCmd(ctx,args):
1850 if (len(args) != 2):
1851 print "usage: removeIso path"
1852 return 0
1853
1854 vb = ctx['vb']
1855 loc = args[1]
1856 try:
1857 dvd = vb.findDVDImage(loc)
1858 except:
1859 print "no DVD with path %s registered" %(loc)
1860 return 0
1861
1862 progress = dvd.deleteStorage()
1863 if progressBar(ctx,progress):
1864 print "Removed ISO at %s" %(dvd.location)
1865 else:
1866 reportError(ctx,progress)
1867 return 0
1868
1869def attachIsoCmd(ctx,args):
1870 if (len(args) < 3):
1871 print "usage: attachIso vm iso controller port:slot"
1872 return 0
1873
1874 mach = argsToMach(ctx,args)
1875 if mach is None:
1876 return 0
1877 vb = ctx['vb']
1878 loc = args[2]
1879 try:
1880 dvd = vb.findDVDImage(loc)
1881 except:
1882 print "no DVD with path %s registered" %(loc)
1883 return 0
1884 if len(args) > 3:
1885 ctr = args[3]
1886 (port,slot) = args[4].split(":")
1887 else:
1888 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1889 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
1890 return 0
1891
1892def detachIsoCmd(ctx,args):
1893 if (len(args) < 3):
1894 print "usage: detachIso vm iso"
1895 return 0
1896
1897 mach = argsToMach(ctx,args)
1898 if mach is None:
1899 return 0
1900 vb = ctx['vb']
1901 loc = args[2]
1902 try:
1903 dvd = vb.findDVDImage(loc)
1904 except:
1905 print "no DVD with path %s registered" %(loc)
1906 return 0
1907
1908 detachMedium(ctx,mach.id,dvd)
1909 return 0
1910
1911def mountIsoCmd(ctx,args):
1912 if (len(args) < 3):
1913 print "usage: mountIso vm iso controller port:slot"
1914 return 0
1915
1916 mach = argsToMach(ctx,args)
1917 if mach is None:
1918 return 0
1919 vb = ctx['vb']
1920 loc = args[2]
1921 try:
1922 dvd = vb.findDVDImage(loc)
1923 except:
1924 print "no DVD with path %s registered" %(loc)
1925 return 0
1926
1927 if len(args) > 3:
1928 ctr = args[3]
1929 (port,slot) = args[4].split(":")
1930 else:
1931 # autodetect controller and location, just find first controller with media == DVD
1932 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1933
1934 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
1935
1936 return 0
1937
1938def unmountIsoCmd(ctx,args):
1939 if (len(args) < 2):
1940 print "usage: unmountIso vm controller port:slot"
1941 return 0
1942
1943 mach = argsToMach(ctx,args)
1944 if mach is None:
1945 return 0
1946 vb = ctx['vb']
1947
1948 if len(args) > 2:
1949 ctr = args[2]
1950 (port,slot) = args[3].split(":")
1951 else:
1952 # autodetect controller and location, just find first controller with media == DVD
1953 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1954
1955 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
1956
1957 return 0
1958
1959def attachCtr(ctx,mach,args):
1960 [name, bus, type] = args
1961 ctr = mach.addStorageController(name, bus)
1962 if type != None:
1963 ctr.controllerType = type
1964
1965def attachCtrCmd(ctx,args):
1966 if (len(args) < 4):
1967 print "usage: attachCtr vm cname bus <type>"
1968 return 0
1969
1970 if len(args) > 4:
1971 type = enumFromString(ctx,'StorageControllerType', args[4])
1972 if type == None:
1973 print "Controller type %s unknown" %(args[4])
1974 return 0
1975 else:
1976 type = None
1977
1978 mach = argsToMach(ctx,args)
1979 if mach is None:
1980 return 0
1981 bus = enumFromString(ctx,'StorageBus', args[3])
1982 if bus is None:
1983 print "Bus type %s unknown" %(args[3])
1984 return 0
1985 name = args[2]
1986 cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
1987 return 0
1988
1989def detachCtrCmd(ctx,args):
1990 if (len(args) < 3):
1991 print "usage: detachCtr vm name"
1992 return 0
1993
1994 mach = argsToMach(ctx,args)
1995 if mach is None:
1996 return 0
1997 ctr = args[2]
1998 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
1999 return 0
2000
2001def usbctr(ctx,mach,console,args):
2002 if (args[0]):
2003 console.attachUSBDevice(args[1])
2004 else:
2005 console.detachUSBDevice(args[1])
2006
2007def attachUsbCmd(ctx,args):
2008 if (len(args) < 3):
2009 print "usage: attachUsb vm deviceuid"
2010 return 0
2011
2012 mach = argsToMach(ctx,args)
2013 if mach is None:
2014 return 0
2015 dev = args[2]
2016 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
2017 return 0
2018
2019def detachUsbCmd(ctx,args):
2020 if (len(args) < 3):
2021 print "usage: detachUsb vm deviceuid"
2022 return 0
2023
2024 mach = argsToMach(ctx,args)
2025 if mach is None:
2026 return 0
2027 dev = args[2]
2028 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
2029 return 0
2030
2031
2032def guiCmd(ctx,args):
2033 if (len(args) > 1):
2034 print "usage: gui"
2035 return 0
2036
2037 binDir = ctx['global'].getBinDir()
2038
2039 vbox = os.path.join(binDir, 'VirtualBox')
2040 try:
2041 os.system(vbox)
2042 except KeyboardInterrupt:
2043 # to allow interruption
2044 pass
2045 return 0
2046
2047def shareFolderCmd(ctx,args):
2048 if (len(args) < 4):
2049 print "usage: shareFolder vm path name <writable> <persistent>"
2050 return 0
2051
2052 mach = argsToMach(ctx,args)
2053 if mach is None:
2054 return 0
2055 path = args[2]
2056 name = args[3]
2057 writable = False
2058 persistent = False
2059 if len(args) > 4:
2060 for a in args[4:]:
2061 if a == 'writable':
2062 writable = True
2063 if a == 'persistent':
2064 persistent = True
2065 if persistent:
2066 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.createSharedFolder(name, path, writable), [])
2067 else:
2068 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.createSharedFolder(name, path, writable)])
2069 return 0
2070
2071def unshareFolderCmd(ctx,args):
2072 if (len(args) < 3):
2073 print "usage: unshareFolder vm name"
2074 return 0
2075
2076 mach = argsToMach(ctx,args)
2077 if mach is None:
2078 return 0
2079 name = args[2]
2080 found = False
2081 for sf in ctx['global'].getArray(mach, 'sharedFolders'):
2082 if sf.name == name:
2083 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeSharedFolder(name), [])
2084 found = True
2085 break
2086 if not found:
2087 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.removeSharedFolder(name)])
2088 return 0
2089
2090aliases = {'s':'start',
2091 'i':'info',
2092 'l':'list',
2093 'h':'help',
2094 'a':'alias',
2095 'q':'quit', 'exit':'quit',
2096 'tg': 'typeGuest',
2097 'v':'verbose'}
2098
2099commands = {'help':['Prints help information', helpCmd, 0],
2100 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
2101 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
2102 'removeVm':['Remove virtual machine', removeVmCmd, 0],
2103 'pause':['Pause virtual machine', pauseCmd, 0],
2104 'resume':['Resume virtual machine', resumeCmd, 0],
2105 'save':['Save execution state of virtual machine', saveCmd, 0],
2106 'stats':['Stats for virtual machine', statsCmd, 0],
2107 'powerdown':['Power down virtual machine', powerdownCmd, 0],
2108 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
2109 'list':['Shows known virtual machines', listCmd, 0],
2110 'info':['Shows info on machine', infoCmd, 0],
2111 'ginfo':['Shows info on guest', ginfoCmd, 0],
2112 'gexec':['Executes program in the guest', gexecCmd, 0],
2113 'alias':['Control aliases', aliasCmd, 0],
2114 'verbose':['Toggle verbosity', verboseCmd, 0],
2115 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
2116 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
2117 'quit':['Exits', quitCmd, 0],
2118 'host':['Show host information', hostCmd, 0],
2119 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
2120 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
2121 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
2122 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
2123 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
2124 'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
2125 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
2126 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
2127 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
2128 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
2129 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
2130 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
2131 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
2132 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
2133 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
2134 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
2135 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
2136 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
2137 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
2138 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
2139 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
2140 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
2141 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
2142 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
2143 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
2144 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
2145 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
2146 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
2147 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
2148 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
2149 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
2150 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
2151 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
2152 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
2153 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
2154 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
2155 'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
2156 'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
2157 'listMedia': ['List media known to this VBox instance', listMediaCmd, 0],
2158 'listUsb': ['List known USB devices', listUsbCmd, 0],
2159 'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
2160 'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
2161 'gui': ['Start GUI frontend', guiCmd, 0],
2162 'colors':['Toggle colors', colorsCmd, 0],
2163 }
2164
2165def runCommandArgs(ctx, args):
2166 c = args[0]
2167 if aliases.get(c, None) != None:
2168 c = aliases[c]
2169 ci = commands.get(c,None)
2170 if ci == None:
2171 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
2172 return 0
2173 if ctx['remote'] and ctx['vb'] is None:
2174 if c not in ['connect', 'reconnect', 'help', 'quit']:
2175 print "First connect to remote server with %s command." %(colored('connect', 'blue'))
2176 return 0
2177 return ci[1](ctx, args)
2178
2179
2180def runCommand(ctx, cmd):
2181 if len(cmd) == 0: return 0
2182 args = split_no_quotes(cmd)
2183 if len(args) == 0: return 0
2184 return runCommandArgs(ctx, args)
2185
2186#
2187# To write your own custom commands to vboxshell, create
2188# file ~/.VirtualBox/shellext.py with content like
2189#
2190# def runTestCmd(ctx, args):
2191# print "Testy test", ctx['vb']
2192# return 0
2193#
2194# commands = {
2195# 'test': ['Test help', runTestCmd]
2196# }
2197# and issue reloadExt shell command.
2198# This file also will be read automatically on startup or 'reloadExt'.
2199#
2200# Also one can put shell extensions into ~/.VirtualBox/shexts and
2201# they will also be picked up, so this way one can exchange
2202# shell extensions easily.
2203def addExtsFromFile(ctx, cmds, file):
2204 if not os.path.isfile(file):
2205 return
2206 d = {}
2207 try:
2208 execfile(file, d, d)
2209 for (k,v) in d['commands'].items():
2210 if g_verbose:
2211 print "customize: adding \"%s\" - %s" %(k, v[0])
2212 cmds[k] = [v[0], v[1], file]
2213 except:
2214 print "Error loading user extensions from %s" %(file)
2215 traceback.print_exc()
2216
2217
2218def checkUserExtensions(ctx, cmds, folder):
2219 folder = str(folder)
2220 name = os.path.join(folder, "shellext.py")
2221 addExtsFromFile(ctx, cmds, name)
2222 # also check 'exts' directory for all files
2223 shextdir = os.path.join(folder, "shexts")
2224 if not os.path.isdir(shextdir):
2225 return
2226 exts = os.listdir(shextdir)
2227 for e in exts:
2228 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
2229
2230def getHomeFolder(ctx):
2231 if ctx['remote'] or ctx['vb'] is None:
2232 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
2233 else:
2234 return ctx['vb'].homeFolder
2235
2236def interpret(ctx):
2237 if ctx['remote']:
2238 commands['connect'] = ["Connect to remote VBox instance: connect http://server:18083 user password", connectCmd, 0]
2239 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
2240 commands['reconnect'] = ["Reconnect to remote VBox instance", reconnectCmd, 0]
2241 ctx['wsinfo'] = ["http://localhost:18083", "", ""]
2242
2243 vbox = ctx['vb']
2244
2245 if vbox is not None:
2246 print "Running VirtualBox version %s" %(vbox.version)
2247 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
2248 else:
2249 ctx['perf'] = None
2250
2251 home = getHomeFolder(ctx)
2252 checkUserExtensions(ctx, commands, home)
2253 if platform.system() == 'Windows':
2254 global g_hascolors
2255 g_hascolors = False
2256 hist_file=os.path.join(home, ".vboxshellhistory")
2257 autoCompletion(commands, ctx)
2258
2259 if g_hasreadline and os.path.exists(hist_file):
2260 readline.read_history_file(hist_file)
2261
2262 # to allow to print actual host information, we collect info for
2263 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
2264 if ctx['perf']:
2265 try:
2266 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
2267 except:
2268 pass
2269
2270 while True:
2271 try:
2272 cmd = raw_input(colored("vbox> ", 'blue'))
2273 done = runCommand(ctx, cmd)
2274 if done != 0: break
2275 except KeyboardInterrupt:
2276 print '====== You can type quit or q to leave'
2277 except EOFError:
2278 break
2279 except Exception,e:
2280 printErr(ctx,e)
2281 if g_verbose:
2282 traceback.print_exc()
2283 ctx['global'].waitForEvents(0)
2284 try:
2285 # There is no need to disable metric collection. This is just an example.
2286 if ct['perf']:
2287 ctx['perf'].disable(['*'], [vbox.host])
2288 except:
2289 pass
2290 if g_hasreadline:
2291 readline.write_history_file(hist_file)
2292
2293def runCommandCb(ctx, cmd, args):
2294 args.insert(0, cmd)
2295 return runCommandArgs(ctx, args)
2296
2297def runGuestCommandCb(ctx, id, guestLambda, args):
2298 mach = machById(ctx,id)
2299 if mach == None:
2300 return 0
2301 args.insert(0, guestLambda)
2302 cmdExistingVm(ctx, mach, 'guestlambda', args)
2303 return 0
2304
2305def main(argv):
2306 style = None
2307 autopath = False
2308 argv.pop(0)
2309 while len(argv) > 0:
2310 if argv[0] == "-w":
2311 style = "WEBSERVICE"
2312 if argv[0] == "-a":
2313 autopath = True
2314 argv.pop(0)
2315
2316 if autopath:
2317 cwd = os.getcwd()
2318 vpp = os.environ.get("VBOX_PROGRAM_PATH")
2319 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
2320 vpp = cwd
2321 print "Autodetected VBOX_PROGRAM_PATH as",vpp
2322 os.environ["VBOX_PROGRAM_PATH"] = cwd
2323 sys.path.append(os.path.join(vpp, "sdk", "installer"))
2324
2325 from vboxapi import VirtualBoxManager
2326 g_virtualBoxManager = VirtualBoxManager(style, None)
2327 ctx = {'global':g_virtualBoxManager,
2328 'mgr':g_virtualBoxManager.mgr,
2329 'vb':g_virtualBoxManager.vbox,
2330 'ifaces':g_virtualBoxManager.constants,
2331 'remote':g_virtualBoxManager.remote,
2332 'type':g_virtualBoxManager.type,
2333 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
2334 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
2335 'machById': lambda id: machById(ctx,id),
2336 'argsToMach': lambda args: argsToMach(ctx,args),
2337 'progressBar': lambda p: progressBar(ctx,p),
2338 'typeInGuest': typeInGuest,
2339 '_machlist':None
2340 }
2341 interpret(ctx)
2342 g_virtualBoxManager.deinit()
2343 del g_virtualBoxManager
2344
2345if __name__ == '__main__':
2346 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