VirtualBox

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

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

python shell: only running VM to be used here

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