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 reportError(ctx,session,rc):
|
---|
222 | if not ctx['remote']:
|
---|
223 | print session.QueryErrorObject(rc)
|
---|
224 |
|
---|
225 |
|
---|
226 | def createVm(ctx,name,kind,base):
|
---|
227 | mgr = ctx['mgr']
|
---|
228 | vb = ctx['vb']
|
---|
229 | mach = vb.createMachine(name, kind, base, "")
|
---|
230 | mach.saveSettings()
|
---|
231 | print "created machine with UUID",mach.id
|
---|
232 | vb.registerMachine(mach)
|
---|
233 | # update cache
|
---|
234 | getMachines(ctx, True)
|
---|
235 |
|
---|
236 | def removeVm(ctx,mach):
|
---|
237 | mgr = ctx['mgr']
|
---|
238 | vb = ctx['vb']
|
---|
239 | id = mach.id
|
---|
240 | print "removing machine ",mach.name,"with UUID",id
|
---|
241 | session = ctx['global'].openMachineSession(id)
|
---|
242 | try:
|
---|
243 | mach = session.machine
|
---|
244 | for d in ctx['global'].getArray(mach, 'mediumAttachments'):
|
---|
245 | mach.detachDevice(d.controller, d.port, d.device)
|
---|
246 | except:
|
---|
247 | traceback.print_exc()
|
---|
248 | mach.saveSettings()
|
---|
249 | ctx['global'].closeMachineSession(session)
|
---|
250 | mach = vb.unregisterMachine(id)
|
---|
251 | if mach:
|
---|
252 | mach.deleteSettings()
|
---|
253 | # update cache
|
---|
254 | getMachines(ctx, True)
|
---|
255 |
|
---|
256 | def startVm(ctx,mach,type):
|
---|
257 | mgr = ctx['mgr']
|
---|
258 | vb = ctx['vb']
|
---|
259 | perf = ctx['perf']
|
---|
260 | session = mgr.getSessionObject(vb)
|
---|
261 | uuid = mach.id
|
---|
262 | progress = vb.openRemoteSession(session, uuid, type, "")
|
---|
263 | progressBar(ctx, progress, 100)
|
---|
264 | completed = progress.completed
|
---|
265 | rc = int(progress.resultCode)
|
---|
266 | print "Completed:", completed, "rc:",hex(rc&0xffffffff)
|
---|
267 | if rc == 0:
|
---|
268 | # we ignore exceptions to allow starting VM even if
|
---|
269 | # perf collector cannot be started
|
---|
270 | if perf:
|
---|
271 | try:
|
---|
272 | perf.setup(['*'], [mach], 10, 15)
|
---|
273 | except Exception,e:
|
---|
274 | print e
|
---|
275 | if g_verbose:
|
---|
276 | traceback.print_exc()
|
---|
277 | pass
|
---|
278 | # if session not opened, close doesn't make sense
|
---|
279 | session.close()
|
---|
280 | else:
|
---|
281 | reportError(ctx,session,rc)
|
---|
282 |
|
---|
283 | def getMachines(ctx, invalidate = False):
|
---|
284 | if ctx['vb'] is not None:
|
---|
285 | if ctx['_machlist'] is None or invalidate:
|
---|
286 | ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
|
---|
287 | return ctx['_machlist']
|
---|
288 | else:
|
---|
289 | return []
|
---|
290 |
|
---|
291 | def asState(var):
|
---|
292 | if var:
|
---|
293 | return 'on'
|
---|
294 | else:
|
---|
295 | return 'off'
|
---|
296 |
|
---|
297 | def guestStats(ctx,mach):
|
---|
298 | if not ctx['perf']:
|
---|
299 | return
|
---|
300 | for metric in ctx['perf'].query(["*"], [mach]):
|
---|
301 | print metric['name'], metric['values_as_string']
|
---|
302 |
|
---|
303 | def guestExec(ctx, machine, console, cmds):
|
---|
304 | exec cmds
|
---|
305 |
|
---|
306 | def monitorGuest(ctx, machine, console, dur):
|
---|
307 | cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
|
---|
308 | console.registerCallback(cb)
|
---|
309 | if dur == -1:
|
---|
310 | # not infinity, but close enough
|
---|
311 | dur = 100000
|
---|
312 | try:
|
---|
313 | end = time.time() + dur
|
---|
314 | while time.time() < end:
|
---|
315 | ctx['global'].waitForEvents(500)
|
---|
316 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
317 | except:
|
---|
318 | pass
|
---|
319 | console.unregisterCallback(cb)
|
---|
320 |
|
---|
321 |
|
---|
322 | def monitorVBox(ctx, dur):
|
---|
323 | vbox = ctx['vb']
|
---|
324 | isMscom = (ctx['global'].type == 'MSCOM')
|
---|
325 | cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
|
---|
326 | vbox.registerCallback(cb)
|
---|
327 | if dur == -1:
|
---|
328 | # not infinity, but close enough
|
---|
329 | dur = 100000
|
---|
330 | try:
|
---|
331 | end = time.time() + dur
|
---|
332 | while time.time() < end:
|
---|
333 | ctx['global'].waitForEvents(500)
|
---|
334 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
335 | except:
|
---|
336 | pass
|
---|
337 | vbox.unregisterCallback(cb)
|
---|
338 |
|
---|
339 |
|
---|
340 | def takeScreenshot(ctx,console,args):
|
---|
341 | from PIL import Image
|
---|
342 | display = console.display
|
---|
343 | if len(args) > 0:
|
---|
344 | f = args[0]
|
---|
345 | else:
|
---|
346 | f = "/tmp/screenshot.png"
|
---|
347 | if len(args) > 1:
|
---|
348 | w = args[1]
|
---|
349 | else:
|
---|
350 | w = console.display.width
|
---|
351 | if len(args) > 2:
|
---|
352 | h = args[2]
|
---|
353 | else:
|
---|
354 | h = console.display.height
|
---|
355 | print "Saving screenshot (%d x %d) in %s..." %(w,h,f)
|
---|
356 | data = display.takeScreenShotSlow(w,h)
|
---|
357 | size = (w,h)
|
---|
358 | mode = "RGBA"
|
---|
359 | im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
|
---|
360 | im.save(f, "PNG")
|
---|
361 |
|
---|
362 |
|
---|
363 | def teleport(ctx,session,console,args):
|
---|
364 | if args[0].find(":") == -1:
|
---|
365 | print "Use host:port format for teleport target"
|
---|
366 | return
|
---|
367 | (host,port) = args[0].split(":")
|
---|
368 | if len(args) > 1:
|
---|
369 | passwd = args[1]
|
---|
370 | else:
|
---|
371 | passwd = ""
|
---|
372 |
|
---|
373 | port = int(port)
|
---|
374 | print "Teleporting to %s:%d..." %(host,port)
|
---|
375 | progress = console.teleport(host, port, passwd)
|
---|
376 | progressBar(ctx, progress, 100)
|
---|
377 | completed = progress.completed
|
---|
378 | rc = int(progress.resultCode)
|
---|
379 | if rc == 0:
|
---|
380 | print "Success!"
|
---|
381 | else:
|
---|
382 | reportError(ctx,session,rc)
|
---|
383 |
|
---|
384 | def cmdExistingVm(ctx,mach,cmd,args):
|
---|
385 | mgr=ctx['mgr']
|
---|
386 | vb=ctx['vb']
|
---|
387 | session = mgr.getSessionObject(vb)
|
---|
388 | uuid = mach.id
|
---|
389 | try:
|
---|
390 | progress = vb.openExistingSession(session, uuid)
|
---|
391 | except Exception,e:
|
---|
392 | print "Session to '%s' not open: %s" %(mach.name,e)
|
---|
393 | if g_verbose:
|
---|
394 | traceback.print_exc()
|
---|
395 | return
|
---|
396 | if str(session.state) != str(ctx['ifaces'].SessionState_Open):
|
---|
397 | print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
|
---|
398 | return
|
---|
399 | # unfortunately IGuest is suppressed, thus WebServices knows not about it
|
---|
400 | # this is an example how to handle local only functionality
|
---|
401 | if ctx['remote'] and cmd == 'stats2':
|
---|
402 | print 'Trying to use local only functionality, ignored'
|
---|
403 | return
|
---|
404 | console=session.console
|
---|
405 | ops={'pause': lambda: console.pause(),
|
---|
406 | 'resume': lambda: console.resume(),
|
---|
407 | 'powerdown': lambda: console.powerDown(),
|
---|
408 | 'powerbutton': lambda: console.powerButton(),
|
---|
409 | 'stats': lambda: guestStats(ctx, mach),
|
---|
410 | 'guest': lambda: guestExec(ctx, mach, console, args),
|
---|
411 | 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
|
---|
412 | 'save': lambda: progressBar(ctx,console.saveState()),
|
---|
413 | 'screenshot': lambda: takeScreenshot(ctx,console,args),
|
---|
414 | 'teleport': lambda: teleport(ctx,session,console,args)
|
---|
415 | }
|
---|
416 | try:
|
---|
417 | ops[cmd]()
|
---|
418 | except Exception, e:
|
---|
419 | print 'failed: ',e
|
---|
420 | if g_verbose:
|
---|
421 | traceback.print_exc()
|
---|
422 |
|
---|
423 | session.close()
|
---|
424 |
|
---|
425 | def machById(ctx,id):
|
---|
426 | mach = None
|
---|
427 | for m in getMachines(ctx):
|
---|
428 | if m.name == id:
|
---|
429 | mach = m
|
---|
430 | break
|
---|
431 | mid = str(m.id)
|
---|
432 | if mid[0] == '{':
|
---|
433 | mid = mid[1:-1]
|
---|
434 | if mid == id:
|
---|
435 | mach = m
|
---|
436 | break
|
---|
437 | return mach
|
---|
438 |
|
---|
439 | def argsToMach(ctx,args):
|
---|
440 | if len(args) < 2:
|
---|
441 | print "usage: %s [vmname|uuid]" %(args[0])
|
---|
442 | return None
|
---|
443 | id = args[1]
|
---|
444 | m = machById(ctx, id)
|
---|
445 | if m == None:
|
---|
446 | print "Machine '%s' is unknown, use list command to find available machines" %(id)
|
---|
447 | return m
|
---|
448 |
|
---|
449 | def helpSingleCmd(cmd,h,sp):
|
---|
450 | if sp != 0:
|
---|
451 | spec = " [ext from "+sp+"]"
|
---|
452 | else:
|
---|
453 | spec = ""
|
---|
454 | print " %s: %s%s" %(cmd,h,spec)
|
---|
455 |
|
---|
456 | def helpCmd(ctx, args):
|
---|
457 | if len(args) == 1:
|
---|
458 | print "Help page:"
|
---|
459 | names = commands.keys()
|
---|
460 | names.sort()
|
---|
461 | for i in names:
|
---|
462 | helpSingleCmd(i, commands[i][0], commands[i][2])
|
---|
463 | else:
|
---|
464 | cmd = args[1]
|
---|
465 | c = commands.get(cmd)
|
---|
466 | if c == None:
|
---|
467 | print "Command '%s' not known" %(cmd)
|
---|
468 | else:
|
---|
469 | helpSingleCmd(cmd, c[0], c[2])
|
---|
470 | return 0
|
---|
471 |
|
---|
472 | def listCmd(ctx, args):
|
---|
473 | for m in getMachines(ctx, True):
|
---|
474 | if m.teleporterEnabled:
|
---|
475 | tele = "[T] "
|
---|
476 | else:
|
---|
477 | tele = " "
|
---|
478 | print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,m.sessionState)
|
---|
479 | return 0
|
---|
480 |
|
---|
481 | def getControllerType(type):
|
---|
482 | if type == 0:
|
---|
483 | return "Null"
|
---|
484 | elif type == 1:
|
---|
485 | return "LsiLogic"
|
---|
486 | elif type == 2:
|
---|
487 | return "BusLogic"
|
---|
488 | elif type == 3:
|
---|
489 | return "IntelAhci"
|
---|
490 | elif type == 4:
|
---|
491 | return "PIIX3"
|
---|
492 | elif type == 5:
|
---|
493 | return "PIIX4"
|
---|
494 | elif type == 6:
|
---|
495 | return "ICH6"
|
---|
496 | else:
|
---|
497 | return "Unknown"
|
---|
498 |
|
---|
499 | def getFirmwareType(type):
|
---|
500 | if type == 0:
|
---|
501 | return "invalid"
|
---|
502 | elif type == 1:
|
---|
503 | return "bios"
|
---|
504 | elif type == 2:
|
---|
505 | return "efi"
|
---|
506 | elif type == 3:
|
---|
507 | return "efi64"
|
---|
508 | elif type == 4:
|
---|
509 | return "efidual"
|
---|
510 | else:
|
---|
511 | return "Unknown"
|
---|
512 |
|
---|
513 |
|
---|
514 | def infoCmd(ctx,args):
|
---|
515 | if (len(args) < 2):
|
---|
516 | print "usage: info [vmname|uuid]"
|
---|
517 | return 0
|
---|
518 | mach = argsToMach(ctx,args)
|
---|
519 | if mach == None:
|
---|
520 | return 0
|
---|
521 | os = ctx['vb'].getGuestOSType(mach.OSTypeId)
|
---|
522 | print " One can use setvar <mach> <var> <value> to change variable, using name in []."
|
---|
523 | print " Name [name]: %s" %(mach.name)
|
---|
524 | print " ID [n/a]: %s" %(mach.id)
|
---|
525 | print " OS Type [n/a]: %s" %(os.description)
|
---|
526 | print " Firmware [firmwareType]: %s (%s)" %(getFirmwareType(mach.firmwareType),mach.firmwareType)
|
---|
527 | print
|
---|
528 | print " CPUs [CPUCount]: %d" %(mach.CPUCount)
|
---|
529 | print " RAM [memorySize]: %dM" %(mach.memorySize)
|
---|
530 | print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
|
---|
531 | print " Monitors [monitorCount]: %d" %(mach.monitorCount)
|
---|
532 | print
|
---|
533 | print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
|
---|
534 | print " Machine status [n/a]: %d" % (mach.sessionState)
|
---|
535 | print
|
---|
536 | if mach.teleporterEnabled:
|
---|
537 | print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
|
---|
538 | print
|
---|
539 | bios = mach.BIOSSettings
|
---|
540 | print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
|
---|
541 | print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
|
---|
542 | hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
|
---|
543 | print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
|
---|
544 | hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
|
---|
545 | print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
|
---|
546 | hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
|
---|
547 | print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
|
---|
548 |
|
---|
549 | print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
|
---|
550 | print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
|
---|
551 |
|
---|
552 | print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
|
---|
553 | print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
|
---|
554 |
|
---|
555 | controllers = ctx['global'].getArray(mach, 'storageControllers')
|
---|
556 | if controllers:
|
---|
557 | print
|
---|
558 | print " Controllers:"
|
---|
559 | for controller in controllers:
|
---|
560 | print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
|
---|
561 |
|
---|
562 | attaches = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
563 | if attaches:
|
---|
564 | print
|
---|
565 | print " Mediums:"
|
---|
566 | for a in attaches:
|
---|
567 | print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
|
---|
568 | m = a.medium
|
---|
569 | if a.type == ctx['global'].constants.DeviceType_HardDisk:
|
---|
570 | print " HDD:"
|
---|
571 | print " Id: %s" %(m.id)
|
---|
572 | print " Location: %s" %(m.location)
|
---|
573 | print " Name: %s" %(m.name)
|
---|
574 | print " Format: %s" %(m.format)
|
---|
575 |
|
---|
576 | if a.type == ctx['global'].constants.DeviceType_DVD:
|
---|
577 | print " DVD:"
|
---|
578 | if m:
|
---|
579 | print " Id: %s" %(m.id)
|
---|
580 | print " Name: %s" %(m.name)
|
---|
581 | if m.hostDrive:
|
---|
582 | print " Host DVD %s" %(m.location)
|
---|
583 | if a.passthrough:
|
---|
584 | print " [passthrough mode]"
|
---|
585 | else:
|
---|
586 | print " Virtual image at %s" %(m.location)
|
---|
587 | print " Size: %s" %(m.size)
|
---|
588 |
|
---|
589 | if a.type == ctx['global'].constants.DeviceType_Floppy:
|
---|
590 | print " Floppy:"
|
---|
591 | if m:
|
---|
592 | print " Id: %s" %(m.id)
|
---|
593 | print " Name: %s" %(m.name)
|
---|
594 | if m.hostDrive:
|
---|
595 | print " Host floppy %s" %(m.location)
|
---|
596 | else:
|
---|
597 | print " Virtual image at %s" %(m.location)
|
---|
598 | print " Size: %s" %(m.size)
|
---|
599 |
|
---|
600 | return 0
|
---|
601 |
|
---|
602 | def startCmd(ctx, args):
|
---|
603 | mach = argsToMach(ctx,args)
|
---|
604 | if mach == None:
|
---|
605 | return 0
|
---|
606 | if len(args) > 2:
|
---|
607 | type = args[2]
|
---|
608 | else:
|
---|
609 | type = "gui"
|
---|
610 | startVm(ctx, mach, type)
|
---|
611 | return 0
|
---|
612 |
|
---|
613 | def createCmd(ctx, args):
|
---|
614 | if (len(args) < 3 or len(args) > 4):
|
---|
615 | print "usage: create name ostype <basefolder>"
|
---|
616 | return 0
|
---|
617 | name = args[1]
|
---|
618 | oskind = args[2]
|
---|
619 | if len(args) == 4:
|
---|
620 | base = args[3]
|
---|
621 | else:
|
---|
622 | base = ''
|
---|
623 | try:
|
---|
624 | ctx['vb'].getGuestOSType(oskind)
|
---|
625 | except Exception, e:
|
---|
626 | print 'Unknown OS type:',oskind
|
---|
627 | return 0
|
---|
628 | createVm(ctx, name, oskind, base)
|
---|
629 | return 0
|
---|
630 |
|
---|
631 | def removeCmd(ctx, args):
|
---|
632 | mach = argsToMach(ctx,args)
|
---|
633 | if mach == None:
|
---|
634 | return 0
|
---|
635 | removeVm(ctx, mach)
|
---|
636 | return 0
|
---|
637 |
|
---|
638 | def pauseCmd(ctx, args):
|
---|
639 | mach = argsToMach(ctx,args)
|
---|
640 | if mach == None:
|
---|
641 | return 0
|
---|
642 | cmdExistingVm(ctx, mach, 'pause', '')
|
---|
643 | return 0
|
---|
644 |
|
---|
645 | def powerdownCmd(ctx, args):
|
---|
646 | mach = argsToMach(ctx,args)
|
---|
647 | if mach == None:
|
---|
648 | return 0
|
---|
649 | cmdExistingVm(ctx, mach, 'powerdown', '')
|
---|
650 | return 0
|
---|
651 |
|
---|
652 | def powerbuttonCmd(ctx, args):
|
---|
653 | mach = argsToMach(ctx,args)
|
---|
654 | if mach == None:
|
---|
655 | return 0
|
---|
656 | cmdExistingVm(ctx, mach, 'powerbutton', '')
|
---|
657 | return 0
|
---|
658 |
|
---|
659 | def resumeCmd(ctx, args):
|
---|
660 | mach = argsToMach(ctx,args)
|
---|
661 | if mach == None:
|
---|
662 | return 0
|
---|
663 | cmdExistingVm(ctx, mach, 'resume', '')
|
---|
664 | return 0
|
---|
665 |
|
---|
666 | def saveCmd(ctx, args):
|
---|
667 | mach = argsToMach(ctx,args)
|
---|
668 | if mach == None:
|
---|
669 | return 0
|
---|
670 | cmdExistingVm(ctx, mach, 'save', '')
|
---|
671 | return 0
|
---|
672 |
|
---|
673 | def statsCmd(ctx, args):
|
---|
674 | mach = argsToMach(ctx,args)
|
---|
675 | if mach == None:
|
---|
676 | return 0
|
---|
677 | cmdExistingVm(ctx, mach, 'stats', '')
|
---|
678 | return 0
|
---|
679 |
|
---|
680 | def guestCmd(ctx, args):
|
---|
681 | if (len(args) < 3):
|
---|
682 | print "usage: guest name commands"
|
---|
683 | return 0
|
---|
684 | mach = argsToMach(ctx,args)
|
---|
685 | if mach == None:
|
---|
686 | return 0
|
---|
687 | cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
|
---|
688 | return 0
|
---|
689 |
|
---|
690 | def screenshotCmd(ctx, args):
|
---|
691 | if (len(args) < 3):
|
---|
692 | print "usage: screenshot name file <width> <height>"
|
---|
693 | return 0
|
---|
694 | mach = argsToMach(ctx,args)
|
---|
695 | if mach == None:
|
---|
696 | return 0
|
---|
697 | cmdExistingVm(ctx, mach, 'screenshot', args[2:])
|
---|
698 | return 0
|
---|
699 |
|
---|
700 | def teleportCmd(ctx, args):
|
---|
701 | if (len(args) < 3):
|
---|
702 | print "usage: teleport name host:port <password>"
|
---|
703 | return 0
|
---|
704 | mach = argsToMach(ctx,args)
|
---|
705 | if mach == None:
|
---|
706 | return 0
|
---|
707 | cmdExistingVm(ctx, mach, 'teleport', args[2:])
|
---|
708 | return 0
|
---|
709 |
|
---|
710 | def openportalCmd(ctx, args):
|
---|
711 | if (len(args) < 3):
|
---|
712 | print "usage: openportal name port <password>"
|
---|
713 | return 0
|
---|
714 | mach = argsToMach(ctx,args)
|
---|
715 | if mach == None:
|
---|
716 | return 0
|
---|
717 | port = int(args[2])
|
---|
718 | if (len(args) > 3):
|
---|
719 | passwd = args[3]
|
---|
720 | else:
|
---|
721 | passwd = ""
|
---|
722 | if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
|
---|
723 | session = ctx['global'].openMachineSession(mach.id)
|
---|
724 | mach1 = session.machine
|
---|
725 | mach1.teleporterEnabled = True
|
---|
726 | mach1.teleporterPort = port
|
---|
727 | mach1.teleporterPassword = passwd
|
---|
728 | mach1.saveSettings()
|
---|
729 | session.close()
|
---|
730 | startVm(ctx, mach, "gui")
|
---|
731 | return 0
|
---|
732 |
|
---|
733 | def closeportalCmd(ctx, args):
|
---|
734 | if (len(args) < 2):
|
---|
735 | print "usage: closeportal name"
|
---|
736 | return 0
|
---|
737 | mach = argsToMach(ctx,args)
|
---|
738 | if mach == None:
|
---|
739 | return 0
|
---|
740 | if mach.teleporterEnabled:
|
---|
741 | session = ctx['global'].openMachineSession(mach.id)
|
---|
742 | mach1 = session.machine
|
---|
743 | mach1.teleporterEnabled = False
|
---|
744 | mach1.saveSettings()
|
---|
745 | session.close()
|
---|
746 | return 0
|
---|
747 |
|
---|
748 |
|
---|
749 | def setvarCmd(ctx, args):
|
---|
750 | if (len(args) < 4):
|
---|
751 | print "usage: setvar [vmname|uuid] expr value"
|
---|
752 | return 0
|
---|
753 | mach = argsToMach(ctx,args)
|
---|
754 | if mach == None:
|
---|
755 | return 0
|
---|
756 | session = ctx['global'].openMachineSession(mach.id)
|
---|
757 | mach = session.machine
|
---|
758 | expr = 'mach.'+args[2]+' = '+args[3]
|
---|
759 | print "Executing",expr
|
---|
760 | try:
|
---|
761 | exec expr
|
---|
762 | except Exception, e:
|
---|
763 | print 'failed: ',e
|
---|
764 | if g_verbose:
|
---|
765 | traceback.print_exc()
|
---|
766 | mach.saveSettings()
|
---|
767 | session.close()
|
---|
768 | return 0
|
---|
769 |
|
---|
770 | def quitCmd(ctx, args):
|
---|
771 | return 1
|
---|
772 |
|
---|
773 | def aliasCmd(ctx, args):
|
---|
774 | if (len(args) == 3):
|
---|
775 | aliases[args[1]] = args[2]
|
---|
776 | return 0
|
---|
777 |
|
---|
778 | for (k,v) in aliases.items():
|
---|
779 | print "'%s' is an alias for '%s'" %(k,v)
|
---|
780 | return 0
|
---|
781 |
|
---|
782 | def verboseCmd(ctx, args):
|
---|
783 | global g_verbose
|
---|
784 | g_verbose = not g_verbose
|
---|
785 | return 0
|
---|
786 |
|
---|
787 | def getUSBStateString(state):
|
---|
788 | if state == 0:
|
---|
789 | return "NotSupported"
|
---|
790 | elif state == 1:
|
---|
791 | return "Unavailable"
|
---|
792 | elif state == 2:
|
---|
793 | return "Busy"
|
---|
794 | elif state == 3:
|
---|
795 | return "Available"
|
---|
796 | elif state == 4:
|
---|
797 | return "Held"
|
---|
798 | elif state == 5:
|
---|
799 | return "Captured"
|
---|
800 | else:
|
---|
801 | return "Unknown"
|
---|
802 |
|
---|
803 | def hostCmd(ctx, args):
|
---|
804 | host = ctx['vb'].host
|
---|
805 | cnt = host.processorCount
|
---|
806 | print "Processor count:",cnt
|
---|
807 | for i in range(0,cnt):
|
---|
808 | print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
|
---|
809 |
|
---|
810 | print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
|
---|
811 | print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
|
---|
812 | if host.Acceleration3DAvailable:
|
---|
813 | print "3D acceleration available"
|
---|
814 | else:
|
---|
815 | print "3D acceleration NOT available"
|
---|
816 |
|
---|
817 | print "Network interfaces:"
|
---|
818 | for ni in ctx['global'].getArray(host, 'networkInterfaces'):
|
---|
819 | print " %s (%s)" %(ni.name, ni.IPAddress)
|
---|
820 |
|
---|
821 | print "DVD drives:"
|
---|
822 | for dd in ctx['global'].getArray(host, 'DVDDrives'):
|
---|
823 | print " %s - %s" %(dd.name, dd.description)
|
---|
824 |
|
---|
825 | print "USB devices:"
|
---|
826 | for ud in ctx['global'].getArray(host, 'USBDevices'):
|
---|
827 | print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
|
---|
828 |
|
---|
829 | if ctx['perf']:
|
---|
830 | for metric in ctx['perf'].query(["*"], [host]):
|
---|
831 | print metric['name'], metric['values_as_string']
|
---|
832 |
|
---|
833 | return 0
|
---|
834 |
|
---|
835 | def monitorGuestCmd(ctx, args):
|
---|
836 | if (len(args) < 2):
|
---|
837 | print "usage: monitorGuest name (duration)"
|
---|
838 | return 0
|
---|
839 | mach = argsToMach(ctx,args)
|
---|
840 | if mach == None:
|
---|
841 | return 0
|
---|
842 | dur = 5
|
---|
843 | if len(args) > 2:
|
---|
844 | dur = float(args[2])
|
---|
845 | cmdExistingVm(ctx, mach, 'monitorGuest', dur)
|
---|
846 | return 0
|
---|
847 |
|
---|
848 | def monitorVBoxCmd(ctx, args):
|
---|
849 | if (len(args) > 2):
|
---|
850 | print "usage: monitorVBox (duration)"
|
---|
851 | return 0
|
---|
852 | dur = 5
|
---|
853 | if len(args) > 1:
|
---|
854 | dur = float(args[1])
|
---|
855 | monitorVBox(ctx, dur)
|
---|
856 | return 0
|
---|
857 |
|
---|
858 | def getAdapterType(ctx, type):
|
---|
859 | if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
|
---|
860 | type == ctx['global'].constants.NetworkAdapterType_Am79C973):
|
---|
861 | return "pcnet"
|
---|
862 | elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
|
---|
863 | type == ctx['global'].constants.NetworkAdapterType_I82545EM or
|
---|
864 | type == ctx['global'].constants.NetworkAdapterType_I82543GC):
|
---|
865 | return "e1000"
|
---|
866 | elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
|
---|
867 | return "virtio"
|
---|
868 | elif (type == ctx['global'].constants.NetworkAdapterType_Null):
|
---|
869 | return None
|
---|
870 | else:
|
---|
871 | raise Exception("Unknown adapter type: "+type)
|
---|
872 |
|
---|
873 |
|
---|
874 | def portForwardCmd(ctx, args):
|
---|
875 | if (len(args) != 5):
|
---|
876 | print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
|
---|
877 | return 0
|
---|
878 | mach = argsToMach(ctx,args)
|
---|
879 | if mach == None:
|
---|
880 | return 0
|
---|
881 | adapterNum = int(args[2])
|
---|
882 | hostPort = int(args[3])
|
---|
883 | guestPort = int(args[4])
|
---|
884 | proto = "TCP"
|
---|
885 | session = ctx['global'].openMachineSession(mach.id)
|
---|
886 | mach = session.machine
|
---|
887 |
|
---|
888 | adapter = mach.getNetworkAdapter(adapterNum)
|
---|
889 | adapterType = getAdapterType(ctx, adapter.adapterType)
|
---|
890 |
|
---|
891 | profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
|
---|
892 | config = "VBoxInternal/Devices/" + adapterType + "/"
|
---|
893 | config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
|
---|
894 |
|
---|
895 | mach.setExtraData(config + "/Protocol", proto)
|
---|
896 | mach.setExtraData(config + "/HostPort", str(hostPort))
|
---|
897 | mach.setExtraData(config + "/GuestPort", str(guestPort))
|
---|
898 |
|
---|
899 | mach.saveSettings()
|
---|
900 | session.close()
|
---|
901 |
|
---|
902 | return 0
|
---|
903 |
|
---|
904 |
|
---|
905 | def showLogCmd(ctx, args):
|
---|
906 | if (len(args) < 2):
|
---|
907 | print "usage: showLog <vm> <num>"
|
---|
908 | return 0
|
---|
909 | mach = argsToMach(ctx,args)
|
---|
910 | if mach == None:
|
---|
911 | return 0
|
---|
912 |
|
---|
913 | log = "VBox.log"
|
---|
914 | if (len(args) > 2):
|
---|
915 | log += "."+args[2]
|
---|
916 | fileName = os.path.join(mach.logFolder, log)
|
---|
917 |
|
---|
918 | try:
|
---|
919 | lf = open(fileName, 'r')
|
---|
920 | except IOError,e:
|
---|
921 | print "cannot open: ",e
|
---|
922 | return 0
|
---|
923 |
|
---|
924 | for line in lf:
|
---|
925 | print line,
|
---|
926 | lf.close()
|
---|
927 |
|
---|
928 | return 0
|
---|
929 |
|
---|
930 | def evalCmd(ctx, args):
|
---|
931 | expr = ' '.join(args[1:])
|
---|
932 | try:
|
---|
933 | exec expr
|
---|
934 | except Exception, e:
|
---|
935 | print 'failed: ',e
|
---|
936 | if g_verbose:
|
---|
937 | traceback.print_exc()
|
---|
938 | return 0
|
---|
939 |
|
---|
940 | def reloadExtCmd(ctx, args):
|
---|
941 | # maybe will want more args smartness
|
---|
942 | checkUserExtensions(ctx, commands, getHomeFolder(ctx))
|
---|
943 | autoCompletion(commands, ctx)
|
---|
944 | return 0
|
---|
945 |
|
---|
946 |
|
---|
947 | def runScriptCmd(ctx, args):
|
---|
948 | if (len(args) != 2):
|
---|
949 | print "usage: runScript <script>"
|
---|
950 | return 0
|
---|
951 | try:
|
---|
952 | lf = open(args[1], 'r')
|
---|
953 | except IOError,e:
|
---|
954 | print "cannot open:",args[1], ":",e
|
---|
955 | return 0
|
---|
956 |
|
---|
957 | try:
|
---|
958 | for line in lf:
|
---|
959 | done = runCommand(ctx, line)
|
---|
960 | if done != 0: break
|
---|
961 | except Exception,e:
|
---|
962 | print "error:",e
|
---|
963 | if g_verbose:
|
---|
964 | traceback.print_exc()
|
---|
965 | lf.close()
|
---|
966 | return 0
|
---|
967 |
|
---|
968 | def sleepCmd(ctx, args):
|
---|
969 | if (len(args) != 2):
|
---|
970 | print "usage: sleep <secs>"
|
---|
971 | return 0
|
---|
972 |
|
---|
973 | try:
|
---|
974 | time.sleep(float(args[1]))
|
---|
975 | except:
|
---|
976 | # to allow sleep interrupt
|
---|
977 | pass
|
---|
978 | return 0
|
---|
979 |
|
---|
980 |
|
---|
981 | def shellCmd(ctx, args):
|
---|
982 | if (len(args) < 2):
|
---|
983 | print "usage: shell <commands>"
|
---|
984 | return 0
|
---|
985 | cmd = ' '.join(args[1:])
|
---|
986 | try:
|
---|
987 | os.system(cmd)
|
---|
988 | except KeyboardInterrupt:
|
---|
989 | # to allow shell command interruption
|
---|
990 | pass
|
---|
991 | return 0
|
---|
992 |
|
---|
993 |
|
---|
994 | def connectCmd(ctx, args):
|
---|
995 | if (len(args) > 4):
|
---|
996 | print "usage: connect [url] [username] [passwd]"
|
---|
997 | return 0
|
---|
998 |
|
---|
999 | if ctx['vb'] is not None:
|
---|
1000 | print "Already connected, disconnect first..."
|
---|
1001 | return 0
|
---|
1002 |
|
---|
1003 | if (len(args) > 1):
|
---|
1004 | url = args[1]
|
---|
1005 | else:
|
---|
1006 | url = None
|
---|
1007 |
|
---|
1008 | if (len(args) > 2):
|
---|
1009 | user = args[2]
|
---|
1010 | else:
|
---|
1011 | user = ""
|
---|
1012 |
|
---|
1013 | if (len(args) > 3):
|
---|
1014 | passwd = args[3]
|
---|
1015 | else:
|
---|
1016 | passwd = ""
|
---|
1017 |
|
---|
1018 | vbox = ctx['global'].platform.connect(url, user, passwd)
|
---|
1019 | ctx['vb'] = vbox
|
---|
1020 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1021 | ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
|
---|
1022 | return 0
|
---|
1023 |
|
---|
1024 | def disconnectCmd(ctx, args):
|
---|
1025 | if (len(args) != 1):
|
---|
1026 | print "usage: disconnect"
|
---|
1027 | return 0
|
---|
1028 |
|
---|
1029 | if ctx['vb'] is None:
|
---|
1030 | print "Not connected yet."
|
---|
1031 | return 0
|
---|
1032 |
|
---|
1033 | try:
|
---|
1034 | ctx['global'].platform.disconnect()
|
---|
1035 | except:
|
---|
1036 | ctx['vb'] = None
|
---|
1037 | raise
|
---|
1038 |
|
---|
1039 | ctx['vb'] = None
|
---|
1040 | return 0
|
---|
1041 |
|
---|
1042 | def exportVMCmd(ctx, args):
|
---|
1043 | import sys
|
---|
1044 |
|
---|
1045 | if len(args) < 3:
|
---|
1046 | print "usage: exportVm <machine> <path> <format> <license>"
|
---|
1047 | return 0
|
---|
1048 | mach = ctx['machById'](args[1])
|
---|
1049 | if mach is None:
|
---|
1050 | return 0
|
---|
1051 | path = args[2]
|
---|
1052 | if (len(args) > 3):
|
---|
1053 | format = args[3]
|
---|
1054 | else:
|
---|
1055 | format = "ovf-1.0"
|
---|
1056 | if (len(args) > 4):
|
---|
1057 | license = args[4]
|
---|
1058 | else:
|
---|
1059 | license = "GPL"
|
---|
1060 |
|
---|
1061 | app = ctx['vb'].createAppliance()
|
---|
1062 | desc = mach.export(app)
|
---|
1063 | desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
|
---|
1064 | p = app.write(format, path)
|
---|
1065 | progressBar(ctx, p)
|
---|
1066 | print "Exported to %s in format %s" %(path, format)
|
---|
1067 | return 0
|
---|
1068 |
|
---|
1069 | aliases = {'s':'start',
|
---|
1070 | 'i':'info',
|
---|
1071 | 'l':'list',
|
---|
1072 | 'h':'help',
|
---|
1073 | 'a':'alias',
|
---|
1074 | 'q':'quit', 'exit':'quit',
|
---|
1075 | 'v':'verbose'}
|
---|
1076 |
|
---|
1077 | commands = {'help':['Prints help information', helpCmd, 0],
|
---|
1078 | 'start':['Start virtual machine by name or uuid', startCmd, 0],
|
---|
1079 | 'create':['Create virtual machine', createCmd, 0],
|
---|
1080 | 'remove':['Remove virtual machine', removeCmd, 0],
|
---|
1081 | 'pause':['Pause virtual machine', pauseCmd, 0],
|
---|
1082 | 'resume':['Resume virtual machine', resumeCmd, 0],
|
---|
1083 | 'save':['Save execution state of virtual machine', saveCmd, 0],
|
---|
1084 | 'stats':['Stats for virtual machine', statsCmd, 0],
|
---|
1085 | 'powerdown':['Power down virtual machine', powerdownCmd, 0],
|
---|
1086 | 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
|
---|
1087 | 'list':['Shows known virtual machines', listCmd, 0],
|
---|
1088 | 'info':['Shows info on machine', infoCmd, 0],
|
---|
1089 | 'alias':['Control aliases', aliasCmd, 0],
|
---|
1090 | 'verbose':['Toggle verbosity', verboseCmd, 0],
|
---|
1091 | 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
|
---|
1092 | 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
|
---|
1093 | 'quit':['Exits', quitCmd, 0],
|
---|
1094 | 'host':['Show host information', hostCmd, 0],
|
---|
1095 | 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
|
---|
1096 | 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
|
---|
1097 | 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
|
---|
1098 | 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
|
---|
1099 | 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
|
---|
1100 | 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
|
---|
1101 | 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
|
---|
1102 | 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
|
---|
1103 | 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
|
---|
1104 | 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
|
---|
1105 | 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
|
---|
1106 | 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd>', teleportCmd, 0],
|
---|
1107 | 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
|
---|
1108 | 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0]
|
---|
1109 | }
|
---|
1110 |
|
---|
1111 | def runCommandArgs(ctx, args):
|
---|
1112 | c = args[0]
|
---|
1113 | if aliases.get(c, None) != None:
|
---|
1114 | c = aliases[c]
|
---|
1115 | ci = commands.get(c,None)
|
---|
1116 | if ci == None:
|
---|
1117 | print "Unknown command: '%s', type 'help' for list of known commands" %(c)
|
---|
1118 | return 0
|
---|
1119 | return ci[1](ctx, args)
|
---|
1120 |
|
---|
1121 |
|
---|
1122 | def runCommand(ctx, cmd):
|
---|
1123 | if len(cmd) == 0: return 0
|
---|
1124 | args = split_no_quotes(cmd)
|
---|
1125 | if len(args) == 0: return 0
|
---|
1126 | return runCommandArgs(ctx, args)
|
---|
1127 |
|
---|
1128 | #
|
---|
1129 | # To write your own custom commands to vboxshell, create
|
---|
1130 | # file ~/.VirtualBox/shellext.py with content like
|
---|
1131 | #
|
---|
1132 | # def runTestCmd(ctx, args):
|
---|
1133 | # print "Testy test", ctx['vb']
|
---|
1134 | # return 0
|
---|
1135 | #
|
---|
1136 | # commands = {
|
---|
1137 | # 'test': ['Test help', runTestCmd]
|
---|
1138 | # }
|
---|
1139 | # and issue reloadExt shell command.
|
---|
1140 | # This file also will be read automatically on startup or 'reloadExt'.
|
---|
1141 | #
|
---|
1142 | # Also one can put shell extensions into ~/.VirtualBox/shexts and
|
---|
1143 | # they will also be picked up, so this way one can exchange
|
---|
1144 | # shell extensions easily.
|
---|
1145 | def addExtsFromFile(ctx, cmds, file):
|
---|
1146 | if not os.path.isfile(file):
|
---|
1147 | return
|
---|
1148 | d = {}
|
---|
1149 | try:
|
---|
1150 | execfile(file, d, d)
|
---|
1151 | for (k,v) in d['commands'].items():
|
---|
1152 | if g_verbose:
|
---|
1153 | print "customize: adding \"%s\" - %s" %(k, v[0])
|
---|
1154 | cmds[k] = [v[0], v[1], file]
|
---|
1155 | except:
|
---|
1156 | print "Error loading user extensions from %s" %(file)
|
---|
1157 | traceback.print_exc()
|
---|
1158 |
|
---|
1159 |
|
---|
1160 | def checkUserExtensions(ctx, cmds, folder):
|
---|
1161 | folder = str(folder)
|
---|
1162 | name = os.path.join(folder, "shellext.py")
|
---|
1163 | addExtsFromFile(ctx, cmds, name)
|
---|
1164 | # also check 'exts' directory for all files
|
---|
1165 | shextdir = os.path.join(folder, "shexts")
|
---|
1166 | if not os.path.isdir(shextdir):
|
---|
1167 | return
|
---|
1168 | exts = os.listdir(shextdir)
|
---|
1169 | for e in exts:
|
---|
1170 | addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
|
---|
1171 |
|
---|
1172 | def getHomeFolder(ctx):
|
---|
1173 | if ctx['remote'] or ctx['vb'] is None:
|
---|
1174 | return os.path.join(os.path.expanduser("~"), ".VirtualBox")
|
---|
1175 | else:
|
---|
1176 | return ctx['vb'].homeFolder
|
---|
1177 |
|
---|
1178 | def interpret(ctx):
|
---|
1179 | if ctx['remote']:
|
---|
1180 | commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
|
---|
1181 | commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
|
---|
1182 |
|
---|
1183 | vbox = ctx['vb']
|
---|
1184 |
|
---|
1185 | if vbox is not None:
|
---|
1186 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1187 | ctx['perf'] = ctx['global'].getPerfCollector(vbox)
|
---|
1188 | else:
|
---|
1189 | ctx['perf'] = None
|
---|
1190 |
|
---|
1191 | home = getHomeFolder(ctx)
|
---|
1192 | checkUserExtensions(ctx, commands, home)
|
---|
1193 |
|
---|
1194 | autoCompletion(commands, ctx)
|
---|
1195 |
|
---|
1196 | # to allow to print actual host information, we collect info for
|
---|
1197 | # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
|
---|
1198 | if ctx['perf']:
|
---|
1199 | try:
|
---|
1200 | ctx['perf'].setup(['*'], [vbox.host], 10, 15)
|
---|
1201 | except:
|
---|
1202 | pass
|
---|
1203 |
|
---|
1204 | while True:
|
---|
1205 | try:
|
---|
1206 | cmd = raw_input("vbox> ")
|
---|
1207 | done = runCommand(ctx, cmd)
|
---|
1208 | if done != 0: break
|
---|
1209 | except KeyboardInterrupt:
|
---|
1210 | print '====== You can type quit or q to leave'
|
---|
1211 | break
|
---|
1212 | except EOFError:
|
---|
1213 | break;
|
---|
1214 | except Exception,e:
|
---|
1215 | print e
|
---|
1216 | if g_verbose:
|
---|
1217 | traceback.print_exc()
|
---|
1218 | ctx['global'].waitForEvents(0)
|
---|
1219 | try:
|
---|
1220 | # There is no need to disable metric collection. This is just an example.
|
---|
1221 | if ct['perf']:
|
---|
1222 | ctx['perf'].disable(['*'], [vbox.host])
|
---|
1223 | except:
|
---|
1224 | pass
|
---|
1225 |
|
---|
1226 | def runCommandCb(ctx, cmd, args):
|
---|
1227 | args.insert(0, cmd)
|
---|
1228 | return runCommandArgs(ctx, args)
|
---|
1229 |
|
---|
1230 | def main(argv):
|
---|
1231 | style = None
|
---|
1232 | autopath = False
|
---|
1233 | argv.pop(0)
|
---|
1234 | while len(argv) > 0:
|
---|
1235 | if argv[0] == "-w":
|
---|
1236 | style = "WEBSERVICE"
|
---|
1237 | if argv[0] == "-a":
|
---|
1238 | autopath = True
|
---|
1239 | argv.pop(0)
|
---|
1240 |
|
---|
1241 | if autopath:
|
---|
1242 | cwd = os.getcwd()
|
---|
1243 | vpp = os.environ.get("VBOX_PROGRAM_PATH")
|
---|
1244 | if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
|
---|
1245 | vpp = cwd
|
---|
1246 | print "Autodetected VBOX_PROGRAM_PATH as",vpp
|
---|
1247 | os.environ["VBOX_PROGRAM_PATH"] = cwd
|
---|
1248 | sys.path.append(os.path.join(vpp, "sdk", "installer"))
|
---|
1249 |
|
---|
1250 | from vboxapi import VirtualBoxManager
|
---|
1251 | g_virtualBoxManager = VirtualBoxManager(style, None)
|
---|
1252 | ctx = {'global':g_virtualBoxManager,
|
---|
1253 | 'mgr':g_virtualBoxManager.mgr,
|
---|
1254 | 'vb':g_virtualBoxManager.vbox,
|
---|
1255 | 'ifaces':g_virtualBoxManager.constants,
|
---|
1256 | 'remote':g_virtualBoxManager.remote,
|
---|
1257 | 'type':g_virtualBoxManager.type,
|
---|
1258 | 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
|
---|
1259 | 'machById': lambda id: machById(ctx,id),
|
---|
1260 | 'progressBar': lambda p: progressBar(ctx,p),
|
---|
1261 | '_machlist':None
|
---|
1262 | }
|
---|
1263 | interpret(ctx)
|
---|
1264 | g_virtualBoxManager.deinit()
|
---|
1265 | del g_virtualBoxManager
|
---|
1266 |
|
---|
1267 | if __name__ == '__main__':
|
---|
1268 | main(sys.argv)
|
---|