VirtualBox

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

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

VBoxShell: print guest process output

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