1 | #!/usr/bin/python
|
---|
2 | #
|
---|
3 | # Copyright (C) 2009 Sun Microsystems, Inc.
|
---|
4 | #
|
---|
5 | # This file is part of VirtualBox Open Source Edition (OSE), as
|
---|
6 | # available from http://www.virtualbox.org. This file is free software;
|
---|
7 | # you can redistribute it and/or modify it under the terms of the GNU
|
---|
8 | # General Public License (GPL) as published by the Free Software
|
---|
9 | # Foundation, in version 2 as it comes in the "COPYING" file of the
|
---|
10 | # VirtualBox OSE distribution. VirtualBox OSE is distributed in the
|
---|
11 | # hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
|
---|
12 | #
|
---|
13 | # Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
|
---|
14 | # Clara, CA 95054 USA or visit http://www.sun.com if you need
|
---|
15 | # additional information or have any questions.
|
---|
16 | #
|
---|
17 | #################################################################################
|
---|
18 | # This program is a simple interactive shell for VirtualBox. You can query #
|
---|
19 | # information and issue commands from a simple command line. #
|
---|
20 | # #
|
---|
21 | # It also provides you with examples on how to use VirtualBox's Python API. #
|
---|
22 | # This shell is even somewhat documented and supports TAB-completion and #
|
---|
23 | # history if you have Python readline installed. #
|
---|
24 | # #
|
---|
25 | # Enjoy. #
|
---|
26 | ################################################################################
|
---|
27 |
|
---|
28 | import os,sys
|
---|
29 | import traceback
|
---|
30 | import shlex
|
---|
31 | import time
|
---|
32 |
|
---|
33 | # Simple implementation of IConsoleCallback, one can use it as skeleton
|
---|
34 | # for custom implementations
|
---|
35 | class 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, needsHostCursor):
|
---|
42 | print "%s: onMouseCapabilityChange: needsHostCursor=%d" %(self.mach.name, 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 |
|
---|
90 | class 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 onSnapshotDiscarded(self, mach, id):
|
---|
127 | print "onSnapshotDiscarded: %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 |
|
---|
135 | g_hasreadline = 1
|
---|
136 | try:
|
---|
137 | import readline
|
---|
138 | import rlcompleter
|
---|
139 | except:
|
---|
140 | g_hasreadline = 0
|
---|
141 |
|
---|
142 |
|
---|
143 | if g_hasreadline:
|
---|
144 | class CompleterNG(rlcompleter.Completer):
|
---|
145 | def __init__(self, dic, ctx):
|
---|
146 | self.ctx = ctx
|
---|
147 | return rlcompleter.Completer.__init__(self,dic)
|
---|
148 |
|
---|
149 | def complete(self, text, state):
|
---|
150 | """
|
---|
151 | taken from:
|
---|
152 | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
|
---|
153 | """
|
---|
154 | if text == "":
|
---|
155 | return ['\t',None][state]
|
---|
156 | else:
|
---|
157 | return rlcompleter.Completer.complete(self,text,state)
|
---|
158 |
|
---|
159 | def global_matches(self, text):
|
---|
160 | """
|
---|
161 | Compute matches when text is a simple name.
|
---|
162 | Return a list of all names currently defined
|
---|
163 | in self.namespace that match.
|
---|
164 | """
|
---|
165 |
|
---|
166 | matches = []
|
---|
167 | n = len(text)
|
---|
168 |
|
---|
169 | for list in [ self.namespace ]:
|
---|
170 | for word in list:
|
---|
171 | if word[:n] == text:
|
---|
172 | matches.append(word)
|
---|
173 |
|
---|
174 |
|
---|
175 | try:
|
---|
176 | for m in getMachines(self.ctx):
|
---|
177 | # although it has autoconversion, we need to cast
|
---|
178 | # explicitly for subscripts to work
|
---|
179 | word = str(m.name)
|
---|
180 | if word[:n] == text:
|
---|
181 | matches.append(word)
|
---|
182 | word = str(m.id)
|
---|
183 | if word[0] == '{':
|
---|
184 | word = word[1:-1]
|
---|
185 | if word[:n] == text:
|
---|
186 | matches.append(word)
|
---|
187 | except Exception,e:
|
---|
188 | traceback.print_exc()
|
---|
189 | print e
|
---|
190 |
|
---|
191 | return matches
|
---|
192 |
|
---|
193 |
|
---|
194 | def autoCompletion(commands, ctx):
|
---|
195 | if not g_hasreadline:
|
---|
196 | return
|
---|
197 |
|
---|
198 | comps = {}
|
---|
199 | for (k,v) in commands.items():
|
---|
200 | comps[k] = None
|
---|
201 | completer = CompleterNG(comps, ctx)
|
---|
202 | readline.set_completer(completer.complete)
|
---|
203 | readline.parse_and_bind("tab: complete")
|
---|
204 |
|
---|
205 | g_verbose = True
|
---|
206 |
|
---|
207 | def split_no_quotes(s):
|
---|
208 | return shlex.split(s)
|
---|
209 |
|
---|
210 | def progressBar(ctx,p,wait=1000):
|
---|
211 | try:
|
---|
212 | while not p.completed:
|
---|
213 | print "%d %%\r" %(p.percent),
|
---|
214 | sys.stdout.flush()
|
---|
215 | p.waitForCompletion(wait)
|
---|
216 | ctx['global'].waitForEvents(0)
|
---|
217 | except KeyboardInterrupt:
|
---|
218 | print "Interrupted."
|
---|
219 |
|
---|
220 |
|
---|
221 | def createVm(ctx,name,kind,base):
|
---|
222 | mgr = ctx['mgr']
|
---|
223 | vb = ctx['vb']
|
---|
224 | mach = vb.createMachine(name, kind, base, "")
|
---|
225 | mach.saveSettings()
|
---|
226 | print "created machine with UUID",mach.id
|
---|
227 | vb.registerMachine(mach)
|
---|
228 | # update cache
|
---|
229 | getMachines(ctx, True)
|
---|
230 |
|
---|
231 | def removeVm(ctx,mach):
|
---|
232 | mgr = ctx['mgr']
|
---|
233 | vb = ctx['vb']
|
---|
234 | id = mach.id
|
---|
235 | print "removing machine ",mach.name,"with UUID",id
|
---|
236 | session = ctx['global'].openMachineSession(id)
|
---|
237 | try:
|
---|
238 | mach = session.machine
|
---|
239 | for d in ctx['global'].getArray(mach, 'hardDiskAttachments'):
|
---|
240 | mach.detachHardDisk(d.controller, d.port, d.device)
|
---|
241 | except:
|
---|
242 | traceback.print_exc()
|
---|
243 | mach.saveSettings()
|
---|
244 | ctx['global'].closeMachineSession(session)
|
---|
245 | mach = vb.unregisterMachine(id)
|
---|
246 | if mach:
|
---|
247 | mach.deleteSettings()
|
---|
248 | # update cache
|
---|
249 | getMachines(ctx, True)
|
---|
250 |
|
---|
251 | def startVm(ctx,mach,type):
|
---|
252 | mgr = ctx['mgr']
|
---|
253 | vb = ctx['vb']
|
---|
254 | perf = ctx['perf']
|
---|
255 | session = mgr.getSessionObject(vb)
|
---|
256 | uuid = mach.id
|
---|
257 | progress = vb.openRemoteSession(session, uuid, type, "")
|
---|
258 | progressBar(ctx, progress, 100)
|
---|
259 | completed = progress.completed
|
---|
260 | rc = int(progress.resultCode)
|
---|
261 | print "Completed:", completed, "rc:",hex(rc&0xffffffff)
|
---|
262 | if rc == 0:
|
---|
263 | # we ignore exceptions to allow starting VM even if
|
---|
264 | # perf collector cannot be started
|
---|
265 | if perf:
|
---|
266 | try:
|
---|
267 | perf.setup(['*'], [mach], 10, 15)
|
---|
268 | except Exception,e:
|
---|
269 | print e
|
---|
270 | if g_verbose:
|
---|
271 | traceback.print_exc()
|
---|
272 | pass
|
---|
273 | # if session not opened, close doesn't make sense
|
---|
274 | session.close()
|
---|
275 | else:
|
---|
276 | # Not yet implemented error string query API for remote API
|
---|
277 | if not ctx['remote']:
|
---|
278 | print session.QueryErrorObject(rc)
|
---|
279 |
|
---|
280 | def getMachines(ctx, invalidate = False):
|
---|
281 | if ctx['vb'] is not None:
|
---|
282 | if ctx['_machlist'] is None or invalidate:
|
---|
283 | ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
|
---|
284 | return ctx['_machlist']
|
---|
285 | else:
|
---|
286 | return []
|
---|
287 |
|
---|
288 | def asState(var):
|
---|
289 | if var:
|
---|
290 | return 'on'
|
---|
291 | else:
|
---|
292 | return 'off'
|
---|
293 |
|
---|
294 | def guestStats(ctx,mach):
|
---|
295 | if not ctx['perf']:
|
---|
296 | return
|
---|
297 | for metric in ctx['perf'].query(["*"], [mach]):
|
---|
298 | print metric['name'], metric['values_as_string']
|
---|
299 |
|
---|
300 | def guestExec(ctx, machine, console, cmds):
|
---|
301 | exec cmds
|
---|
302 |
|
---|
303 | def monitorGuest(ctx, machine, console, dur):
|
---|
304 | cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
|
---|
305 | console.registerCallback(cb)
|
---|
306 | if dur == -1:
|
---|
307 | # not infinity, but close enough
|
---|
308 | dur = 100000
|
---|
309 | try:
|
---|
310 | end = time.time() + dur
|
---|
311 | while time.time() < end:
|
---|
312 | ctx['global'].waitForEvents(500)
|
---|
313 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
314 | except:
|
---|
315 | pass
|
---|
316 | console.unregisterCallback(cb)
|
---|
317 |
|
---|
318 |
|
---|
319 | def monitorVBox(ctx, dur):
|
---|
320 | vbox = ctx['vb']
|
---|
321 | isMscom = (ctx['global'].type == 'MSCOM')
|
---|
322 | cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
|
---|
323 | vbox.registerCallback(cb)
|
---|
324 | if dur == -1:
|
---|
325 | # not infinity, but close enough
|
---|
326 | dur = 100000
|
---|
327 | try:
|
---|
328 | end = time.time() + dur
|
---|
329 | while time.time() < end:
|
---|
330 | ctx['global'].waitForEvents(500)
|
---|
331 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
332 | except:
|
---|
333 | pass
|
---|
334 | vbox.unregisterCallback(cb)
|
---|
335 |
|
---|
336 | def cmdExistingVm(ctx,mach,cmd,args):
|
---|
337 | mgr=ctx['mgr']
|
---|
338 | vb=ctx['vb']
|
---|
339 | session = mgr.getSessionObject(vb)
|
---|
340 | uuid = mach.id
|
---|
341 | try:
|
---|
342 | progress = vb.openExistingSession(session, uuid)
|
---|
343 | except Exception,e:
|
---|
344 | print "Session to '%s' not open: %s" %(mach.name,e)
|
---|
345 | if g_verbose:
|
---|
346 | traceback.print_exc()
|
---|
347 | return
|
---|
348 | if session.state != ctx['ifaces'].SessionState_Open:
|
---|
349 | print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
|
---|
350 | return
|
---|
351 | # unfortunately IGuest is suppressed, thus WebServices knows not about it
|
---|
352 | # this is an example how to handle local only functionality
|
---|
353 | if ctx['remote'] and cmd == 'stats2':
|
---|
354 | print 'Trying to use local only functionality, ignored'
|
---|
355 | return
|
---|
356 | console=session.console
|
---|
357 | ops={'pause': lambda: console.pause(),
|
---|
358 | 'resume': lambda: console.resume(),
|
---|
359 | 'powerdown': lambda: console.powerDown(),
|
---|
360 | 'powerbutton': lambda: console.powerButton(),
|
---|
361 | 'stats': lambda: guestStats(ctx, mach),
|
---|
362 | 'guest': lambda: guestExec(ctx, mach, console, args),
|
---|
363 | 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
|
---|
364 | 'save': lambda: progressBar(ctx,console.saveState())
|
---|
365 | }
|
---|
366 | try:
|
---|
367 | ops[cmd]()
|
---|
368 | except Exception, e:
|
---|
369 | print 'failed: ',e
|
---|
370 | if g_verbose:
|
---|
371 | traceback.print_exc()
|
---|
372 |
|
---|
373 | session.close()
|
---|
374 |
|
---|
375 | def machById(ctx,id):
|
---|
376 | mach = None
|
---|
377 | for m in getMachines(ctx):
|
---|
378 | if m.name == id:
|
---|
379 | mach = m
|
---|
380 | break
|
---|
381 | mid = str(m.id)
|
---|
382 | if mid[0] == '{':
|
---|
383 | mid = mid[1:-1]
|
---|
384 | if mid == id:
|
---|
385 | mach = m
|
---|
386 | break
|
---|
387 | return mach
|
---|
388 |
|
---|
389 | def argsToMach(ctx,args):
|
---|
390 | if len(args) < 2:
|
---|
391 | print "usage: %s [vmname|uuid]" %(args[0])
|
---|
392 | return None
|
---|
393 | id = args[1]
|
---|
394 | m = machById(ctx, id)
|
---|
395 | if m == None:
|
---|
396 | print "Machine '%s' is unknown, use list command to find available machines" %(id)
|
---|
397 | return m
|
---|
398 |
|
---|
399 | def helpSingleCmd(cmd,h,sp):
|
---|
400 | if sp != 0:
|
---|
401 | spec = " [ext from "+sp+"]"
|
---|
402 | else:
|
---|
403 | spec = ""
|
---|
404 | print " %s: %s%s" %(cmd,h,spec)
|
---|
405 |
|
---|
406 | def helpCmd(ctx, args):
|
---|
407 | if len(args) == 1:
|
---|
408 | print "Help page:"
|
---|
409 | names = commands.keys()
|
---|
410 | names.sort()
|
---|
411 | for i in names:
|
---|
412 | helpSingleCmd(i, commands[i][0], commands[i][2])
|
---|
413 | else:
|
---|
414 | cmd = args[1]
|
---|
415 | c = commands.get(cmd)
|
---|
416 | if c == None:
|
---|
417 | print "Command '%s' not known" %(cmd)
|
---|
418 | else:
|
---|
419 | helpSingleCmd(cmd, c[0], c[2])
|
---|
420 | return 0
|
---|
421 |
|
---|
422 | def listCmd(ctx, args):
|
---|
423 | for m in getMachines(ctx, True):
|
---|
424 | print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
|
---|
425 | return 0
|
---|
426 |
|
---|
427 | def getControllerType(type):
|
---|
428 | if type == 0:
|
---|
429 | return "Null"
|
---|
430 | elif type == 1:
|
---|
431 | return "LsiLogic"
|
---|
432 | elif type == 2:
|
---|
433 | return "BusLogic"
|
---|
434 | elif type == 3:
|
---|
435 | return "IntelAhci"
|
---|
436 | elif type == 4:
|
---|
437 | return "PIIX3"
|
---|
438 | elif type == 5:
|
---|
439 | return "PIIX4"
|
---|
440 | elif type == 6:
|
---|
441 | return "ICH6"
|
---|
442 | else:
|
---|
443 | return "Unknown"
|
---|
444 |
|
---|
445 | def infoCmd(ctx,args):
|
---|
446 | if (len(args) < 2):
|
---|
447 | print "usage: info [vmname|uuid]"
|
---|
448 | return 0
|
---|
449 | mach = argsToMach(ctx,args)
|
---|
450 | if mach == None:
|
---|
451 | return 0
|
---|
452 | os = ctx['vb'].getGuestOSType(mach.OSTypeId)
|
---|
453 | print " One can use setvar <mach> <var> <value> to change variable, using name in []."
|
---|
454 | print " Name [name]: %s" %(mach.name)
|
---|
455 | print " ID [n/a]: %s" %(mach.id)
|
---|
456 | print " OS Type [n/a]: %s" %(os.description)
|
---|
457 | print
|
---|
458 | print " CPUs [CPUCount]: %d" %(mach.CPUCount)
|
---|
459 | print " RAM [memorySize]: %dM" %(mach.memorySize)
|
---|
460 | print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
|
---|
461 | print " Monitors [monitorCount]: %d" %(mach.monitorCount)
|
---|
462 | print
|
---|
463 | print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
|
---|
464 | print " Machine status [n/a]: %d" % (mach.sessionState)
|
---|
465 | print
|
---|
466 | bios = mach.BIOSSettings
|
---|
467 | print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
|
---|
468 | print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
|
---|
469 | print " PAE [PAEEnabled]: %s" %(asState(int(mach.PAEEnabled)))
|
---|
470 | print " Hardware virtualization [HWVirtExEnabled]: " + asState(mach.HWVirtExEnabled)
|
---|
471 | print " VPID support [HWVirtExVPIDEnabled]: " + asState(mach.HWVirtExVPIDEnabled)
|
---|
472 | print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
|
---|
473 | print " Nested paging [HWVirtExNestedPagingEnabled]: " + asState(mach.HWVirtExNestedPagingEnabled)
|
---|
474 | print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
|
---|
475 | print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
|
---|
476 |
|
---|
477 | controllers = ctx['global'].getArray(mach, 'storageControllers')
|
---|
478 | if controllers:
|
---|
479 | print
|
---|
480 | print " Controllers:"
|
---|
481 | for controller in controllers:
|
---|
482 | print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
|
---|
483 |
|
---|
484 | disks = ctx['global'].getArray(mach, 'hardDiskAttachments')
|
---|
485 | if disks:
|
---|
486 | print
|
---|
487 | print " Hard disk(s):"
|
---|
488 | for disk in disks:
|
---|
489 | print " Controller: %s port: %d device: %d:" % (disk.controller, disk.port, disk.device)
|
---|
490 | hd = disk.hardDisk
|
---|
491 | print " id: %s" %(hd.id)
|
---|
492 | print " location: %s" %(hd.location)
|
---|
493 | print " name: %s" %(hd.name)
|
---|
494 | print " format: %s" %(hd.format)
|
---|
495 | print
|
---|
496 |
|
---|
497 | dvd = mach.DVDDrive
|
---|
498 | if dvd.getHostDrive():
|
---|
499 | hdvd = dvd.getHostDrive()
|
---|
500 | print " DVD:"
|
---|
501 | print " Host disk: %s" %(hdvd.name)
|
---|
502 | print
|
---|
503 |
|
---|
504 | if dvd.getImage():
|
---|
505 | vdvd = dvd.getImage()
|
---|
506 | print " DVD:"
|
---|
507 | print " Image at: %s" %(vdvd.location)
|
---|
508 | print " Size: %s" %(vdvd.size)
|
---|
509 | print " Id: %s" %(vdvd.id)
|
---|
510 | print
|
---|
511 |
|
---|
512 | floppy = mach.floppyDrive
|
---|
513 | if floppy.getHostDrive():
|
---|
514 | hfloppy = floppy.getHostDrive()
|
---|
515 | print " Floppy:"
|
---|
516 | print " Host disk: %s" %(hfloppy.name)
|
---|
517 | print
|
---|
518 |
|
---|
519 | if floppy.getImage():
|
---|
520 | vfloppy = floppy.getImage()
|
---|
521 | print " Floppy:"
|
---|
522 | print " Image at: %s" %(vfloppy.location)
|
---|
523 | print " Size: %s" %(vfloppy.size)
|
---|
524 | print
|
---|
525 |
|
---|
526 | return 0
|
---|
527 |
|
---|
528 | def startCmd(ctx, args):
|
---|
529 | mach = argsToMach(ctx,args)
|
---|
530 | if mach == None:
|
---|
531 | return 0
|
---|
532 | if len(args) > 2:
|
---|
533 | type = args[2]
|
---|
534 | else:
|
---|
535 | type = "gui"
|
---|
536 | startVm(ctx, mach, type)
|
---|
537 | return 0
|
---|
538 |
|
---|
539 | def createCmd(ctx, args):
|
---|
540 | if (len(args) < 3 or len(args) > 4):
|
---|
541 | print "usage: create name ostype <basefolder>"
|
---|
542 | return 0
|
---|
543 | name = args[1]
|
---|
544 | oskind = args[2]
|
---|
545 | if len(args) == 4:
|
---|
546 | base = args[3]
|
---|
547 | else:
|
---|
548 | base = ''
|
---|
549 | try:
|
---|
550 | ctx['vb'].getGuestOSType(oskind)
|
---|
551 | except Exception, e:
|
---|
552 | print 'Unknown OS type:',oskind
|
---|
553 | return 0
|
---|
554 | createVm(ctx, name, oskind, base)
|
---|
555 | return 0
|
---|
556 |
|
---|
557 | def removeCmd(ctx, args):
|
---|
558 | mach = argsToMach(ctx,args)
|
---|
559 | if mach == None:
|
---|
560 | return 0
|
---|
561 | removeVm(ctx, mach)
|
---|
562 | return 0
|
---|
563 |
|
---|
564 | def pauseCmd(ctx, args):
|
---|
565 | mach = argsToMach(ctx,args)
|
---|
566 | if mach == None:
|
---|
567 | return 0
|
---|
568 | cmdExistingVm(ctx, mach, 'pause', '')
|
---|
569 | return 0
|
---|
570 |
|
---|
571 | def powerdownCmd(ctx, args):
|
---|
572 | mach = argsToMach(ctx,args)
|
---|
573 | if mach == None:
|
---|
574 | return 0
|
---|
575 | cmdExistingVm(ctx, mach, 'powerdown', '')
|
---|
576 | return 0
|
---|
577 |
|
---|
578 | def powerbuttonCmd(ctx, args):
|
---|
579 | mach = argsToMach(ctx,args)
|
---|
580 | if mach == None:
|
---|
581 | return 0
|
---|
582 | cmdExistingVm(ctx, mach, 'powerbutton', '')
|
---|
583 | return 0
|
---|
584 |
|
---|
585 | def resumeCmd(ctx, args):
|
---|
586 | mach = argsToMach(ctx,args)
|
---|
587 | if mach == None:
|
---|
588 | return 0
|
---|
589 | cmdExistingVm(ctx, mach, 'resume', '')
|
---|
590 | return 0
|
---|
591 |
|
---|
592 | def saveCmd(ctx, args):
|
---|
593 | mach = argsToMach(ctx,args)
|
---|
594 | if mach == None:
|
---|
595 | return 0
|
---|
596 | cmdExistingVm(ctx, mach, 'save', '')
|
---|
597 | return 0
|
---|
598 |
|
---|
599 | def statsCmd(ctx, args):
|
---|
600 | mach = argsToMach(ctx,args)
|
---|
601 | if mach == None:
|
---|
602 | return 0
|
---|
603 | cmdExistingVm(ctx, mach, 'stats', '')
|
---|
604 | return 0
|
---|
605 |
|
---|
606 | def guestCmd(ctx, args):
|
---|
607 | if (len(args) < 3):
|
---|
608 | print "usage: guest name commands"
|
---|
609 | return 0
|
---|
610 | mach = argsToMach(ctx,args)
|
---|
611 | if mach == None:
|
---|
612 | return 0
|
---|
613 | cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
|
---|
614 | return 0
|
---|
615 |
|
---|
616 | def setvarCmd(ctx, args):
|
---|
617 | if (len(args) < 4):
|
---|
618 | print "usage: setvar [vmname|uuid] expr value"
|
---|
619 | return 0
|
---|
620 | mach = argsToMach(ctx,args)
|
---|
621 | if mach == None:
|
---|
622 | return 0
|
---|
623 | session = ctx['global'].openMachineSession(mach.id)
|
---|
624 | mach = session.machine
|
---|
625 | expr = 'mach.'+args[2]+' = '+args[3]
|
---|
626 | print "Executing",expr
|
---|
627 | try:
|
---|
628 | exec expr
|
---|
629 | except Exception, e:
|
---|
630 | print 'failed: ',e
|
---|
631 | if g_verbose:
|
---|
632 | traceback.print_exc()
|
---|
633 | mach.saveSettings()
|
---|
634 | session.close()
|
---|
635 | return 0
|
---|
636 |
|
---|
637 | def quitCmd(ctx, args):
|
---|
638 | return 1
|
---|
639 |
|
---|
640 | def aliasCmd(ctx, args):
|
---|
641 | if (len(args) == 3):
|
---|
642 | aliases[args[1]] = args[2]
|
---|
643 | return 0
|
---|
644 |
|
---|
645 | for (k,v) in aliases.items():
|
---|
646 | print "'%s' is an alias for '%s'" %(k,v)
|
---|
647 | return 0
|
---|
648 |
|
---|
649 | def verboseCmd(ctx, args):
|
---|
650 | global g_verbose
|
---|
651 | g_verbose = not g_verbose
|
---|
652 | return 0
|
---|
653 |
|
---|
654 | def getUSBStateString(state):
|
---|
655 | if state == 0:
|
---|
656 | return "NotSupported"
|
---|
657 | elif state == 1:
|
---|
658 | return "Unavailable"
|
---|
659 | elif state == 2:
|
---|
660 | return "Busy"
|
---|
661 | elif state == 3:
|
---|
662 | return "Available"
|
---|
663 | elif state == 4:
|
---|
664 | return "Held"
|
---|
665 | elif state == 5:
|
---|
666 | return "Captured"
|
---|
667 | else:
|
---|
668 | return "Unknown"
|
---|
669 |
|
---|
670 | def hostCmd(ctx, args):
|
---|
671 | host = ctx['vb'].host
|
---|
672 | cnt = host.processorCount
|
---|
673 | print "Processor count:",cnt
|
---|
674 | for i in range(0,cnt):
|
---|
675 | print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
|
---|
676 |
|
---|
677 | print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
|
---|
678 | print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
|
---|
679 | if host.Acceleration3DAvailable:
|
---|
680 | print "3D acceleration available"
|
---|
681 | else:
|
---|
682 | print "3D acceleration NOT available"
|
---|
683 |
|
---|
684 | print "Network interfaces:"
|
---|
685 | for ni in ctx['global'].getArray(host, 'networkInterfaces'):
|
---|
686 | print " %s (%s)" %(ni.name, ni.IPAddress)
|
---|
687 |
|
---|
688 | print "DVD drives:"
|
---|
689 | for dd in ctx['global'].getArray(host, 'DVDDrives'):
|
---|
690 | print " %s - %s" %(dd.name, dd.description)
|
---|
691 |
|
---|
692 | print "USB devices:"
|
---|
693 | for ud in ctx['global'].getArray(host, 'USBDevices'):
|
---|
694 | print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
|
---|
695 |
|
---|
696 | if ctx['perf']:
|
---|
697 | for metric in ctx['perf'].query(["*"], [host]):
|
---|
698 | print metric['name'], metric['values_as_string']
|
---|
699 |
|
---|
700 | return 0
|
---|
701 |
|
---|
702 | def monitorGuestCmd(ctx, args):
|
---|
703 | if (len(args) < 2):
|
---|
704 | print "usage: monitorGuest name (duration)"
|
---|
705 | return 0
|
---|
706 | mach = argsToMach(ctx,args)
|
---|
707 | if mach == None:
|
---|
708 | return 0
|
---|
709 | dur = 5
|
---|
710 | if len(args) > 2:
|
---|
711 | dur = float(args[2])
|
---|
712 | cmdExistingVm(ctx, mach, 'monitorGuest', dur)
|
---|
713 | return 0
|
---|
714 |
|
---|
715 | def monitorVBoxCmd(ctx, args):
|
---|
716 | if (len(args) > 2):
|
---|
717 | print "usage: monitorVBox (duration)"
|
---|
718 | return 0
|
---|
719 | dur = 5
|
---|
720 | if len(args) > 1:
|
---|
721 | dur = float(args[1])
|
---|
722 | monitorVBox(ctx, dur)
|
---|
723 | return 0
|
---|
724 |
|
---|
725 | def getAdapterType(ctx, type):
|
---|
726 | if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
|
---|
727 | type == ctx['global'].constants.NetworkAdapterType_Am79C973):
|
---|
728 | return "pcnet"
|
---|
729 | elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
|
---|
730 | type == ctx['global'].constants.NetworkAdapterType_I82545EM or
|
---|
731 | type == ctx['global'].constants.NetworkAdapterType_I82543GC):
|
---|
732 | return "e1000"
|
---|
733 | elif (type == ctx['global'].constants.NetworkAdapterType_Null):
|
---|
734 | return None
|
---|
735 | else:
|
---|
736 | raise Exception("Unknown adapter type: "+type)
|
---|
737 |
|
---|
738 |
|
---|
739 | def portForwardCmd(ctx, args):
|
---|
740 | if (len(args) != 5):
|
---|
741 | print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
|
---|
742 | return 0
|
---|
743 | mach = argsToMach(ctx,args)
|
---|
744 | if mach == None:
|
---|
745 | return 0
|
---|
746 | adapterNum = int(args[2])
|
---|
747 | hostPort = int(args[3])
|
---|
748 | guestPort = int(args[4])
|
---|
749 | proto = "TCP"
|
---|
750 | session = ctx['global'].openMachineSession(mach.id)
|
---|
751 | mach = session.machine
|
---|
752 |
|
---|
753 | adapter = mach.getNetworkAdapter(adapterNum)
|
---|
754 | adapterType = getAdapterType(ctx, adapter.adapterType)
|
---|
755 |
|
---|
756 | profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
|
---|
757 | config = "VBoxInternal/Devices/" + adapterType + "/"
|
---|
758 | config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
|
---|
759 |
|
---|
760 | mach.setExtraData(config + "/Protocol", proto)
|
---|
761 | mach.setExtraData(config + "/HostPort", str(hostPort))
|
---|
762 | mach.setExtraData(config + "/GuestPort", str(guestPort))
|
---|
763 |
|
---|
764 | mach.saveSettings()
|
---|
765 | session.close()
|
---|
766 |
|
---|
767 | return 0
|
---|
768 |
|
---|
769 |
|
---|
770 | def showLogCmd(ctx, args):
|
---|
771 | if (len(args) < 2):
|
---|
772 | print "usage: showLog <vm> <num>"
|
---|
773 | return 0
|
---|
774 | mach = argsToMach(ctx,args)
|
---|
775 | if mach == None:
|
---|
776 | return 0
|
---|
777 |
|
---|
778 | log = "VBox.log"
|
---|
779 | if (len(args) > 2):
|
---|
780 | log += "."+args[2]
|
---|
781 | fileName = os.path.join(mach.logFolder, log)
|
---|
782 |
|
---|
783 | try:
|
---|
784 | lf = open(fileName, 'r')
|
---|
785 | except IOError,e:
|
---|
786 | print "cannot open: ",e
|
---|
787 | return 0
|
---|
788 |
|
---|
789 | for line in lf:
|
---|
790 | print line,
|
---|
791 | lf.close()
|
---|
792 |
|
---|
793 | return 0
|
---|
794 |
|
---|
795 | def evalCmd(ctx, args):
|
---|
796 | expr = ' '.join(args[1:])
|
---|
797 | try:
|
---|
798 | exec expr
|
---|
799 | except Exception, e:
|
---|
800 | print 'failed: ',e
|
---|
801 | if g_verbose:
|
---|
802 | traceback.print_exc()
|
---|
803 | return 0
|
---|
804 |
|
---|
805 | def reloadExtCmd(ctx, args):
|
---|
806 | # maybe will want more args smartness
|
---|
807 | checkUserExtensions(ctx, commands, getHomeFolder(ctx))
|
---|
808 | autoCompletion(commands, ctx)
|
---|
809 | return 0
|
---|
810 |
|
---|
811 |
|
---|
812 | def runScriptCmd(ctx, args):
|
---|
813 | if (len(args) != 2):
|
---|
814 | print "usage: runScript <script>"
|
---|
815 | return 0
|
---|
816 | try:
|
---|
817 | lf = open(args[1], 'r')
|
---|
818 | except IOError,e:
|
---|
819 | print "cannot open:",args[1], ":",e
|
---|
820 | return 0
|
---|
821 |
|
---|
822 | try:
|
---|
823 | for line in lf:
|
---|
824 | done = runCommand(ctx, line)
|
---|
825 | if done != 0: break
|
---|
826 | except Exception,e:
|
---|
827 | print "error:",e
|
---|
828 | if g_verbose:
|
---|
829 | traceback.print_exc()
|
---|
830 | lf.close()
|
---|
831 | return 0
|
---|
832 |
|
---|
833 | def sleepCmd(ctx, args):
|
---|
834 | if (len(args) != 2):
|
---|
835 | print "usage: sleep <secs>"
|
---|
836 | return 0
|
---|
837 |
|
---|
838 | try:
|
---|
839 | time.sleep(float(args[1]))
|
---|
840 | except:
|
---|
841 | # to allow sleep interrupt
|
---|
842 | pass
|
---|
843 | return 0
|
---|
844 |
|
---|
845 |
|
---|
846 | def shellCmd(ctx, args):
|
---|
847 | if (len(args) < 2):
|
---|
848 | print "usage: shell <commands>"
|
---|
849 | return 0
|
---|
850 | cmd = ' '.join(args[1:])
|
---|
851 | try:
|
---|
852 | os.system(cmd)
|
---|
853 | except KeyboardInterrupt:
|
---|
854 | # to allow shell command interruption
|
---|
855 | pass
|
---|
856 | return 0
|
---|
857 |
|
---|
858 |
|
---|
859 | def connectCmd(ctx, args):
|
---|
860 | if (len(args) > 4):
|
---|
861 | print "usage: connect [url] [username] [passwd]"
|
---|
862 | return 0
|
---|
863 |
|
---|
864 | if ctx['vb'] is not None:
|
---|
865 | print "Already connected, disconnect first..."
|
---|
866 | return 0
|
---|
867 |
|
---|
868 | if (len(args) > 1):
|
---|
869 | url = args[1]
|
---|
870 | else:
|
---|
871 | url = None
|
---|
872 |
|
---|
873 | if (len(args) > 2):
|
---|
874 | user = args[2]
|
---|
875 | else:
|
---|
876 | user = ""
|
---|
877 |
|
---|
878 | if (len(args) > 3):
|
---|
879 | passwd = args[3]
|
---|
880 | else:
|
---|
881 | passwd = ""
|
---|
882 |
|
---|
883 | vbox = ctx['global'].platform.connect(url, user, passwd)
|
---|
884 | ctx['vb'] = vbox
|
---|
885 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
886 | ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
|
---|
887 | return 0
|
---|
888 |
|
---|
889 | def disconnectCmd(ctx, args):
|
---|
890 | if (len(args) != 1):
|
---|
891 | print "usage: disconnect"
|
---|
892 | return 0
|
---|
893 |
|
---|
894 | if ctx['vb'] is None:
|
---|
895 | print "Not connected yet."
|
---|
896 | return 0
|
---|
897 |
|
---|
898 | try:
|
---|
899 | ctx['global'].platform.disconnect()
|
---|
900 | except:
|
---|
901 | ctx['vb'] = None
|
---|
902 | raise
|
---|
903 |
|
---|
904 | ctx['vb'] = None
|
---|
905 | return 0
|
---|
906 |
|
---|
907 | def exportVMCmd(ctx, args):
|
---|
908 | import sys
|
---|
909 |
|
---|
910 | if len(args) < 3:
|
---|
911 | print "usage: exportVm <machine> <path> <format> <license>"
|
---|
912 | return 0
|
---|
913 | mach = ctx['machById'](args[1])
|
---|
914 | if mach is None:
|
---|
915 | return 0
|
---|
916 | path = args[2]
|
---|
917 | if (len(args) > 3):
|
---|
918 | format = args[3]
|
---|
919 | else:
|
---|
920 | format = "ovf-1.0"
|
---|
921 | if (len(args) > 4):
|
---|
922 | license = args[4]
|
---|
923 | else:
|
---|
924 | license = "GPL"
|
---|
925 |
|
---|
926 | app = ctx['vb'].createAppliance()
|
---|
927 | desc = mach.export(app)
|
---|
928 | desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
|
---|
929 | p = app.write(format, path)
|
---|
930 | progressBar(ctx, p)
|
---|
931 | print "Exported to %s in format %s" %(path, format)
|
---|
932 | return 0
|
---|
933 |
|
---|
934 | aliases = {'s':'start',
|
---|
935 | 'i':'info',
|
---|
936 | 'l':'list',
|
---|
937 | 'h':'help',
|
---|
938 | 'a':'alias',
|
---|
939 | 'q':'quit', 'exit':'quit',
|
---|
940 | 'v':'verbose'}
|
---|
941 |
|
---|
942 | commands = {'help':['Prints help information', helpCmd, 0],
|
---|
943 | 'start':['Start virtual machine by name or uuid', startCmd, 0],
|
---|
944 | 'create':['Create virtual machine', createCmd, 0],
|
---|
945 | 'remove':['Remove virtual machine', removeCmd, 0],
|
---|
946 | 'pause':['Pause virtual machine', pauseCmd, 0],
|
---|
947 | 'resume':['Resume virtual machine', resumeCmd, 0],
|
---|
948 | 'save':['Save execution state of virtual machine', saveCmd, 0],
|
---|
949 | 'stats':['Stats for virtual machine', statsCmd, 0],
|
---|
950 | 'powerdown':['Power down virtual machine', powerdownCmd, 0],
|
---|
951 | 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
|
---|
952 | 'list':['Shows known virtual machines', listCmd, 0],
|
---|
953 | 'info':['Shows info on machine', infoCmd, 0],
|
---|
954 | 'alias':['Control aliases', aliasCmd, 0],
|
---|
955 | 'verbose':['Toggle verbosity', verboseCmd, 0],
|
---|
956 | 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
|
---|
957 | 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
|
---|
958 | 'quit':['Exits', quitCmd, 0],
|
---|
959 | 'host':['Show host information', hostCmd, 0],
|
---|
960 | 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
|
---|
961 | 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
|
---|
962 | 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
|
---|
963 | 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
|
---|
964 | 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
|
---|
965 | 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
|
---|
966 | 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
|
---|
967 | 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
|
---|
968 | 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
|
---|
969 | 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0]
|
---|
970 | }
|
---|
971 |
|
---|
972 | def runCommandArgs(ctx, args):
|
---|
973 | c = args[0]
|
---|
974 | if aliases.get(c, None) != None:
|
---|
975 | c = aliases[c]
|
---|
976 | ci = commands.get(c,None)
|
---|
977 | if ci == None:
|
---|
978 | print "Unknown command: '%s', type 'help' for list of known commands" %(c)
|
---|
979 | return 0
|
---|
980 | return ci[1](ctx, args)
|
---|
981 |
|
---|
982 |
|
---|
983 | def runCommand(ctx, cmd):
|
---|
984 | if len(cmd) == 0: return 0
|
---|
985 | args = split_no_quotes(cmd)
|
---|
986 | if len(args) == 0: return 0
|
---|
987 | return runCommandArgs(ctx, args)
|
---|
988 |
|
---|
989 | #
|
---|
990 | # To write your own custom commands to vboxshell, create
|
---|
991 | # file ~/.VirtualBox/shellext.py with content like
|
---|
992 | #
|
---|
993 | # def runTestCmd(ctx, args):
|
---|
994 | # print "Testy test", ctx['vb']
|
---|
995 | # return 0
|
---|
996 | #
|
---|
997 | # commands = {
|
---|
998 | # 'test': ['Test help', runTestCmd]
|
---|
999 | # }
|
---|
1000 | # and issue reloadExt shell command.
|
---|
1001 | # This file also will be read automatically on startup or 'reloadExt'.
|
---|
1002 | #
|
---|
1003 | # Also one can put shell extensions into ~/.VirtualBox/shexts and
|
---|
1004 | # they will also be picked up, so this way one can exchange
|
---|
1005 | # shell extensions easily.
|
---|
1006 | def addExtsFromFile(ctx, cmds, file):
|
---|
1007 | if not os.path.isfile(file):
|
---|
1008 | return
|
---|
1009 | d = {}
|
---|
1010 | try:
|
---|
1011 | execfile(file, d, d)
|
---|
1012 | for (k,v) in d['commands'].items():
|
---|
1013 | if g_verbose:
|
---|
1014 | print "customize: adding \"%s\" - %s" %(k, v[0])
|
---|
1015 | cmds[k] = [v[0], v[1], file]
|
---|
1016 | except:
|
---|
1017 | print "Error loading user extensions from %s" %(file)
|
---|
1018 | traceback.print_exc()
|
---|
1019 |
|
---|
1020 |
|
---|
1021 | def checkUserExtensions(ctx, cmds, folder):
|
---|
1022 | folder = str(folder)
|
---|
1023 | name = os.path.join(folder, "shellext.py")
|
---|
1024 | addExtsFromFile(ctx, cmds, name)
|
---|
1025 | # also check 'exts' directory for all files
|
---|
1026 | shextdir = os.path.join(folder, "shexts")
|
---|
1027 | if not os.path.isdir(shextdir):
|
---|
1028 | return
|
---|
1029 | exts = os.listdir(shextdir)
|
---|
1030 | for e in exts:
|
---|
1031 | addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
|
---|
1032 |
|
---|
1033 | def getHomeFolder(ctx):
|
---|
1034 | if ctx['remote'] or ctx['vb'] is None:
|
---|
1035 | return os.path.join(os.path.expanduser("~"), ".VirtualBox")
|
---|
1036 | else:
|
---|
1037 | return ctx['vb'].homeFolder
|
---|
1038 |
|
---|
1039 | def interpret(ctx):
|
---|
1040 | if ctx['remote']:
|
---|
1041 | commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
|
---|
1042 | commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
|
---|
1043 |
|
---|
1044 | vbox = ctx['vb']
|
---|
1045 |
|
---|
1046 | if vbox is not None:
|
---|
1047 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1048 | ctx['perf'] = ctx['global'].getPerfCollector(vbox)
|
---|
1049 | else:
|
---|
1050 | ctx['perf'] = None
|
---|
1051 |
|
---|
1052 | home = getHomeFolder(ctx)
|
---|
1053 | checkUserExtensions(ctx, commands, home)
|
---|
1054 |
|
---|
1055 | autoCompletion(commands, ctx)
|
---|
1056 |
|
---|
1057 | # to allow to print actual host information, we collect info for
|
---|
1058 | # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
|
---|
1059 | if ctx['perf']:
|
---|
1060 | try:
|
---|
1061 | ctx['perf'].setup(['*'], [vbox.host], 10, 15)
|
---|
1062 | except:
|
---|
1063 | pass
|
---|
1064 |
|
---|
1065 | while True:
|
---|
1066 | try:
|
---|
1067 | cmd = raw_input("vbox> ")
|
---|
1068 | done = runCommand(ctx, cmd)
|
---|
1069 | if done != 0: break
|
---|
1070 | except KeyboardInterrupt:
|
---|
1071 | print '====== You can type quit or q to leave'
|
---|
1072 | break
|
---|
1073 | except EOFError:
|
---|
1074 | break;
|
---|
1075 | except Exception,e:
|
---|
1076 | print e
|
---|
1077 | if g_verbose:
|
---|
1078 | traceback.print_exc()
|
---|
1079 | ctx['global'].waitForEvents(0)
|
---|
1080 | try:
|
---|
1081 | # There is no need to disable metric collection. This is just an example.
|
---|
1082 | if ct['perf']:
|
---|
1083 | ctx['perf'].disable(['*'], [vbox.host])
|
---|
1084 | except:
|
---|
1085 | pass
|
---|
1086 |
|
---|
1087 | def runCommandCb(ctx, cmd, args):
|
---|
1088 | args.insert(0, cmd)
|
---|
1089 | return runCommandArgs(ctx, args)
|
---|
1090 |
|
---|
1091 | def main(argv):
|
---|
1092 | style = None
|
---|
1093 | autopath = False
|
---|
1094 | argv.pop(0)
|
---|
1095 | while len(argv) > 0:
|
---|
1096 | if argv[0] == "-w":
|
---|
1097 | style = "WEBSERVICE"
|
---|
1098 | if argv[0] == "-a":
|
---|
1099 | autopath = True
|
---|
1100 | argv.pop(0)
|
---|
1101 |
|
---|
1102 | if autopath:
|
---|
1103 | cwd = os.getcwd()
|
---|
1104 | vpp = os.environ.get("VBOX_PROGRAM_PATH")
|
---|
1105 | if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
|
---|
1106 | vpp = cwd
|
---|
1107 | print "Autodetected VBOX_PROGRAM_PATH as",vpp
|
---|
1108 | os.environ["VBOX_PROGRAM_PATH"] = cwd
|
---|
1109 | sys.path.append(os.path.join(vpp, "sdk", "installer"))
|
---|
1110 |
|
---|
1111 | from vboxapi import VirtualBoxManager
|
---|
1112 | g_virtualBoxManager = VirtualBoxManager(style, None)
|
---|
1113 | ctx = {'global':g_virtualBoxManager,
|
---|
1114 | 'mgr':g_virtualBoxManager.mgr,
|
---|
1115 | 'vb':g_virtualBoxManager.vbox,
|
---|
1116 | 'ifaces':g_virtualBoxManager.constants,
|
---|
1117 | 'remote':g_virtualBoxManager.remote,
|
---|
1118 | 'type':g_virtualBoxManager.type,
|
---|
1119 | 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
|
---|
1120 | 'machById': lambda id: machById(ctx,id),
|
---|
1121 | 'progressBar': lambda p: progressBar(ctx,p),
|
---|
1122 | '_machlist':None
|
---|
1123 | }
|
---|
1124 | interpret(ctx)
|
---|
1125 | g_virtualBoxManager.deinit()
|
---|
1126 | del g_virtualBoxManager
|
---|
1127 |
|
---|
1128 | if __name__ == '__main__':
|
---|
1129 | main(sys.argv)
|
---|