VirtualBox

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

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

VBoxShell: replaces with None in tuples returned with nat's commannds.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 83.6 KB
Line 
1#!/usr/bin/python
2#
3# Copyright (C) 2009-2010 Oracle Corporation
4#
5# This file is part of VirtualBox Open Source Edition (OSE), as
6# available from http://www.virtualbox.org. This file is free software;
7# you can redistribute it and/or modify it under the terms of the GNU
8# General Public License (GPL) as published by the Free Software
9# Foundation, in version 2 as it comes in the "COPYING" file of the
10# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
11# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
12#
13#################################################################################
14# This program is a simple interactive shell for VirtualBox. You can query #
15# information and issue commands from a simple command line. #
16# #
17# It also provides you with examples on how to use VirtualBox's Python API. #
18# This shell is even somewhat documented, supports TAB-completion and #
19# history if you have Python readline installed. #
20# #
21# Finally, shell allows arbitrary custom extensions, just create #
22# .VirtualBox/shexts/ and drop your extensions there. #
23# Enjoy. #
24################################################################################
25
26import os,sys
27import traceback
28import shlex
29import time
30import re
31import platform
32
33# Simple implementation of IConsoleCallback, one can use it as skeleton
34# for custom implementations
35class GuestMonitor:
36 def __init__(self, mach):
37 self.mach = mach
38
39 def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
40 print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
41 def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
42 print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, needsHostCursor)
43
44 def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
45 print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
46
47 def onStateChange(self, state):
48 print "%s: onStateChange state=%d" %(self.mach.name, state)
49
50 def onAdditionsStateChange(self):
51 print "%s: onAdditionsStateChange" %(self.mach.name)
52
53 def onNetworkAdapterChange(self, adapter):
54 print "%s: onNetworkAdapterChange" %(self.mach.name)
55
56 def onSerialPortChange(self, port):
57 print "%s: onSerialPortChange" %(self.mach.name)
58
59 def onParallelPortChange(self, port):
60 print "%s: onParallelPortChange" %(self.mach.name)
61
62 def onStorageControllerChange(self):
63 print "%s: onStorageControllerChange" %(self.mach.name)
64
65 def onMediumChange(self, attachment):
66 print "%s: onMediumChange" %(self.mach.name)
67
68 def onVRDPServerChange(self):
69 print "%s: onVRDPServerChange" %(self.mach.name)
70
71 def onUSBControllerChange(self):
72 print "%s: onUSBControllerChange" %(self.mach.name)
73
74 def onUSBDeviceStateChange(self, device, attached, error):
75 print "%s: onUSBDeviceStateChange" %(self.mach.name)
76
77 def onSharedFolderChange(self, scope):
78 print "%s: onSharedFolderChange" %(self.mach.name)
79
80 def onRuntimeError(self, fatal, id, message):
81 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
82
83 def onCanShowWindow(self):
84 print "%s: onCanShowWindow" %(self.mach.name)
85 return True
86
87 def onShowWindow(self, winId):
88 print "%s: onShowWindow: %d" %(self.mach.name, winId)
89
90class VBoxMonitor:
91 def __init__(self, params):
92 self.vbox = params[0]
93 self.isMscom = params[1]
94 pass
95
96 def onMachineStateChange(self, id, state):
97 print "onMachineStateChange: %s %d" %(id, state)
98
99 def onMachineDataChange(self,id):
100 print "onMachineDataChange: %s" %(id)
101
102 def onExtraDataCanChange(self, id, key, value):
103 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
104 # Witty COM bridge thinks if someone wishes to return tuple, hresult
105 # is one of values we want to return
106 if self.isMscom:
107 return "", 0, True
108 else:
109 return True, ""
110
111 def onExtraDataChange(self, id, key, value):
112 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
113
114 def onMediaRegistered(self, id, type, registered):
115 print "onMediaRegistered: %s" %(id)
116
117 def onMachineRegistered(self, id, registred):
118 print "onMachineRegistered: %s" %(id)
119
120 def onSessionStateChange(self, id, state):
121 print "onSessionStateChange: %s %d" %(id, state)
122
123 def onSnapshotTaken(self, mach, id):
124 print "onSnapshotTaken: %s %s" %(mach, id)
125
126 def onSnapshotDeleted(self, mach, id):
127 print "onSnapshotDeleted: %s %s" %(mach, id)
128
129 def onSnapshotChange(self, mach, id):
130 print "onSnapshotChange: %s %s" %(mach, id)
131
132 def onGuestPropertyChange(self, id, name, newValue, flags):
133 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
134
135g_hasreadline = True
136try:
137 import readline
138 import rlcompleter
139except:
140 g_hasreadline = False
141
142
143g_hascolors = True
144term_colors = {
145 'red':'\033[31m',
146 'blue':'\033[94m',
147 'green':'\033[92m',
148 'yellow':'\033[93m',
149 'magenta':'\033[35m'
150 }
151def colored(string,color):
152 if not g_hascolors:
153 return string
154 global term_colors
155 col = term_colors.get(color,None)
156 if col:
157 return col+str(string)+'\033[0m'
158 else:
159 return string
160
161if g_hasreadline:
162 class CompleterNG(rlcompleter.Completer):
163 def __init__(self, dic, ctx):
164 self.ctx = ctx
165 return rlcompleter.Completer.__init__(self,dic)
166
167 def complete(self, text, state):
168 """
169 taken from:
170 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
171 """
172 if text == "":
173 return ['\t',None][state]
174 else:
175 return rlcompleter.Completer.complete(self,text,state)
176
177 def global_matches(self, text):
178 """
179 Compute matches when text is a simple name.
180 Return a list of all names currently defined
181 in self.namespace that match.
182 """
183
184 matches = []
185 n = len(text)
186
187 for list in [ self.namespace ]:
188 for word in list:
189 if word[:n] == text:
190 matches.append(word)
191
192
193 try:
194 for m in getMachines(self.ctx, False, True):
195 # although it has autoconversion, we need to cast
196 # explicitly for subscripts to work
197 word = re.sub("(?<!\\\\) ", "\\ ", str(m.name))
198 if word[:n] == text:
199 matches.append(word)
200 word = str(m.id)
201 if word[0] == '{':
202 word = word[1:-1]
203 if word[:n] == text:
204 matches.append(word)
205 except Exception,e:
206 printErr(e)
207 if g_verbose:
208 traceback.print_exc()
209
210 return matches
211
212def autoCompletion(commands, ctx):
213 if not g_hasreadline:
214 return
215
216 comps = {}
217 for (k,v) in commands.items():
218 comps[k] = None
219 completer = CompleterNG(comps, ctx)
220 readline.set_completer(completer.complete)
221 delims = readline.get_completer_delims()
222 readline.set_completer_delims(re.sub("[\\.]", "", delims)) # remove some of the delimiters
223 readline.parse_and_bind("set editing-mode emacs")
224 # OSX need it
225 if platform.system() == 'Darwin':
226 # see http://www.certif.com/spec_help/readline.html
227 readline.parse_and_bind ("bind ^I rl_complete")
228 readline.parse_and_bind ("bind ^W ed-delete-prev-word")
229 # Doesn't work well
230 # readline.parse_and_bind ("bind ^R em-inc-search-prev")
231 readline.parse_and_bind("tab: complete")
232
233
234g_verbose = False
235
236def split_no_quotes(s):
237 return shlex.split(s)
238
239def progressBar(ctx,p,wait=1000):
240 try:
241 while not p.completed:
242 print "%s %%\r" %(colored(str(p.percent),'red')),
243 sys.stdout.flush()
244 p.waitForCompletion(wait)
245 ctx['global'].waitForEvents(0)
246 return 1
247 except KeyboardInterrupt:
248 print "Interrupted."
249 if p.cancelable:
250 print "Canceling task..."
251 p.cancel()
252 return 0
253
254def printErr(ctx,e):
255 print colored(str(e), 'red')
256
257def reportError(ctx,progress):
258 ei = progress.errorInfo
259 if ei:
260 print colored("Error in %s: %s" %(ei.component, ei.text), 'red')
261
262def colCat(ctx,str):
263 return colored(str, 'magenta')
264
265def colVm(ctx,vm):
266 return colored(vm, 'blue')
267
268def colPath(ctx,vm):
269 return colored(vm, 'green')
270
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 try:
527 session = ctx['global'].openMachineSession(mach.id)
528 except Exception,e:
529 printErr(ctx, "Session to '%s' not open: %s" %(mach.name,str(e)))
530 if g_verbose:
531 traceback.print_exc()
532 return
533 if session.state != ctx['ifaces'].SessionState_Open:
534 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
535 session.close()
536 return
537 # this could be an example how to handle local only (i.e. unavailable
538 # in Webservices) functionality
539 if ctx['remote'] and cmd == 'some_local_only_command':
540 print 'Trying to use local only functionality, ignored'
541 session.close()
542 return
543 console=session.console
544 ops={'pause': lambda: console.pause(),
545 'resume': lambda: console.resume(),
546 'powerdown': lambda: console.powerDown(),
547 'powerbutton': lambda: console.powerButton(),
548 'stats': lambda: perfStats(ctx, mach),
549 'guest': lambda: guestExec(ctx, mach, console, args),
550 'ginfo': lambda: ginfo(ctx, console, args),
551 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
552 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
553 'save': lambda: progressBar(ctx,console.saveState()),
554 'screenshot': lambda: takeScreenshot(ctx,console,args),
555 'teleport': lambda: teleport(ctx,session,console,args),
556 'gueststats': lambda: guestStats(ctx, console, args),
557 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
558 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
559 'mountiso': lambda: mountIso(ctx, session.machine, session, args),
560 }
561 try:
562 ops[cmd]()
563 except Exception, e:
564 printErr(ctx,e)
565 if g_verbose:
566 traceback.print_exc()
567
568 session.close()
569
570
571def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
572 session = ctx['global'].openMachineSession(mach.id)
573 mach = session.machine
574 try:
575 cmd(ctx, mach, args)
576 except Exception, e:
577 save = False
578 printErr(ctx,e)
579 if g_verbose:
580 traceback.print_exc()
581 if save:
582 mach.saveSettings()
583 ctx['global'].closeMachineSession(session)
584
585
586def cmdAnyVm(ctx,mach,cmd, args=[],save=False):
587 session = ctx['global'].openMachineSession(mach.id)
588 mach = session.machine
589 try:
590 cmd(ctx, mach, session.console, args)
591 except Exception, e:
592 save = False;
593 printErr(ctx,e)
594 if g_verbose:
595 traceback.print_exc()
596 if save:
597 mach.saveSettings()
598 ctx['global'].closeMachineSession(session)
599
600def machById(ctx,id):
601 mach = None
602 for m in getMachines(ctx):
603 if m.name == id:
604 mach = m
605 break
606 mid = str(m.id)
607 if mid[0] == '{':
608 mid = mid[1:-1]
609 if mid == id:
610 mach = m
611 break
612 return mach
613
614def argsToMach(ctx,args):
615 if len(args) < 2:
616 print "usage: %s [vmname|uuid]" %(args[0])
617 return None
618 id = args[1]
619 m = machById(ctx, id)
620 if m == None:
621 print "Machine '%s' is unknown, use list command to find available machines" %(id)
622 return m
623
624def helpSingleCmd(cmd,h,sp):
625 if sp != 0:
626 spec = " [ext from "+sp+"]"
627 else:
628 spec = ""
629 print " %s: %s%s" %(colored(cmd,'blue'),h,spec)
630
631def helpCmd(ctx, args):
632 if len(args) == 1:
633 print "Help page:"
634 names = commands.keys()
635 names.sort()
636 for i in names:
637 helpSingleCmd(i, commands[i][0], commands[i][2])
638 else:
639 cmd = args[1]
640 c = commands.get(cmd)
641 if c == None:
642 print "Command '%s' not known" %(cmd)
643 else:
644 helpSingleCmd(cmd, c[0], c[2])
645 return 0
646
647def asEnumElem(ctx,enum,elem):
648 all = ctx['ifaces'].all_values(enum)
649 for e in all.keys():
650 if str(elem) == str(all[e]):
651 return colored(e, 'green')
652 return colored("<unknown>", 'green')
653
654def enumFromString(ctx,enum,str):
655 all = ctx['ifaces'].all_values(enum)
656 return all.get(str, None)
657
658def listCmd(ctx, args):
659 for m in getMachines(ctx, True):
660 if m.teleporterEnabled:
661 tele = "[T] "
662 else:
663 tele = " "
664 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))
665 return 0
666
667def infoCmd(ctx,args):
668 if (len(args) < 2):
669 print "usage: info [vmname|uuid]"
670 return 0
671 mach = argsToMach(ctx,args)
672 if mach == None:
673 return 0
674 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
675 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
676 print " Name [name]: %s" %(colVm(ctx,mach.name))
677 print " Description [description]: %s" %(mach.description)
678 print " ID [n/a]: %s" %(mach.id)
679 print " OS Type [via OSTypeId]: %s" %(os.description)
680 print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
681 print
682 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
683 print " RAM [memorySize]: %dM" %(mach.memorySize)
684 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
685 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
686 print
687 print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
688 print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
689 print
690 if mach.teleporterEnabled:
691 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
692 print
693 bios = mach.BIOSSettings
694 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
695 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
696 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
697 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
698 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
699 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
700 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
701 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
702
703 print " Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
704 print " Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
705
706 print " Use universal time [RTCUseUTC]: %s" %(asState(mach.RTCUseUTC))
707 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
708 if mach.audioAdapter.enabled:
709 print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
710 if mach.USBController.enabled:
711 print " USB [via USBController]: high speed %s" %(asState(mach.USBController.enabledEhci))
712 print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
713
714 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
715 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
716 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
717 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
718
719 print
720 print colCat(ctx," I/O subsystem info:")
721 print " I/O manager [ioMgr]: %s" %(asEnumElem(ctx, "IoMgrType", mach.ioMgr))
722 print " I/O backend [ioBackend]: %s" %(asEnumElem(ctx, "IoBackendType", mach.ioBackend))
723 print " Cache enabled [ioCacheEnabled]: %s" %(asState(mach.ioCacheEnabled))
724 print " Cache size [ioCacheSize]: %dM" %(mach.ioCacheSize)
725 print " Bandwidth limit [ioBandwidthMax]: %dM/s" %(mach.ioBandwidthMax)
726
727 controllers = ctx['global'].getArray(mach, 'storageControllers')
728 if controllers:
729 print
730 print colCat(ctx," Controllers:")
731 for controller in controllers:
732 print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
733
734 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
735 if attaches:
736 print
737 print colCat(ctx," Media:")
738 for a in attaches:
739 print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
740 m = a.medium
741 if a.type == ctx['global'].constants.DeviceType_HardDisk:
742 print " HDD:"
743 print " Id: %s" %(m.id)
744 print " Location: %s" %(m.location)
745 print " Name: %s" %(m.name)
746 print " Format: %s" %(m.format)
747
748 if a.type == ctx['global'].constants.DeviceType_DVD:
749 print " DVD:"
750 if m:
751 print " Id: %s" %(m.id)
752 print " Name: %s" %(m.name)
753 if m.hostDrive:
754 print " Host DVD %s" %(m.location)
755 if a.passthrough:
756 print " [passthrough mode]"
757 else:
758 print " Virtual image at %s" %(m.location)
759 print " Size: %s" %(m.size)
760
761 if a.type == ctx['global'].constants.DeviceType_Floppy:
762 print " Floppy:"
763 if m:
764 print " Id: %s" %(m.id)
765 print " Name: %s" %(m.name)
766 if m.hostDrive:
767 print " Host floppy %s" %(m.location)
768 else:
769 print " Virtual image at %s" %(m.location)
770 print " Size: %s" %(m.size)
771
772 print
773 print colCat(ctx," Shared folders:")
774 for sf in ctx['global'].getArray(mach, 'sharedFolders'):
775 printSf(ctx,sf)
776
777 return 0
778
779def startCmd(ctx, args):
780 mach = argsToMach(ctx,args)
781 if mach == None:
782 return 0
783 if len(args) > 2:
784 type = args[2]
785 else:
786 type = "gui"
787 startVm(ctx, mach, type)
788 return 0
789
790def createVmCmd(ctx, args):
791 if (len(args) < 3 or len(args) > 4):
792 print "usage: createvm name ostype <basefolder>"
793 return 0
794 name = args[1]
795 oskind = args[2]
796 if len(args) == 4:
797 base = args[3]
798 else:
799 base = ''
800 try:
801 ctx['vb'].getGuestOSType(oskind)
802 except Exception, e:
803 print 'Unknown OS type:',oskind
804 return 0
805 createVm(ctx, name, oskind, base)
806 return 0
807
808def ginfoCmd(ctx,args):
809 if (len(args) < 2):
810 print "usage: ginfo [vmname|uuid]"
811 return 0
812 mach = argsToMach(ctx,args)
813 if mach == None:
814 return 0
815 cmdExistingVm(ctx, mach, 'ginfo', '')
816 return 0
817
818def execInGuest(ctx,console,args,env):
819 if len(args) < 1:
820 print "exec in guest needs at least program name"
821 return
822 user = ""
823 passwd = ""
824 tmo = 0
825 guest = console.guest
826 # shall contain program name as argv[0]
827 gargs = args
828 print "executing %s with args %s" %(args[0], gargs)
829 (progress, pid) = guest.executeProcess(args[0], 0, gargs, env, "", "", "", user, passwd, tmo)
830 print "executed with pid %d" %(pid)
831 if pid != 0:
832 try:
833 while True:
834 data = guest.getProcessOutput(pid, 0, 1000, 4096)
835 if data and len(data) > 0:
836 sys.stdout.write(data)
837 continue
838 progress.waitForCompletion(100)
839 ctx['global'].waitForEvents(0)
840 if progress.completed:
841 break
842
843 except KeyboardInterrupt:
844 print "Interrupted."
845 if progress.cancelable:
846 progress.cancel()
847 return 0
848 else:
849 reportError(ctx, progress)
850
851def gexecCmd(ctx,args):
852 if (len(args) < 2):
853 print "usage: gexec [vmname|uuid] command args"
854 return 0
855 mach = argsToMach(ctx,args)
856 if mach == None:
857 return 0
858 gargs = args[2:]
859 env = [] # ["DISPLAY=:0"]
860 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env))
861 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
862 return 0
863
864def gcatCmd(ctx,args):
865 if (len(args) < 2):
866 print "usage: gcat [vmname|uuid] local_file | guestProgram, such as gcat linux /home/nike/.bashrc | sh -c 'cat >'"
867 return 0
868 mach = argsToMach(ctx,args)
869 if mach == None:
870 return 0
871 gargs = args[2:]
872 env = []
873 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env))
874 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
875 return 0
876
877
878def removeVmCmd(ctx, args):
879 mach = argsToMach(ctx,args)
880 if mach == None:
881 return 0
882 removeVm(ctx, mach)
883 return 0
884
885def pauseCmd(ctx, args):
886 mach = argsToMach(ctx,args)
887 if mach == None:
888 return 0
889 cmdExistingVm(ctx, mach, 'pause', '')
890 return 0
891
892def powerdownCmd(ctx, args):
893 mach = argsToMach(ctx,args)
894 if mach == None:
895 return 0
896 cmdExistingVm(ctx, mach, 'powerdown', '')
897 return 0
898
899def powerbuttonCmd(ctx, args):
900 mach = argsToMach(ctx,args)
901 if mach == None:
902 return 0
903 cmdExistingVm(ctx, mach, 'powerbutton', '')
904 return 0
905
906def resumeCmd(ctx, args):
907 mach = argsToMach(ctx,args)
908 if mach == None:
909 return 0
910 cmdExistingVm(ctx, mach, 'resume', '')
911 return 0
912
913def saveCmd(ctx, args):
914 mach = argsToMach(ctx,args)
915 if mach == None:
916 return 0
917 cmdExistingVm(ctx, mach, 'save', '')
918 return 0
919
920def statsCmd(ctx, args):
921 mach = argsToMach(ctx,args)
922 if mach == None:
923 return 0
924 cmdExistingVm(ctx, mach, 'stats', '')
925 return 0
926
927def guestCmd(ctx, args):
928 if (len(args) < 3):
929 print "usage: guest name commands"
930 return 0
931 mach = argsToMach(ctx,args)
932 if mach == None:
933 return 0
934 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
935 return 0
936
937def screenshotCmd(ctx, args):
938 if (len(args) < 2):
939 print "usage: screenshot vm <file> <width> <height> <monitor>"
940 return 0
941 mach = argsToMach(ctx,args)
942 if mach == None:
943 return 0
944 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
945 return 0
946
947def teleportCmd(ctx, args):
948 if (len(args) < 3):
949 print "usage: teleport name host:port <password>"
950 return 0
951 mach = argsToMach(ctx,args)
952 if mach == None:
953 return 0
954 cmdExistingVm(ctx, mach, 'teleport', args[2:])
955 return 0
956
957def portalsettings(ctx,mach,args):
958 enabled = args[0]
959 mach.teleporterEnabled = enabled
960 if enabled:
961 port = args[1]
962 passwd = args[2]
963 mach.teleporterPort = port
964 mach.teleporterPassword = passwd
965
966def openportalCmd(ctx, args):
967 if (len(args) < 3):
968 print "usage: openportal name port <password>"
969 return 0
970 mach = argsToMach(ctx,args)
971 if mach == None:
972 return 0
973 port = int(args[2])
974 if (len(args) > 3):
975 passwd = args[3]
976 else:
977 passwd = ""
978 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
979 cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
980 startVm(ctx, mach, "gui")
981 return 0
982
983def closeportalCmd(ctx, args):
984 if (len(args) < 2):
985 print "usage: closeportal name"
986 return 0
987 mach = argsToMach(ctx,args)
988 if mach == None:
989 return 0
990 if mach.teleporterEnabled:
991 cmdClosedVm(ctx, mach, portalsettings, [False])
992 return 0
993
994def gueststatsCmd(ctx, args):
995 if (len(args) < 2):
996 print "usage: gueststats name <check interval>"
997 return 0
998 mach = argsToMach(ctx,args)
999 if mach == None:
1000 return 0
1001 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
1002 return 0
1003
1004def plugcpu(ctx,mach,args):
1005 plug = args[0]
1006 cpu = args[1]
1007 if plug:
1008 print "Adding CPU %d..." %(cpu)
1009 mach.hotPlugCPU(cpu)
1010 else:
1011 print "Removing CPU %d..." %(cpu)
1012 mach.hotUnplugCPU(cpu)
1013
1014def plugcpuCmd(ctx, args):
1015 if (len(args) < 2):
1016 print "usage: plugcpu 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, [True, int(args[2])])
1024 else:
1025 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
1026 return 0
1027
1028def unplugcpuCmd(ctx, args):
1029 if (len(args) < 2):
1030 print "usage: unplugcpu name cpuid"
1031 return 0
1032 mach = argsToMach(ctx,args)
1033 if mach == None:
1034 return 0
1035 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
1036 if mach.CPUHotPlugEnabled:
1037 cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
1038 else:
1039 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
1040 return 0
1041
1042def setvar(ctx,mach,args):
1043 expr = 'mach.'+args[0]+' = '+args[1]
1044 print "Executing",expr
1045 exec expr
1046
1047def setvarCmd(ctx, args):
1048 if (len(args) < 4):
1049 print "usage: setvar [vmname|uuid] expr value"
1050 return 0
1051 mach = argsToMach(ctx,args)
1052 if mach == None:
1053 return 0
1054 cmdClosedVm(ctx, mach, setvar, args[2:])
1055 return 0
1056
1057def setvmextra(ctx,mach,args):
1058 key = args[0]
1059 value = args[1]
1060 print "%s: setting %s to %s" %(mach.name, key, value)
1061 mach.setExtraData(key, value)
1062
1063def setExtraDataCmd(ctx, args):
1064 if (len(args) < 3):
1065 print "usage: setextra [vmname|uuid|global] key <value>"
1066 return 0
1067 key = args[2]
1068 if len(args) == 4:
1069 value = args[3]
1070 else:
1071 value = None
1072 if args[1] == 'global':
1073 ctx['vb'].setExtraData(key, value)
1074 return 0
1075
1076 mach = argsToMach(ctx,args)
1077 if mach == None:
1078 return 0
1079 cmdClosedVm(ctx, mach, setvmextra, [key, value])
1080 return 0
1081
1082def printExtraKey(obj, key, value):
1083 print "%s: '%s' = '%s'" %(obj, key, value)
1084
1085def getExtraDataCmd(ctx, args):
1086 if (len(args) < 2):
1087 print "usage: getextra [vmname|uuid|global] <key>"
1088 return 0
1089 if len(args) == 3:
1090 key = args[2]
1091 else:
1092 key = None
1093
1094 if args[1] == 'global':
1095 obj = ctx['vb']
1096 else:
1097 obj = argsToMach(ctx,args)
1098 if obj == None:
1099 return 0
1100
1101 if key == None:
1102 keys = obj.getExtraDataKeys()
1103 else:
1104 keys = [ key ]
1105 for k in keys:
1106 printExtraKey(args[1], k, obj.getExtraData(k))
1107
1108 return 0
1109
1110def quitCmd(ctx, args):
1111 return 1
1112
1113def aliasCmd(ctx, args):
1114 if (len(args) == 3):
1115 aliases[args[1]] = args[2]
1116 return 0
1117
1118 for (k,v) in aliases.items():
1119 print "'%s' is an alias for '%s'" %(k,v)
1120 return 0
1121
1122def verboseCmd(ctx, args):
1123 global g_verbose
1124 g_verbose = not g_verbose
1125 return 0
1126
1127def colorsCmd(ctx, args):
1128 global g_hascolors
1129 g_hascolors = not g_hascolors
1130 return 0
1131
1132def hostCmd(ctx, args):
1133 vb = ctx['vb']
1134 print "VirtualBox version %s" %(colored(vb.version, 'blue'))
1135 props = vb.systemProperties
1136 print "Machines: %s" %(colPath(ctx,props.defaultMachineFolder))
1137 print "HDDs: %s" %(colPath(ctx,props.defaultHardDiskFolder))
1138
1139 #print "Global shared folders:"
1140 #for ud in ctx['global'].getArray(vb, 'sharedFolders'):
1141 # printSf(ctx,sf)
1142 host = vb.host
1143 cnt = host.processorCount
1144 print colCat(ctx,"Processors:")
1145 print " available/online: %d/%d " %(cnt,host.processorOnlineCount)
1146 for i in range(0,cnt):
1147 print " processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
1148
1149 print colCat(ctx, "RAM:")
1150 print " %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
1151 print colCat(ctx,"OS:");
1152 print " %s (%s)" %(host.operatingSystem, host.OSVersion)
1153 if host.Acceleration3DAvailable:
1154 print colCat(ctx,"3D acceleration available")
1155 else:
1156 print colCat(ctx,"3D acceleration NOT available")
1157
1158 print colCat(ctx,"Network interfaces:")
1159 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
1160 print " %s (%s)" %(ni.name, ni.IPAddress)
1161
1162 print colCat(ctx,"DVD drives:")
1163 for dd in ctx['global'].getArray(host, 'DVDDrives'):
1164 print " %s - %s" %(dd.name, dd.description)
1165
1166 print colCat(ctx,"Floppy drives:")
1167 for dd in ctx['global'].getArray(host, 'floppyDrives'):
1168 print " %s - %s" %(dd.name, dd.description)
1169
1170 print colCat(ctx,"USB devices:")
1171 for ud in ctx['global'].getArray(host, 'USBDevices'):
1172 printHostUsbDev(ctx,ud)
1173
1174 if ctx['perf']:
1175 for metric in ctx['perf'].query(["*"], [host]):
1176 print metric['name'], metric['values_as_string']
1177
1178 return 0
1179
1180def monitorGuestCmd(ctx, args):
1181 if (len(args) < 2):
1182 print "usage: monitorGuest name (duration)"
1183 return 0
1184 mach = argsToMach(ctx,args)
1185 if mach == None:
1186 return 0
1187 dur = 5
1188 if len(args) > 2:
1189 dur = float(args[2])
1190 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1191 return 0
1192
1193def monitorVBoxCmd(ctx, args):
1194 if (len(args) > 2):
1195 print "usage: monitorVBox (duration)"
1196 return 0
1197 dur = 5
1198 if len(args) > 1:
1199 dur = float(args[1])
1200 monitorVBox(ctx, dur)
1201 return 0
1202
1203def getAdapterType(ctx, type):
1204 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1205 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1206 return "pcnet"
1207 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1208 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1209 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1210 return "e1000"
1211 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1212 return "virtio"
1213 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1214 return None
1215 else:
1216 raise Exception("Unknown adapter type: "+type)
1217
1218
1219def portForwardCmd(ctx, args):
1220 if (len(args) != 5):
1221 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1222 return 0
1223 mach = argsToMach(ctx,args)
1224 if mach == None:
1225 return 0
1226 adapterNum = int(args[2])
1227 hostPort = int(args[3])
1228 guestPort = int(args[4])
1229 proto = "TCP"
1230 session = ctx['global'].openMachineSession(mach.id)
1231 mach = session.machine
1232
1233 adapter = mach.getNetworkAdapter(adapterNum)
1234 adapterType = getAdapterType(ctx, adapter.adapterType)
1235
1236 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1237 config = "VBoxInternal/Devices/" + adapterType + "/"
1238 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1239
1240 mach.setExtraData(config + "/Protocol", proto)
1241 mach.setExtraData(config + "/HostPort", str(hostPort))
1242 mach.setExtraData(config + "/GuestPort", str(guestPort))
1243
1244 mach.saveSettings()
1245 session.close()
1246
1247 return 0
1248
1249
1250def showLogCmd(ctx, args):
1251 if (len(args) < 2):
1252 print "usage: showLog vm <num>"
1253 return 0
1254 mach = argsToMach(ctx,args)
1255 if mach == None:
1256 return 0
1257
1258 log = 0
1259 if (len(args) > 2):
1260 log = args[2]
1261
1262 uOffset = 0
1263 while True:
1264 data = mach.readLog(log, uOffset, 4096)
1265 if (len(data) == 0):
1266 break
1267 # print adds either NL or space to chunks not ending with a NL
1268 sys.stdout.write(str(data))
1269 uOffset += len(data)
1270
1271 return 0
1272
1273def findLogCmd(ctx, args):
1274 if (len(args) < 3):
1275 print "usage: findLog vm pattern <num>"
1276 return 0
1277 mach = argsToMach(ctx,args)
1278 if mach == None:
1279 return 0
1280
1281 log = 0
1282 if (len(args) > 3):
1283 log = args[3]
1284
1285 pattern = args[2]
1286 uOffset = 0
1287 while True:
1288 # to reduce line splits on buffer boundary
1289 data = mach.readLog(log, uOffset, 512*1024)
1290 if (len(data) == 0):
1291 break
1292 d = str(data).split("\n")
1293 for s in d:
1294 m = re.findall(pattern, s)
1295 if len(m) > 0:
1296 for mt in m:
1297 s = s.replace(mt, colored(mt,'red'))
1298 print s
1299 uOffset += len(data)
1300
1301 return 0
1302
1303def evalCmd(ctx, args):
1304 expr = ' '.join(args[1:])
1305 try:
1306 exec expr
1307 except Exception, e:
1308 printErr(ctx,e)
1309 if g_verbose:
1310 traceback.print_exc()
1311 return 0
1312
1313def reloadExtCmd(ctx, args):
1314 # maybe will want more args smartness
1315 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1316 autoCompletion(commands, ctx)
1317 return 0
1318
1319
1320def runScriptCmd(ctx, args):
1321 if (len(args) != 2):
1322 print "usage: runScript <script>"
1323 return 0
1324 try:
1325 lf = open(args[1], 'r')
1326 except IOError,e:
1327 print "cannot open:",args[1], ":",e
1328 return 0
1329
1330 try:
1331 for line in lf:
1332 done = runCommand(ctx, line)
1333 if done != 0: break
1334 except Exception,e:
1335 printErr(ctx,e)
1336 if g_verbose:
1337 traceback.print_exc()
1338 lf.close()
1339 return 0
1340
1341def sleepCmd(ctx, args):
1342 if (len(args) != 2):
1343 print "usage: sleep <secs>"
1344 return 0
1345
1346 try:
1347 time.sleep(float(args[1]))
1348 except:
1349 # to allow sleep interrupt
1350 pass
1351 return 0
1352
1353
1354def shellCmd(ctx, args):
1355 if (len(args) < 2):
1356 print "usage: shell <commands>"
1357 return 0
1358 cmd = ' '.join(args[1:])
1359
1360 try:
1361 os.system(cmd)
1362 except KeyboardInterrupt:
1363 # to allow shell command interruption
1364 pass
1365 return 0
1366
1367
1368def connectCmd(ctx, args):
1369 if (len(args) > 4):
1370 print "usage: connect url <username> <passwd>"
1371 return 0
1372
1373 if ctx['vb'] is not None:
1374 print "Already connected, disconnect first..."
1375 return 0
1376
1377 if (len(args) > 1):
1378 url = args[1]
1379 else:
1380 url = None
1381
1382 if (len(args) > 2):
1383 user = args[2]
1384 else:
1385 user = ""
1386
1387 if (len(args) > 3):
1388 passwd = args[3]
1389 else:
1390 passwd = ""
1391
1392 ctx['wsinfo'] = [url, user, passwd]
1393 vbox = ctx['global'].platform.connect(url, user, passwd)
1394 ctx['vb'] = vbox
1395 print "Running VirtualBox version %s" %(vbox.version)
1396 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1397 return 0
1398
1399def disconnectCmd(ctx, args):
1400 if (len(args) != 1):
1401 print "usage: disconnect"
1402 return 0
1403
1404 if ctx['vb'] is None:
1405 print "Not connected yet."
1406 return 0
1407
1408 try:
1409 ctx['global'].platform.disconnect()
1410 except:
1411 ctx['vb'] = None
1412 raise
1413
1414 ctx['vb'] = None
1415 return 0
1416
1417def reconnectCmd(ctx, args):
1418 if ctx['wsinfo'] is None:
1419 print "Never connected..."
1420 return 0
1421
1422 try:
1423 ctx['global'].platform.disconnect()
1424 except:
1425 pass
1426
1427 [url,user,passwd] = ctx['wsinfo']
1428 ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
1429 print "Running VirtualBox version %s" %(ctx['vb'].version)
1430 return 0
1431
1432def exportVMCmd(ctx, args):
1433 import sys
1434
1435 if len(args) < 3:
1436 print "usage: exportVm <machine> <path> <format> <license>"
1437 return 0
1438 mach = argsToMach(ctx,args)
1439 if mach is None:
1440 return 0
1441 path = args[2]
1442 if (len(args) > 3):
1443 format = args[3]
1444 else:
1445 format = "ovf-1.0"
1446 if (len(args) > 4):
1447 license = args[4]
1448 else:
1449 license = "GPL"
1450
1451 app = ctx['vb'].createAppliance()
1452 desc = mach.export(app)
1453 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1454 p = app.write(format, path)
1455 if (progressBar(ctx, p) and int(p.resultCode) == 0):
1456 print "Exported to %s in format %s" %(path, format)
1457 else:
1458 reportError(ctx,p)
1459 return 0
1460
1461# PC XT scancodes
1462scancodes = {
1463 'a': 0x1e,
1464 'b': 0x30,
1465 'c': 0x2e,
1466 'd': 0x20,
1467 'e': 0x12,
1468 'f': 0x21,
1469 'g': 0x22,
1470 'h': 0x23,
1471 'i': 0x17,
1472 'j': 0x24,
1473 'k': 0x25,
1474 'l': 0x26,
1475 'm': 0x32,
1476 'n': 0x31,
1477 'o': 0x18,
1478 'p': 0x19,
1479 'q': 0x10,
1480 'r': 0x13,
1481 's': 0x1f,
1482 't': 0x14,
1483 'u': 0x16,
1484 'v': 0x2f,
1485 'w': 0x11,
1486 'x': 0x2d,
1487 'y': 0x15,
1488 'z': 0x2c,
1489 '0': 0x0b,
1490 '1': 0x02,
1491 '2': 0x03,
1492 '3': 0x04,
1493 '4': 0x05,
1494 '5': 0x06,
1495 '6': 0x07,
1496 '7': 0x08,
1497 '8': 0x09,
1498 '9': 0x0a,
1499 ' ': 0x39,
1500 '-': 0xc,
1501 '=': 0xd,
1502 '[': 0x1a,
1503 ']': 0x1b,
1504 ';': 0x27,
1505 '\'': 0x28,
1506 ',': 0x33,
1507 '.': 0x34,
1508 '/': 0x35,
1509 '\t': 0xf,
1510 '\n': 0x1c,
1511 '`': 0x29
1512};
1513
1514extScancodes = {
1515 'ESC' : [0x01],
1516 'BKSP': [0xe],
1517 'SPACE': [0x39],
1518 'TAB': [0x0f],
1519 'CAPS': [0x3a],
1520 'ENTER': [0x1c],
1521 'LSHIFT': [0x2a],
1522 'RSHIFT': [0x36],
1523 'INS': [0xe0, 0x52],
1524 'DEL': [0xe0, 0x53],
1525 'END': [0xe0, 0x4f],
1526 'HOME': [0xe0, 0x47],
1527 'PGUP': [0xe0, 0x49],
1528 'PGDOWN': [0xe0, 0x51],
1529 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
1530 'RGUI': [0xe0, 0x5c],
1531 'LCTR': [0x1d],
1532 'RCTR': [0xe0, 0x1d],
1533 'LALT': [0x38],
1534 'RALT': [0xe0, 0x38],
1535 'APPS': [0xe0, 0x5d],
1536 'F1': [0x3b],
1537 'F2': [0x3c],
1538 'F3': [0x3d],
1539 'F4': [0x3e],
1540 'F5': [0x3f],
1541 'F6': [0x40],
1542 'F7': [0x41],
1543 'F8': [0x42],
1544 'F9': [0x43],
1545 'F10': [0x44 ],
1546 'F11': [0x57],
1547 'F12': [0x58],
1548 'UP': [0xe0, 0x48],
1549 'LEFT': [0xe0, 0x4b],
1550 'DOWN': [0xe0, 0x50],
1551 'RIGHT': [0xe0, 0x4d],
1552};
1553
1554def keyDown(ch):
1555 code = scancodes.get(ch, 0x0)
1556 if code != 0:
1557 return [code]
1558 extCode = extScancodes.get(ch, [])
1559 if len(extCode) == 0:
1560 print "bad ext",ch
1561 return extCode
1562
1563def keyUp(ch):
1564 codes = keyDown(ch)[:] # make a copy
1565 if len(codes) > 0:
1566 codes[len(codes)-1] += 0x80
1567 return codes
1568
1569def typeInGuest(console, text, delay):
1570 import time
1571 pressed = []
1572 group = False
1573 modGroupEnd = True
1574 i = 0
1575 while i < len(text):
1576 ch = text[i]
1577 i = i+1
1578 if ch == '{':
1579 # start group, all keys to be pressed at the same time
1580 group = True
1581 continue
1582 if ch == '}':
1583 # end group, release all keys
1584 for c in pressed:
1585 console.keyboard.putScancodes(keyUp(c))
1586 pressed = []
1587 group = False
1588 continue
1589 if ch == 'W':
1590 # just wait a bit
1591 time.sleep(0.3)
1592 continue
1593 if ch == '^' or ch == '|' or ch == '$' or ch == '_':
1594 if ch == '^':
1595 ch = 'LCTR'
1596 if ch == '|':
1597 ch = 'LSHIFT'
1598 if ch == '_':
1599 ch = 'LALT'
1600 if ch == '$':
1601 ch = 'LGUI'
1602 if not group:
1603 modGroupEnd = False
1604 else:
1605 if ch == '\\':
1606 if i < len(text):
1607 ch = text[i]
1608 i = i+1
1609 if ch == 'n':
1610 ch = '\n'
1611 elif ch == '&':
1612 combo = ""
1613 while i < len(text):
1614 ch = text[i]
1615 i = i+1
1616 if ch == ';':
1617 break
1618 combo += ch
1619 ch = combo
1620 modGroupEnd = True
1621 console.keyboard.putScancodes(keyDown(ch))
1622 pressed.insert(0, ch)
1623 if not group and modGroupEnd:
1624 for c in pressed:
1625 console.keyboard.putScancodes(keyUp(c))
1626 pressed = []
1627 modGroupEnd = True
1628 time.sleep(delay)
1629
1630def typeGuestCmd(ctx, args):
1631 import sys
1632
1633 if len(args) < 3:
1634 print "usage: typeGuest <machine> <text> <charDelay>"
1635 return 0
1636 mach = argsToMach(ctx,args)
1637 if mach is None:
1638 return 0
1639
1640 text = args[2]
1641
1642 if len(args) > 3:
1643 delay = float(args[3])
1644 else:
1645 delay = 0.1
1646
1647 gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
1648 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1649
1650 return 0
1651
1652def optId(verbose,id):
1653 if verbose:
1654 return ": "+id
1655 else:
1656 return ""
1657
1658def asSize(val,inBytes):
1659 if inBytes:
1660 return int(val)/(1024*1024)
1661 else:
1662 return int(val)
1663
1664def listMediaCmd(ctx,args):
1665 if len(args) > 1:
1666 verbose = int(args[1])
1667 else:
1668 verbose = False
1669 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
1670 print "Hard disks:"
1671 for hdd in hdds:
1672 if hdd.state != ctx['global'].constants.MediumState_Created:
1673 hdd.refreshState()
1674 print " %s (%s)%s %dM [logical %dM]" %(hdd.location, hdd.format, optId(verbose,hdd.id),asSize(hdd.size, True), asSize(hdd.logicalSize, False))
1675
1676 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
1677 print "CD/DVD disks:"
1678 for dvd in dvds:
1679 if dvd.state != ctx['global'].constants.MediumState_Created:
1680 dvd.refreshState()
1681 print " %s (%s)%s %dM" %(dvd.location, dvd.format,optId(verbose,hdd.id),asSize(hdd.size, True))
1682
1683 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
1684 print "Floopy disks:"
1685 for floppy in floppys:
1686 if floppy.state != ctx['global'].constants.MediumState_Created:
1687 floppy.refreshState()
1688 print " %s (%s)%s %dM" %(floppy.location, floppy.format,optId(verbose,hdd.id), asSize(hdd.size, True))
1689
1690 return 0
1691
1692def listUsbCmd(ctx,args):
1693 if (len(args) > 1):
1694 print "usage: listUsb"
1695 return 0
1696
1697 host = ctx['vb'].host
1698 for ud in ctx['global'].getArray(host, 'USBDevices'):
1699 printHostUsbDev(ctx,ud)
1700
1701 return 0
1702
1703def findDevOfType(ctx,mach,type):
1704 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1705 for a in atts:
1706 if a.type == type:
1707 return [a.controller, a.port, a.device]
1708 return [None, 0, 0]
1709
1710def createHddCmd(ctx,args):
1711 if (len(args) < 3):
1712 print "usage: createHdd sizeM location type"
1713 return 0
1714
1715 size = int(args[1])
1716 loc = args[2]
1717 if len(args) > 3:
1718 format = args[3]
1719 else:
1720 format = "vdi"
1721
1722 hdd = ctx['vb'].createHardDisk(format, loc)
1723 progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
1724 if progressBar(ctx,progress) and hdd.id:
1725 print "created HDD at %s as %s" %(hdd.location, hdd.id)
1726 else:
1727 print "cannot create disk (file %s exist?)" %(loc)
1728 reportError(ctx,progress)
1729 return 0
1730
1731 return 0
1732
1733def registerHddCmd(ctx,args):
1734 if (len(args) < 2):
1735 print "usage: registerHdd location"
1736 return 0
1737
1738 vb = ctx['vb']
1739 loc = args[1]
1740 setImageId = False
1741 imageId = ""
1742 setParentId = False
1743 parentId = ""
1744 hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
1745 print "registered HDD as %s" %(hdd.id)
1746 return 0
1747
1748def controldevice(ctx,mach,args):
1749 [ctr,port,slot,type,id] = args
1750 mach.attachDevice(ctr, port, slot,type,id)
1751
1752def attachHddCmd(ctx,args):
1753 if (len(args) < 3):
1754 print "usage: attachHdd vm hdd controller port:slot"
1755 return 0
1756
1757 mach = argsToMach(ctx,args)
1758 if mach is None:
1759 return 0
1760 vb = ctx['vb']
1761 loc = args[2]
1762 try:
1763 hdd = vb.findHardDisk(loc)
1764 except:
1765 print "no HDD with path %s registered" %(loc)
1766 return 0
1767 if len(args) > 3:
1768 ctr = args[3]
1769 (port,slot) = args[4].split(":")
1770 else:
1771 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
1772
1773 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
1774 return 0
1775
1776def detachVmDevice(ctx,mach,args):
1777 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1778 hid = args[0]
1779 for a in atts:
1780 if a.medium:
1781 if hid == "ALL" or a.medium.id == hid:
1782 mach.detachDevice(a.controller, a.port, a.device)
1783
1784def detachMedium(ctx,mid,medium):
1785 cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
1786
1787def detachHddCmd(ctx,args):
1788 if (len(args) < 3):
1789 print "usage: detachHdd vm hdd"
1790 return 0
1791
1792 mach = argsToMach(ctx,args)
1793 if mach is None:
1794 return 0
1795 vb = ctx['vb']
1796 loc = args[2]
1797 try:
1798 hdd = vb.findHardDisk(loc)
1799 except:
1800 print "no HDD with path %s registered" %(loc)
1801 return 0
1802
1803 detachMedium(ctx,mach.id,hdd)
1804 return 0
1805
1806def unregisterHddCmd(ctx,args):
1807 if (len(args) < 2):
1808 print "usage: unregisterHdd path <vmunreg>"
1809 return 0
1810
1811 vb = ctx['vb']
1812 loc = args[1]
1813 if (len(args) > 2):
1814 vmunreg = int(args[2])
1815 else:
1816 vmunreg = 0
1817 try:
1818 hdd = vb.findHardDisk(loc)
1819 except:
1820 print "no HDD with path %s registered" %(loc)
1821 return 0
1822
1823 if vmunreg != 0:
1824 machs = ctx['global'].getArray(hdd, 'machineIds')
1825 try:
1826 for m in machs:
1827 print "Trying to detach from %s" %(m)
1828 detachMedium(ctx,m,hdd)
1829 except Exception, e:
1830 print 'failed: ',e
1831 return 0
1832 hdd.close()
1833 return 0
1834
1835def removeHddCmd(ctx,args):
1836 if (len(args) != 2):
1837 print "usage: removeHdd path"
1838 return 0
1839
1840 vb = ctx['vb']
1841 loc = args[1]
1842 try:
1843 hdd = vb.findHardDisk(loc)
1844 except:
1845 print "no HDD with path %s registered" %(loc)
1846 return 0
1847
1848 progress = hdd.deleteStorage()
1849 progressBar(ctx,progress)
1850
1851 return 0
1852
1853def registerIsoCmd(ctx,args):
1854 if (len(args) < 2):
1855 print "usage: registerIso location"
1856 return 0
1857 vb = ctx['vb']
1858 loc = args[1]
1859 id = ""
1860 iso = vb.openDVDImage(loc, id)
1861 print "registered ISO as %s" %(iso.id)
1862 return 0
1863
1864def unregisterIsoCmd(ctx,args):
1865 if (len(args) != 2):
1866 print "usage: unregisterIso 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.close()
1878 print "Unregistered ISO at %s" %(dvd.location)
1879
1880 return 0
1881
1882def removeIsoCmd(ctx,args):
1883 if (len(args) != 2):
1884 print "usage: removeIso path"
1885 return 0
1886
1887 vb = ctx['vb']
1888 loc = args[1]
1889 try:
1890 dvd = vb.findDVDImage(loc)
1891 except:
1892 print "no DVD with path %s registered" %(loc)
1893 return 0
1894
1895 progress = dvd.deleteStorage()
1896 if progressBar(ctx,progress):
1897 print "Removed ISO at %s" %(dvd.location)
1898 else:
1899 reportError(ctx,progress)
1900 return 0
1901
1902def attachIsoCmd(ctx,args):
1903 if (len(args) < 3):
1904 print "usage: attachIso vm iso controller port:slot"
1905 return 0
1906
1907 mach = argsToMach(ctx,args)
1908 if mach is None:
1909 return 0
1910 vb = ctx['vb']
1911 loc = args[2]
1912 try:
1913 dvd = vb.findDVDImage(loc)
1914 except:
1915 print "no DVD with path %s registered" %(loc)
1916 return 0
1917 if len(args) > 3:
1918 ctr = args[3]
1919 (port,slot) = args[4].split(":")
1920 else:
1921 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1922 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
1923 return 0
1924
1925def detachIsoCmd(ctx,args):
1926 if (len(args) < 3):
1927 print "usage: detachIso vm iso"
1928 return 0
1929
1930 mach = argsToMach(ctx,args)
1931 if mach is None:
1932 return 0
1933 vb = ctx['vb']
1934 loc = args[2]
1935 try:
1936 dvd = vb.findDVDImage(loc)
1937 except:
1938 print "no DVD with path %s registered" %(loc)
1939 return 0
1940
1941 detachMedium(ctx,mach.id,dvd)
1942 return 0
1943
1944def mountIsoCmd(ctx,args):
1945 if (len(args) < 3):
1946 print "usage: mountIso vm iso controller port:slot"
1947 return 0
1948
1949 mach = argsToMach(ctx,args)
1950 if mach is None:
1951 return 0
1952 vb = ctx['vb']
1953 loc = args[2]
1954 try:
1955 dvd = vb.findDVDImage(loc)
1956 except:
1957 print "no DVD with path %s registered" %(loc)
1958 return 0
1959
1960 if len(args) > 3:
1961 ctr = args[3]
1962 (port,slot) = args[4].split(":")
1963 else:
1964 # autodetect controller and location, just find first controller with media == DVD
1965 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1966
1967 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
1968
1969 return 0
1970
1971def unmountIsoCmd(ctx,args):
1972 if (len(args) < 2):
1973 print "usage: unmountIso vm controller port:slot"
1974 return 0
1975
1976 mach = argsToMach(ctx,args)
1977 if mach is None:
1978 return 0
1979 vb = ctx['vb']
1980
1981 if len(args) > 2:
1982 ctr = args[2]
1983 (port,slot) = args[3].split(":")
1984 else:
1985 # autodetect controller and location, just find first controller with media == DVD
1986 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1987
1988 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
1989
1990 return 0
1991
1992def attachCtr(ctx,mach,args):
1993 [name, bus, type] = args
1994 ctr = mach.addStorageController(name, bus)
1995 if type != None:
1996 ctr.controllerType = type
1997
1998def attachCtrCmd(ctx,args):
1999 if (len(args) < 4):
2000 print "usage: attachCtr vm cname bus <type>"
2001 return 0
2002
2003 if len(args) > 4:
2004 type = enumFromString(ctx,'StorageControllerType', args[4])
2005 if type == None:
2006 print "Controller type %s unknown" %(args[4])
2007 return 0
2008 else:
2009 type = None
2010
2011 mach = argsToMach(ctx,args)
2012 if mach is None:
2013 return 0
2014 bus = enumFromString(ctx,'StorageBus', args[3])
2015 if bus is None:
2016 print "Bus type %s unknown" %(args[3])
2017 return 0
2018 name = args[2]
2019 cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
2020 return 0
2021
2022def detachCtrCmd(ctx,args):
2023 if (len(args) < 3):
2024 print "usage: detachCtr vm name"
2025 return 0
2026
2027 mach = argsToMach(ctx,args)
2028 if mach is None:
2029 return 0
2030 ctr = args[2]
2031 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
2032 return 0
2033
2034def usbctr(ctx,mach,console,args):
2035 if (args[0]):
2036 console.attachUSBDevice(args[1])
2037 else:
2038 console.detachUSBDevice(args[1])
2039
2040def attachUsbCmd(ctx,args):
2041 if (len(args) < 3):
2042 print "usage: attachUsb vm deviceuid"
2043 return 0
2044
2045 mach = argsToMach(ctx,args)
2046 if mach is None:
2047 return 0
2048 dev = args[2]
2049 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
2050 return 0
2051
2052def detachUsbCmd(ctx,args):
2053 if (len(args) < 3):
2054 print "usage: detachUsb vm deviceuid"
2055 return 0
2056
2057 mach = argsToMach(ctx,args)
2058 if mach is None:
2059 return 0
2060 dev = args[2]
2061 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
2062 return 0
2063
2064
2065def guiCmd(ctx,args):
2066 if (len(args) > 1):
2067 print "usage: gui"
2068 return 0
2069
2070 binDir = ctx['global'].getBinDir()
2071
2072 vbox = os.path.join(binDir, 'VirtualBox')
2073 try:
2074 os.system(vbox)
2075 except KeyboardInterrupt:
2076 # to allow interruption
2077 pass
2078 return 0
2079
2080def shareFolderCmd(ctx,args):
2081 if (len(args) < 4):
2082 print "usage: shareFolder vm path name <writable> <persistent>"
2083 return 0
2084
2085 mach = argsToMach(ctx,args)
2086 if mach is None:
2087 return 0
2088 path = args[2]
2089 name = args[3]
2090 writable = False
2091 persistent = False
2092 if len(args) > 4:
2093 for a in args[4:]:
2094 if a == 'writable':
2095 writable = True
2096 if a == 'persistent':
2097 persistent = True
2098 if persistent:
2099 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.createSharedFolder(name, path, writable), [])
2100 else:
2101 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.createSharedFolder(name, path, writable)])
2102 return 0
2103
2104def unshareFolderCmd(ctx,args):
2105 if (len(args) < 3):
2106 print "usage: unshareFolder vm name"
2107 return 0
2108
2109 mach = argsToMach(ctx,args)
2110 if mach is None:
2111 return 0
2112 name = args[2]
2113 found = False
2114 for sf in ctx['global'].getArray(mach, 'sharedFolders'):
2115 if sf.name == name:
2116 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeSharedFolder(name), [])
2117 found = True
2118 break
2119 if not found:
2120 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.removeSharedFolder(name)])
2121 return 0
2122
2123
2124def snapshotCmd(ctx,args):
2125 if (len(args) < 2 or args[1] == 'help'):
2126 print "Take snapshot: snapshot vm take name <description>"
2127 print "Restore snapshot: snapshot vm restore name"
2128 print "Merge snapshot: snapshot vm merge name"
2129 return 0
2130
2131 mach = argsToMach(ctx,args)
2132 if mach is None:
2133 return 0
2134 cmd = args[2]
2135 if cmd == 'take':
2136 if (len(args) < 4):
2137 print "usage: snapshot vm take name <description>"
2138 return 0
2139 name = args[3]
2140 if (len(args) > 4):
2141 desc = args[4]
2142 else:
2143 desc = ""
2144 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.takeSnapshot(name,desc)))
2145
2146 if cmd == 'restore':
2147 if (len(args) < 4):
2148 print "usage: snapshot vm restore name"
2149 return 0
2150 name = args[3]
2151 snap = mach.findSnapshot(name)
2152 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
2153 return 0
2154
2155 if cmd == 'restorecurrent':
2156 if (len(args) < 4):
2157 print "usage: snapshot vm restorecurrent"
2158 return 0
2159 snap = mach.currentSnapshot()
2160 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
2161 return 0
2162
2163 if cmd == 'delete':
2164 if (len(args) < 4):
2165 print "usage: snapshot vm delete name"
2166 return 0
2167 name = args[3]
2168 snap = mach.findSnapshot(name)
2169 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.deleteSnapshot(snap.id)))
2170 return 0
2171
2172 print "Command '%s' is unknown" %(cmd)
2173
2174 return 0
2175
2176def natAlias(ctx, mach, nicnum, nat, args=[]):
2177 """This command shows/alters NAT's alias settings.
2178 usage: nat <vm> <nicnum> alias [default|[log] [proxyonly] [sameports]]
2179 default - set settings to default values
2180 log - switch on alias loging
2181 proxyonly - switch proxyonly mode on
2182 sameports - enforces NAT using the same ports
2183 """
2184 alias = {
2185 'log': 0x1,
2186 'proxyonly': 0x2,
2187 'sameports': 0x4
2188 }
2189 if len(args) == 1:
2190 first = 0
2191 msg = ''
2192 for aliasmode, aliaskey in alias.iteritems():
2193 if first == 0:
2194 first = 1
2195 else:
2196 msg += ', '
2197 if int(nat.aliasMode) & aliaskey:
2198 msg += '{0}: {1}'.format(aliasmode, 'on')
2199 else:
2200 msg += '{0}: {1}'.format(aliasmode, 'off')
2201 msg += ')'
2202 return (0, [msg])
2203 else:
2204 nat.aliasMode = 0
2205 if 'default' not in args:
2206 for a in range(1, len(args)):
2207 if not alias.has_key(args[a]):
2208 print 'Invalid alias mode: ' + args[a]
2209 print natAlias.__doc__
2210 return (1, None)
2211 nat.aliasMode = int(nat.aliasMode) | alias[args[a]];
2212 return (0, None)
2213
2214def natSettings(ctx, mach, nicnum, nat, args):
2215 """This command shows/alters NAT settings.
2216 usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
2217 mtu - set mtu <= 16000
2218 socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
2219 tcpsndwnd/tcprcvwnd - sets size of initial tcp sending/receiving window
2220 """
2221 if len(args) == 1:
2222 (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings();
2223 if mtu == 0: mtu = 1500
2224 if socksndbuf == 0: socksndbuf = 64
2225 if sockrcvbuf == 0: sockrcvbuf = 64
2226 if tcpsndwnd == 0: tcpsndwnd = 64
2227 if tcprcvwnd == 0: tcprcvwnd = 64
2228 msg = 'mtu:{0} socket(snd:{1}, rcv:{2}) tcpwnd(snd:{3}, rcv:{4})'.format(mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd);
2229 return (0, [msg])
2230 else:
2231 if args[1] < 16000:
2232 print 'invalid mtu value ({0} no in range [65 - 16000])'.format(args[1])
2233 return (1, None)
2234 for i in range(2, len(args)):
2235 if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024:
2236 print 'invalid {0} parameter ({1} not in range [8-1024])'.format(i, args[i])
2237 return (1, None)
2238 a = [args[1]]
2239 if len(args) < 6:
2240 for i in range(2, len(args)): a.append(args[i])
2241 for i in range(len(args), 6): a.append(0)
2242 else:
2243 for i in range(2, len(args)): a.append(args[i])
2244 #print a
2245 nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))
2246 return (0, None)
2247
2248def natDns(ctx, mach, nicnum, nat, args):
2249 """This command shows/alters DNS's NAT settings
2250 usage: nat <vm> <nicnum> dns [passdomain] [proxy] [usehostresolver]
2251 passdomain - enforces builtin DHCP server to pass domain
2252 proxy - switch on builtin NAT DNS proxying mechanism
2253 usehostresolver - proxies all DNS requests to Host Resolver interface
2254 """
2255 yesno = {0: 'off', 1: 'on'}
2256 if len(args) == 1:
2257 msg = 'passdomain:{0}, proxy:{1}, usehostresolver:{2}'.format(yesno[int(nat.dnsPassDomain)], yesno[int(nat.dnsProxy)], yesno[int(nat.dnsUseHostResolver)])
2258 return (0, [msg])
2259 else:
2260 nat.dnsPassDomain = 'passdomain' in args
2261 nat.dnsProxy = 'proxy' in args
2262 nat.dnsUseHostResolver = 'usehostresolver' in args
2263 return (0, None)
2264
2265def natTftp(ctx, mach, nicnum, nat, args):
2266 """This command shows/alters TFTP settings
2267 usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
2268 prefix - alters prefix TFTP settings
2269 bootfile - alters bootfile TFTP settings
2270 server - sets booting server
2271 """
2272 if len(args) == 1:
2273 server = nat.tftpNextServer
2274 if server is None:
2275 server = nat.network
2276 if server is None:
2277 server = '10.0.{0}/24'.format(int(nicnum) + 2)
2278 (server,mask) = server.split('/')
2279 while server.count('.') != 3:
2280 server += '.0'
2281 (a,b,c,d) = server.split('.')
2282 server = '{0}.{1}.{2}.4'.format(a,b,c)
2283 prefix = nat.tftpPrefix
2284 if prefix is None:
2285 prefix = '{0}/TFTP/'.format(ctx['vb'].homeFolder)
2286 bootfile = nat.tftpBootFile
2287 if bootfile is None:
2288 bootfile = '{0}.pxe'.format(mach.name)
2289 msg = 'server:{0}, prefix:{1}, bootfile:{2}'.format(server, prefix, bootfile)
2290 return (0, [msg])
2291 else:
2292
2293 cmd = args[1]
2294 if len(args) != 3:
2295 print 'invalid args:', args
2296 print natTftp.__doc__
2297 return (1, None)
2298 if cmd == 'prefix': nat.tftpPrefix = args[2]
2299 elif cmd == 'bootfile': nat.tftpBootFile = args[2]
2300 elif cmd == 'server': nat.tftpNextServer = args[2]
2301 else:
2302 print "invalid cmd:", cmd
2303 return (1, None)
2304 return (0, None)
2305
2306def natPortForwarding(ctx, mach, nicnum, nat, args):
2307 """This command shows/manages port-forwarding settings
2308 usage:
2309 nat <vm> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
2310 |[no_name tcp|udp <hostip> <hostport> <guestip> <guestport>]
2311 |[ex tcp|udp <pf-name> <hostip> <hostport> <guestip> <guestport>]
2312 |[delete <pf-name>]
2313 """
2314 if len(args) == 1:
2315 # note: keys/values are swapped in defining part of the function
2316 proto = {0: 'udp', 1: 'tcp'}
2317 msg = []
2318 pfs = ctx['global'].getArray(nat, 'redirects')
2319 for pf in pfs:
2320 (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(',')
2321 msg.append('{0}: {1} {2}:{3} => {4}:{5}'.format(pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
2322 return (0, msg) # msg is array
2323 else:
2324 proto = {'udp': 0, 'tcp': 1}
2325 pfcmd = {
2326 'simple': {
2327 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 5,
2328 'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4]))
2329 },
2330 'no_name': {
2331 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 7,
2332 'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6]))
2333 },
2334 'ex': {
2335 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 8,
2336 'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7]))
2337 },
2338 'delete': {
2339 'validate': lambda: len(args) == 3,
2340 'func': lambda: nat.removeRedirect(args[2])
2341 }
2342 }
2343
2344 if not pfcmd[args[1]]['validate']():
2345 print 'invalid port-forwarding or args of sub command ', args[1]
2346 print natPortForwarding.__doc__
2347 return (1, None)
2348
2349 a = pfcmd[args[1]]['func']()
2350 return (0, None)
2351
2352def natNetwork(ctx, mach, nicnum, nat, args):
2353 """This command shows/alters NAT network settings
2354 usage: nat <vm> <nicnum> network [<network>]
2355 """
2356 if len(args) == 1:
2357 if nat.network is not None and len(str(nat.network)) != 0:
2358 msg = '\'%s\'' % (nat.network)
2359 else:
2360 msg = '10.0.{0}.0/24'.format(int(nicnum) + 2)
2361 return (0, [msg])
2362 else:
2363 (addr, mask) = args[1].split('/')
2364 if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
2365 print 'Invalid arguments'
2366 return (1, None)
2367 nat.network = args[1]
2368 return (0, None)
2369def natCmd(ctx, args):
2370 """This command is entry point to NAT settins management
2371 usage: nat <vm> <nicnum> <cmd> <cmd-args>
2372 cmd - [alias|settings|tftp|dns|pf|network]
2373 for more information about commands:
2374 nat help <cmd>
2375 """
2376
2377 natcommands = {
2378 'alias' : natAlias,
2379 'settings' : natSettings,
2380 'tftp': natTftp,
2381 'dns': natDns,
2382 'pf': natPortForwarding,
2383 'network': natNetwork
2384 }
2385
2386 if args[1] == 'help':
2387 if len(args) > 2:
2388 print natcommands[args[2]].__doc__
2389 else:
2390 print natCmd.__doc__
2391 return 0
2392 if len(args) == 1 or len(args) < 4 or args[3] not in natcommands:
2393 print natCmd.__doc__
2394 return 0
2395 mach = ctx['argsToMach'](args)
2396 if mach == None:
2397 print "please specify vm"
2398 return 0
2399 if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
2400 print 'please specify adapter num {0} isn\'t in range [0-{1}]'.format(args[2], ctx['vb'].systemProperties.networkAdapterCount)
2401 return 0
2402 nicnum = int(args[2])
2403 cmdargs = []
2404 for i in range(3, len(args)):
2405 cmdargs.append(args[i])
2406
2407 # @todo vvl if nicnum is missed but command is entered
2408 # use NAT func for every adapter on machine.
2409 func = args[3]
2410 rosession = 1
2411 session = None
2412 if len(cmdargs) > 1:
2413 rosession = 0
2414 session = ctx['global'].openMachineSession(mach.id);
2415 mach = session.machine;
2416
2417 adapter = mach.getNetworkAdapter(nicnum)
2418 natEngine = adapter.natDriver
2419 (rc, report) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
2420 if rosession == 0:
2421 if rc == 0:
2422 mach.saveSettings()
2423 session.close()
2424 elif report is not None:
2425 for r in report:
2426 msg ='{0} nic{1} {2}: {3}'.format(mach.name, nicnum, func, r)
2427 print msg
2428 return 0
2429
2430
2431aliases = {'s':'start',
2432 'i':'info',
2433 'l':'list',
2434 'h':'help',
2435 'a':'alias',
2436 'q':'quit', 'exit':'quit',
2437 'tg': 'typeGuest',
2438 'v':'verbose'}
2439
2440commands = {'help':['Prints help information', helpCmd, 0],
2441 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
2442 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
2443 'removeVm':['Remove virtual machine', removeVmCmd, 0],
2444 'pause':['Pause virtual machine', pauseCmd, 0],
2445 'resume':['Resume virtual machine', resumeCmd, 0],
2446 'save':['Save execution state of virtual machine', saveCmd, 0],
2447 'stats':['Stats for virtual machine', statsCmd, 0],
2448 'powerdown':['Power down virtual machine', powerdownCmd, 0],
2449 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
2450 'list':['Shows known virtual machines', listCmd, 0],
2451 'info':['Shows info on machine', infoCmd, 0],
2452 'ginfo':['Shows info on guest', ginfoCmd, 0],
2453 'gexec':['Executes program in the guest', gexecCmd, 0],
2454 'alias':['Control aliases', aliasCmd, 0],
2455 'verbose':['Toggle verbosity', verboseCmd, 0],
2456 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
2457 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
2458 'quit':['Exits', quitCmd, 0],
2459 'host':['Show host information', hostCmd, 0],
2460 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
2461 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
2462 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
2463 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
2464 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
2465 'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
2466 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
2467 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
2468 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
2469 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
2470 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
2471 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
2472 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
2473 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
2474 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
2475 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
2476 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
2477 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
2478 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
2479 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
2480 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
2481 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
2482 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
2483 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
2484 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
2485 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
2486 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
2487 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
2488 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
2489 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
2490 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
2491 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
2492 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
2493 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
2494 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
2495 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
2496 'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
2497 'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
2498 'listMedia': ['List media known to this VBox instance', listMediaCmd, 0],
2499 'listUsb': ['List known USB devices', listUsbCmd, 0],
2500 'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
2501 'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
2502 'gui': ['Start GUI frontend', guiCmd, 0],
2503 'colors':['Toggle colors', colorsCmd, 0],
2504 'snapshot':['VM snapshot manipulation, snapshot help for more info', snapshotCmd, 0],
2505 'nat':['NAT manipulation, nat help for more info', natCmd, 0],
2506 }
2507
2508def runCommandArgs(ctx, args):
2509 c = args[0]
2510 if aliases.get(c, None) != None:
2511 c = aliases[c]
2512 ci = commands.get(c,None)
2513 if ci == None:
2514 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
2515 return 0
2516 if ctx['remote'] and ctx['vb'] is None:
2517 if c not in ['connect', 'reconnect', 'help', 'quit']:
2518 print "First connect to remote server with %s command." %(colored('connect', 'blue'))
2519 return 0
2520 return ci[1](ctx, args)
2521
2522
2523def runCommand(ctx, cmd):
2524 if len(cmd) == 0: return 0
2525 args = split_no_quotes(cmd)
2526 if len(args) == 0: return 0
2527 return runCommandArgs(ctx, args)
2528
2529#
2530# To write your own custom commands to vboxshell, create
2531# file ~/.VirtualBox/shellext.py with content like
2532#
2533# def runTestCmd(ctx, args):
2534# print "Testy test", ctx['vb']
2535# return 0
2536#
2537# commands = {
2538# 'test': ['Test help', runTestCmd]
2539# }
2540# and issue reloadExt shell command.
2541# This file also will be read automatically on startup or 'reloadExt'.
2542#
2543# Also one can put shell extensions into ~/.VirtualBox/shexts and
2544# they will also be picked up, so this way one can exchange
2545# shell extensions easily.
2546def addExtsFromFile(ctx, cmds, file):
2547 if not os.path.isfile(file):
2548 return
2549 d = {}
2550 try:
2551 execfile(file, d, d)
2552 for (k,v) in d['commands'].items():
2553 if g_verbose:
2554 print "customize: adding \"%s\" - %s" %(k, v[0])
2555 cmds[k] = [v[0], v[1], file]
2556 except:
2557 print "Error loading user extensions from %s" %(file)
2558 traceback.print_exc()
2559
2560
2561def checkUserExtensions(ctx, cmds, folder):
2562 folder = str(folder)
2563 name = os.path.join(folder, "shellext.py")
2564 addExtsFromFile(ctx, cmds, name)
2565 # also check 'exts' directory for all files
2566 shextdir = os.path.join(folder, "shexts")
2567 if not os.path.isdir(shextdir):
2568 return
2569 exts = os.listdir(shextdir)
2570 for e in exts:
2571 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
2572
2573def getHomeFolder(ctx):
2574 if ctx['remote'] or ctx['vb'] is None:
2575 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
2576 else:
2577 return ctx['vb'].homeFolder
2578
2579def interpret(ctx):
2580 if ctx['remote']:
2581 commands['connect'] = ["Connect to remote VBox instance: connect http://server:18083 user password", connectCmd, 0]
2582 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
2583 commands['reconnect'] = ["Reconnect to remote VBox instance", reconnectCmd, 0]
2584 ctx['wsinfo'] = ["http://localhost:18083", "", ""]
2585
2586 vbox = ctx['vb']
2587
2588 if vbox is not None:
2589 print "Running VirtualBox version %s" %(vbox.version)
2590 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
2591 else:
2592 ctx['perf'] = None
2593
2594 home = getHomeFolder(ctx)
2595 checkUserExtensions(ctx, commands, home)
2596 if platform.system() == 'Windows':
2597 global g_hascolors
2598 g_hascolors = False
2599 hist_file=os.path.join(home, ".vboxshellhistory")
2600 autoCompletion(commands, ctx)
2601
2602 if g_hasreadline and os.path.exists(hist_file):
2603 readline.read_history_file(hist_file)
2604
2605 # to allow to print actual host information, we collect info for
2606 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
2607 if ctx['perf']:
2608 try:
2609 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
2610 except:
2611 pass
2612
2613 while True:
2614 try:
2615 cmd = raw_input("vbox> ")
2616 done = runCommand(ctx, cmd)
2617 if done != 0: break
2618 except KeyboardInterrupt:
2619 print '====== You can type quit or q to leave'
2620 except EOFError:
2621 break
2622 except Exception,e:
2623 printErr(ctx,e)
2624 if g_verbose:
2625 traceback.print_exc()
2626 ctx['global'].waitForEvents(0)
2627 try:
2628 # There is no need to disable metric collection. This is just an example.
2629 if ct['perf']:
2630 ctx['perf'].disable(['*'], [vbox.host])
2631 except:
2632 pass
2633 if g_hasreadline:
2634 readline.write_history_file(hist_file)
2635
2636def runCommandCb(ctx, cmd, args):
2637 args.insert(0, cmd)
2638 return runCommandArgs(ctx, args)
2639
2640def runGuestCommandCb(ctx, id, guestLambda, args):
2641 mach = machById(ctx,id)
2642 if mach == None:
2643 return 0
2644 args.insert(0, guestLambda)
2645 cmdExistingVm(ctx, mach, 'guestlambda', args)
2646 return 0
2647
2648def main(argv):
2649 style = None
2650 autopath = False
2651 argv.pop(0)
2652 while len(argv) > 0:
2653 if argv[0] == "-w":
2654 style = "WEBSERVICE"
2655 if argv[0] == "-a":
2656 autopath = True
2657 argv.pop(0)
2658
2659 if autopath:
2660 cwd = os.getcwd()
2661 vpp = os.environ.get("VBOX_PROGRAM_PATH")
2662 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
2663 vpp = cwd
2664 print "Autodetected VBOX_PROGRAM_PATH as",vpp
2665 os.environ["VBOX_PROGRAM_PATH"] = cwd
2666 sys.path.append(os.path.join(vpp, "sdk", "installer"))
2667
2668 from vboxapi import VirtualBoxManager
2669 g_virtualBoxManager = VirtualBoxManager(style, None)
2670 ctx = {'global':g_virtualBoxManager,
2671 'mgr':g_virtualBoxManager.mgr,
2672 'vb':g_virtualBoxManager.vbox,
2673 'ifaces':g_virtualBoxManager.constants,
2674 'remote':g_virtualBoxManager.remote,
2675 'type':g_virtualBoxManager.type,
2676 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
2677 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
2678 'machById': lambda id: machById(ctx,id),
2679 'argsToMach': lambda args: argsToMach(ctx,args),
2680 'progressBar': lambda p: progressBar(ctx,p),
2681 'typeInGuest': typeInGuest,
2682 '_machlist':None
2683 }
2684 interpret(ctx)
2685 g_virtualBoxManager.deinit()
2686 del g_virtualBoxManager
2687
2688if __name__ == '__main__':
2689 main(sys.argv)
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette