1 | #!/usr/bin/python
|
---|
2 | #
|
---|
3 | # Copyright (C) 2009-2010 Sun Microsystems, Inc.
|
---|
4 | #
|
---|
5 | # This file is part of VirtualBox Open Source Edition (OSE), as
|
---|
6 | # available from http://www.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, supports TAB-completion and #
|
---|
23 | # history if you have Python readline installed. #
|
---|
24 | # #
|
---|
25 | # Finally, shell allows arbitrary custom extensions, just create #
|
---|
26 | # .VirtualBox/shexts/ and drop your extensions there. #
|
---|
27 | # Enjoy. #
|
---|
28 | ################################################################################
|
---|
29 |
|
---|
30 | import os,sys
|
---|
31 | import traceback
|
---|
32 | import shlex
|
---|
33 | import time
|
---|
34 |
|
---|
35 | # Simple implementation of IConsoleCallback, one can use it as skeleton
|
---|
36 | # for custom implementations
|
---|
37 | class GuestMonitor:
|
---|
38 | def __init__(self, mach):
|
---|
39 | self.mach = mach
|
---|
40 |
|
---|
41 | def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
|
---|
42 | print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
|
---|
43 | def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
|
---|
44 | print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, needsHostCursor)
|
---|
45 |
|
---|
46 | def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
|
---|
47 | print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
|
---|
48 |
|
---|
49 | def onStateChange(self, state):
|
---|
50 | print "%s: onStateChange state=%d" %(self.mach.name, state)
|
---|
51 |
|
---|
52 | def onAdditionsStateChange(self):
|
---|
53 | print "%s: onAdditionsStateChange" %(self.mach.name)
|
---|
54 |
|
---|
55 | def onNetworkAdapterChange(self, adapter):
|
---|
56 | print "%s: onNetworkAdapterChange" %(self.mach.name)
|
---|
57 |
|
---|
58 | def onSerialPortChange(self, port):
|
---|
59 | print "%s: onSerialPortChange" %(self.mach.name)
|
---|
60 |
|
---|
61 | def onParallelPortChange(self, port):
|
---|
62 | print "%s: onParallelPortChange" %(self.mach.name)
|
---|
63 |
|
---|
64 | def onStorageControllerChange(self):
|
---|
65 | print "%s: onStorageControllerChange" %(self.mach.name)
|
---|
66 |
|
---|
67 | def onMediumChange(self, attachment):
|
---|
68 | print "%s: onMediumChange" %(self.mach.name)
|
---|
69 |
|
---|
70 | def onVRDPServerChange(self):
|
---|
71 | print "%s: onVRDPServerChange" %(self.mach.name)
|
---|
72 |
|
---|
73 | def onUSBControllerChange(self):
|
---|
74 | print "%s: onUSBControllerChange" %(self.mach.name)
|
---|
75 |
|
---|
76 | def onUSBDeviceStateChange(self, device, attached, error):
|
---|
77 | print "%s: onUSBDeviceStateChange" %(self.mach.name)
|
---|
78 |
|
---|
79 | def onSharedFolderChange(self, scope):
|
---|
80 | print "%s: onSharedFolderChange" %(self.mach.name)
|
---|
81 |
|
---|
82 | def onRuntimeError(self, fatal, id, message):
|
---|
83 | print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
|
---|
84 |
|
---|
85 | def onCanShowWindow(self):
|
---|
86 | print "%s: onCanShowWindow" %(self.mach.name)
|
---|
87 | return True
|
---|
88 |
|
---|
89 | def onShowWindow(self, winId):
|
---|
90 | print "%s: onShowWindow: %d" %(self.mach.name, winId)
|
---|
91 |
|
---|
92 | class VBoxMonitor:
|
---|
93 | def __init__(self, params):
|
---|
94 | self.vbox = params[0]
|
---|
95 | self.isMscom = params[1]
|
---|
96 | pass
|
---|
97 |
|
---|
98 | def onMachineStateChange(self, id, state):
|
---|
99 | print "onMachineStateChange: %s %d" %(id, state)
|
---|
100 |
|
---|
101 | def onMachineDataChange(self,id):
|
---|
102 | print "onMachineDataChange: %s" %(id)
|
---|
103 |
|
---|
104 | def onExtraDataCanChange(self, id, key, value):
|
---|
105 | print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
|
---|
106 | # Witty COM bridge thinks if someone wishes to return tuple, hresult
|
---|
107 | # is one of values we want to return
|
---|
108 | if self.isMscom:
|
---|
109 | return "", 0, True
|
---|
110 | else:
|
---|
111 | return True, ""
|
---|
112 |
|
---|
113 | def onExtraDataChange(self, id, key, value):
|
---|
114 | print "onExtraDataChange: %s %s=>%s" %(id, key, value)
|
---|
115 |
|
---|
116 | def onMediaRegistered(self, id, type, registered):
|
---|
117 | print "onMediaRegistered: %s" %(id)
|
---|
118 |
|
---|
119 | def onMachineRegistered(self, id, registred):
|
---|
120 | print "onMachineRegistered: %s" %(id)
|
---|
121 |
|
---|
122 | def onSessionStateChange(self, id, state):
|
---|
123 | print "onSessionStateChange: %s %d" %(id, state)
|
---|
124 |
|
---|
125 | def onSnapshotTaken(self, mach, id):
|
---|
126 | print "onSnapshotTaken: %s %s" %(mach, id)
|
---|
127 |
|
---|
128 | def onSnapshotDiscarded(self, mach, id):
|
---|
129 | print "onSnapshotDiscarded: %s %s" %(mach, id)
|
---|
130 |
|
---|
131 | def onSnapshotChange(self, mach, id):
|
---|
132 | print "onSnapshotChange: %s %s" %(mach, id)
|
---|
133 |
|
---|
134 | def onGuestPropertyChange(self, id, name, newValue, flags):
|
---|
135 | print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
|
---|
136 |
|
---|
137 | g_hasreadline = 1
|
---|
138 | try:
|
---|
139 | import readline
|
---|
140 | import rlcompleter
|
---|
141 | except:
|
---|
142 | g_hasreadline = 0
|
---|
143 |
|
---|
144 |
|
---|
145 | if g_hasreadline:
|
---|
146 | class CompleterNG(rlcompleter.Completer):
|
---|
147 | def __init__(self, dic, ctx):
|
---|
148 | self.ctx = ctx
|
---|
149 | return rlcompleter.Completer.__init__(self,dic)
|
---|
150 |
|
---|
151 | def complete(self, text, state):
|
---|
152 | """
|
---|
153 | taken from:
|
---|
154 | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
|
---|
155 | """
|
---|
156 | if text == "":
|
---|
157 | return ['\t',None][state]
|
---|
158 | else:
|
---|
159 | return rlcompleter.Completer.complete(self,text,state)
|
---|
160 |
|
---|
161 | def global_matches(self, text):
|
---|
162 | """
|
---|
163 | Compute matches when text is a simple name.
|
---|
164 | Return a list of all names currently defined
|
---|
165 | in self.namespace that match.
|
---|
166 | """
|
---|
167 |
|
---|
168 | matches = []
|
---|
169 | n = len(text)
|
---|
170 |
|
---|
171 | for list in [ self.namespace ]:
|
---|
172 | for word in list:
|
---|
173 | if word[:n] == text:
|
---|
174 | matches.append(word)
|
---|
175 |
|
---|
176 |
|
---|
177 | try:
|
---|
178 | for m in getMachines(self.ctx):
|
---|
179 | # although it has autoconversion, we need to cast
|
---|
180 | # explicitly for subscripts to work
|
---|
181 | word = str(m.name)
|
---|
182 | if word[:n] == text:
|
---|
183 | matches.append(word)
|
---|
184 | word = str(m.id)
|
---|
185 | if word[0] == '{':
|
---|
186 | word = word[1:-1]
|
---|
187 | if word[:n] == text:
|
---|
188 | matches.append(word)
|
---|
189 | except Exception,e:
|
---|
190 | traceback.print_exc()
|
---|
191 | print e
|
---|
192 |
|
---|
193 | return matches
|
---|
194 |
|
---|
195 |
|
---|
196 | def autoCompletion(commands, ctx):
|
---|
197 | if not g_hasreadline:
|
---|
198 | return
|
---|
199 |
|
---|
200 | comps = {}
|
---|
201 | for (k,v) in commands.items():
|
---|
202 | comps[k] = None
|
---|
203 | completer = CompleterNG(comps, ctx)
|
---|
204 | readline.set_completer(completer.complete)
|
---|
205 | # OSX need it
|
---|
206 | readline.parse_and_bind ("bind ^I rl_complete")
|
---|
207 | readline.parse_and_bind("tab: complete")
|
---|
208 |
|
---|
209 | g_verbose = True
|
---|
210 |
|
---|
211 | def split_no_quotes(s):
|
---|
212 | return shlex.split(s)
|
---|
213 |
|
---|
214 | def progressBar(ctx,p,wait=1000):
|
---|
215 | try:
|
---|
216 | while not p.completed:
|
---|
217 | print "%d %%\r" %(p.percent),
|
---|
218 | sys.stdout.flush()
|
---|
219 | p.waitForCompletion(wait)
|
---|
220 | ctx['global'].waitForEvents(0)
|
---|
221 | except KeyboardInterrupt:
|
---|
222 | print "Interrupted."
|
---|
223 |
|
---|
224 |
|
---|
225 | def reportError(ctx,session,rc):
|
---|
226 | if not ctx['remote']:
|
---|
227 | print session.QueryErrorObject(rc)
|
---|
228 |
|
---|
229 |
|
---|
230 | def createVm(ctx,name,kind,base):
|
---|
231 | mgr = ctx['mgr']
|
---|
232 | vb = ctx['vb']
|
---|
233 | mach = vb.createMachine(name, kind, base, "")
|
---|
234 | mach.saveSettings()
|
---|
235 | print "created machine with UUID",mach.id
|
---|
236 | vb.registerMachine(mach)
|
---|
237 | # update cache
|
---|
238 | getMachines(ctx, True)
|
---|
239 |
|
---|
240 | def removeVm(ctx,mach):
|
---|
241 | mgr = ctx['mgr']
|
---|
242 | vb = ctx['vb']
|
---|
243 | id = mach.id
|
---|
244 | print "removing machine ",mach.name,"with UUID",id
|
---|
245 | session = ctx['global'].openMachineSession(id)
|
---|
246 | try:
|
---|
247 | mach = session.machine
|
---|
248 | for d in ctx['global'].getArray(mach, 'mediumAttachments'):
|
---|
249 | mach.detachDevice(d.controller, d.port, d.device)
|
---|
250 | except:
|
---|
251 | traceback.print_exc()
|
---|
252 | mach.saveSettings()
|
---|
253 | ctx['global'].closeMachineSession(session)
|
---|
254 | mach = vb.unregisterMachine(id)
|
---|
255 | if mach:
|
---|
256 | mach.deleteSettings()
|
---|
257 | # update cache
|
---|
258 | getMachines(ctx, True)
|
---|
259 |
|
---|
260 | def startVm(ctx,mach,type):
|
---|
261 | mgr = ctx['mgr']
|
---|
262 | vb = ctx['vb']
|
---|
263 | perf = ctx['perf']
|
---|
264 | session = mgr.getSessionObject(vb)
|
---|
265 | uuid = mach.id
|
---|
266 | progress = vb.openRemoteSession(session, uuid, type, "")
|
---|
267 | progressBar(ctx, progress, 100)
|
---|
268 | completed = progress.completed
|
---|
269 | rc = int(progress.resultCode)
|
---|
270 | print "Completed:", completed, "rc:",hex(rc&0xffffffff)
|
---|
271 | if rc == 0:
|
---|
272 | # we ignore exceptions to allow starting VM even if
|
---|
273 | # perf collector cannot be started
|
---|
274 | if perf:
|
---|
275 | try:
|
---|
276 | perf.setup(['*'], [mach], 10, 15)
|
---|
277 | except Exception,e:
|
---|
278 | print e
|
---|
279 | if g_verbose:
|
---|
280 | traceback.print_exc()
|
---|
281 | pass
|
---|
282 | # if session not opened, close doesn't make sense
|
---|
283 | session.close()
|
---|
284 | else:
|
---|
285 | reportError(ctx,session,rc)
|
---|
286 |
|
---|
287 | def getMachines(ctx, invalidate = False):
|
---|
288 | if ctx['vb'] is not None:
|
---|
289 | if ctx['_machlist'] is None or invalidate:
|
---|
290 | ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
|
---|
291 | return ctx['_machlist']
|
---|
292 | else:
|
---|
293 | return []
|
---|
294 |
|
---|
295 | def asState(var):
|
---|
296 | if var:
|
---|
297 | return 'on'
|
---|
298 | else:
|
---|
299 | return 'off'
|
---|
300 |
|
---|
301 | def perfStats(ctx,mach):
|
---|
302 | if not ctx['perf']:
|
---|
303 | return
|
---|
304 | for metric in ctx['perf'].query(["*"], [mach]):
|
---|
305 | print metric['name'], metric['values_as_string']
|
---|
306 |
|
---|
307 | def guestExec(ctx, machine, console, cmds):
|
---|
308 | exec cmds
|
---|
309 |
|
---|
310 | def monitorGuest(ctx, machine, console, dur):
|
---|
311 | cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
|
---|
312 | console.registerCallback(cb)
|
---|
313 | if dur == -1:
|
---|
314 | # not infinity, but close enough
|
---|
315 | dur = 100000
|
---|
316 | try:
|
---|
317 | end = time.time() + dur
|
---|
318 | while time.time() < end:
|
---|
319 | ctx['global'].waitForEvents(500)
|
---|
320 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
321 | except:
|
---|
322 | pass
|
---|
323 | console.unregisterCallback(cb)
|
---|
324 |
|
---|
325 |
|
---|
326 | def monitorVBox(ctx, dur):
|
---|
327 | vbox = ctx['vb']
|
---|
328 | isMscom = (ctx['global'].type == 'MSCOM')
|
---|
329 | cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
|
---|
330 | vbox.registerCallback(cb)
|
---|
331 | if dur == -1:
|
---|
332 | # not infinity, but close enough
|
---|
333 | dur = 100000
|
---|
334 | try:
|
---|
335 | end = time.time() + dur
|
---|
336 | while time.time() < end:
|
---|
337 | ctx['global'].waitForEvents(500)
|
---|
338 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
339 | except:
|
---|
340 | pass
|
---|
341 | vbox.unregisterCallback(cb)
|
---|
342 |
|
---|
343 |
|
---|
344 | def takeScreenshot(ctx,console,args):
|
---|
345 | from PIL import Image
|
---|
346 | display = console.display
|
---|
347 | if len(args) > 0:
|
---|
348 | f = args[0]
|
---|
349 | else:
|
---|
350 | f = "/tmp/screenshot.png"
|
---|
351 | if len(args) > 1:
|
---|
352 | w = args[1]
|
---|
353 | else:
|
---|
354 | w = console.display.width
|
---|
355 | if len(args) > 2:
|
---|
356 | h = args[2]
|
---|
357 | else:
|
---|
358 | h = console.display.height
|
---|
359 | print "Saving screenshot (%d x %d) in %s..." %(w,h,f)
|
---|
360 | data = display.takeScreenShotSlow(w,h)
|
---|
361 | size = (w,h)
|
---|
362 | mode = "RGBA"
|
---|
363 | im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
|
---|
364 | im.save(f, "PNG")
|
---|
365 |
|
---|
366 |
|
---|
367 | def teleport(ctx,session,console,args):
|
---|
368 | if args[0].find(":") == -1:
|
---|
369 | print "Use host:port format for teleport target"
|
---|
370 | return
|
---|
371 | (host,port) = args[0].split(":")
|
---|
372 | if len(args) > 1:
|
---|
373 | passwd = args[1]
|
---|
374 | else:
|
---|
375 | passwd = ""
|
---|
376 |
|
---|
377 | if len(args) > 2:
|
---|
378 | maxDowntime = int(args[2])
|
---|
379 | else:
|
---|
380 | maxDowntime = 250
|
---|
381 |
|
---|
382 | port = int(port)
|
---|
383 | print "Teleporting to %s:%d..." %(host,port)
|
---|
384 | progress = console.teleport(host, port, passwd, maxDowntime)
|
---|
385 | progressBar(ctx, progress, 100)
|
---|
386 | completed = progress.completed
|
---|
387 | rc = int(progress.resultCode)
|
---|
388 | if rc == 0:
|
---|
389 | print "Success!"
|
---|
390 | else:
|
---|
391 | reportError(ctx,session,rc)
|
---|
392 |
|
---|
393 |
|
---|
394 | def guestStats(ctx,console,args):
|
---|
395 | guest = console.guest
|
---|
396 | # we need to set up guest statistics
|
---|
397 | if len(args) > 0 :
|
---|
398 | update = args[0]
|
---|
399 | else:
|
---|
400 | update = 1
|
---|
401 | if guest.statisticsUpdateInterval != update:
|
---|
402 | guest.statisticsUpdateInterval = update
|
---|
403 | try:
|
---|
404 | time.sleep(float(update)+0.1)
|
---|
405 | except:
|
---|
406 | # to allow sleep interruption
|
---|
407 | pass
|
---|
408 | all_stats = ctx['ifaces'].all_values('GuestStatisticType')
|
---|
409 | cpu = 0
|
---|
410 | for s in all_stats.keys():
|
---|
411 | try:
|
---|
412 | val = guest.getStatistic( cpu, all_stats[s])
|
---|
413 | print "%s: %d" %(s, val)
|
---|
414 | except:
|
---|
415 | # likely not implemented
|
---|
416 | pass
|
---|
417 |
|
---|
418 | def plugCpu(ctx,machine,session,args):
|
---|
419 | cpu = int(args)
|
---|
420 | print "Adding CPU %d..." %(cpu)
|
---|
421 | machine.hotPlugCPU(cpu)
|
---|
422 |
|
---|
423 | def unplugCpu(ctx,machine,session,args):
|
---|
424 | cpu = int(args)
|
---|
425 | print "Removing CPU %d..." %(cpu)
|
---|
426 | machine.hotUnplugCPU(cpu)
|
---|
427 |
|
---|
428 | def cmdExistingVm(ctx,mach,cmd,args):
|
---|
429 | mgr=ctx['mgr']
|
---|
430 | vb=ctx['vb']
|
---|
431 | session = mgr.getSessionObject(vb)
|
---|
432 | uuid = mach.id
|
---|
433 | try:
|
---|
434 | progress = vb.openExistingSession(session, uuid)
|
---|
435 | except Exception,e:
|
---|
436 | print "Session to '%s' not open: %s" %(mach.name,e)
|
---|
437 | if g_verbose:
|
---|
438 | traceback.print_exc()
|
---|
439 | return
|
---|
440 | if str(session.state) != str(ctx['ifaces'].SessionState_Open):
|
---|
441 | print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
|
---|
442 | return
|
---|
443 | # this could be an example how to handle local only (i.e. unavailable
|
---|
444 | # in Webservices) functionality
|
---|
445 | if ctx['remote'] and cmd == 'some_local_only_command':
|
---|
446 | print 'Trying to use local only functionality, ignored'
|
---|
447 | return
|
---|
448 | console=session.console
|
---|
449 | ops={'pause': lambda: console.pause(),
|
---|
450 | 'resume': lambda: console.resume(),
|
---|
451 | 'powerdown': lambda: console.powerDown(),
|
---|
452 | 'powerbutton': lambda: console.powerButton(),
|
---|
453 | 'stats': lambda: perfStats(ctx, mach),
|
---|
454 | 'guest': lambda: guestExec(ctx, mach, console, args),
|
---|
455 | 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
|
---|
456 | 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
|
---|
457 | 'save': lambda: progressBar(ctx,console.saveState()),
|
---|
458 | 'screenshot': lambda: takeScreenshot(ctx,console,args),
|
---|
459 | 'teleport': lambda: teleport(ctx,session,console,args),
|
---|
460 | 'gueststats': lambda: guestStats(ctx, console, args),
|
---|
461 | 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
|
---|
462 | 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
|
---|
463 | }
|
---|
464 | try:
|
---|
465 | ops[cmd]()
|
---|
466 | except Exception, e:
|
---|
467 | print 'failed: ',e
|
---|
468 | if g_verbose:
|
---|
469 | traceback.print_exc()
|
---|
470 |
|
---|
471 | session.close()
|
---|
472 |
|
---|
473 | def machById(ctx,id):
|
---|
474 | mach = None
|
---|
475 | for m in getMachines(ctx):
|
---|
476 | if m.name == id:
|
---|
477 | mach = m
|
---|
478 | break
|
---|
479 | mid = str(m.id)
|
---|
480 | if mid[0] == '{':
|
---|
481 | mid = mid[1:-1]
|
---|
482 | if mid == id:
|
---|
483 | mach = m
|
---|
484 | break
|
---|
485 | return mach
|
---|
486 |
|
---|
487 | def argsToMach(ctx,args):
|
---|
488 | if len(args) < 2:
|
---|
489 | print "usage: %s [vmname|uuid]" %(args[0])
|
---|
490 | return None
|
---|
491 | id = args[1]
|
---|
492 | m = machById(ctx, id)
|
---|
493 | if m == None:
|
---|
494 | print "Machine '%s' is unknown, use list command to find available machines" %(id)
|
---|
495 | return m
|
---|
496 |
|
---|
497 | def helpSingleCmd(cmd,h,sp):
|
---|
498 | if sp != 0:
|
---|
499 | spec = " [ext from "+sp+"]"
|
---|
500 | else:
|
---|
501 | spec = ""
|
---|
502 | print " %s: %s%s" %(cmd,h,spec)
|
---|
503 |
|
---|
504 | def helpCmd(ctx, args):
|
---|
505 | if len(args) == 1:
|
---|
506 | print "Help page:"
|
---|
507 | names = commands.keys()
|
---|
508 | names.sort()
|
---|
509 | for i in names:
|
---|
510 | helpSingleCmd(i, commands[i][0], commands[i][2])
|
---|
511 | else:
|
---|
512 | cmd = args[1]
|
---|
513 | c = commands.get(cmd)
|
---|
514 | if c == None:
|
---|
515 | print "Command '%s' not known" %(cmd)
|
---|
516 | else:
|
---|
517 | helpSingleCmd(cmd, c[0], c[2])
|
---|
518 | return 0
|
---|
519 |
|
---|
520 | def listCmd(ctx, args):
|
---|
521 | for m in getMachines(ctx, True):
|
---|
522 | if m.teleporterEnabled:
|
---|
523 | tele = "[T] "
|
---|
524 | else:
|
---|
525 | tele = " "
|
---|
526 | print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,m.sessionState)
|
---|
527 | return 0
|
---|
528 |
|
---|
529 | def asEnumElem(ctx,enum,elem):
|
---|
530 | all = ctx['ifaces'].all_values(enum)
|
---|
531 | for e in all.keys():
|
---|
532 | if elem == all[e]:
|
---|
533 | return e
|
---|
534 | return "<unknown>"
|
---|
535 |
|
---|
536 | def infoCmd(ctx,args):
|
---|
537 | if (len(args) < 2):
|
---|
538 | print "usage: info [vmname|uuid]"
|
---|
539 | return 0
|
---|
540 | mach = argsToMach(ctx,args)
|
---|
541 | if mach == None:
|
---|
542 | return 0
|
---|
543 | os = ctx['vb'].getGuestOSType(mach.OSTypeId)
|
---|
544 | print " One can use setvar <mach> <var> <value> to change variable, using name in []."
|
---|
545 | print " Name [name]: %s" %(mach.name)
|
---|
546 | print " ID [n/a]: %s" %(mach.id)
|
---|
547 | print " OS Type [via OSTypeId]: %s" %(os.description)
|
---|
548 | print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
|
---|
549 | print
|
---|
550 | print " CPUs [CPUCount]: %d" %(mach.CPUCount)
|
---|
551 | print " RAM [memorySize]: %dM" %(mach.memorySize)
|
---|
552 | print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
|
---|
553 | print " Monitors [monitorCount]: %d" %(mach.monitorCount)
|
---|
554 | print
|
---|
555 | print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
|
---|
556 | print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
|
---|
557 | print
|
---|
558 | if mach.teleporterEnabled:
|
---|
559 | print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
|
---|
560 | print
|
---|
561 | bios = mach.BIOSSettings
|
---|
562 | print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
|
---|
563 | print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
|
---|
564 | hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
|
---|
565 | print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
|
---|
566 | hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
|
---|
567 | print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
|
---|
568 | hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
|
---|
569 | print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
|
---|
570 |
|
---|
571 | print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
|
---|
572 | print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
|
---|
573 |
|
---|
574 | print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
|
---|
575 | if mach.audioAdapter.enabled:
|
---|
576 | print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
|
---|
577 | print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
|
---|
578 |
|
---|
579 | print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
|
---|
580 | print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
|
---|
581 | print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
|
---|
582 | print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
|
---|
583 |
|
---|
584 | controllers = ctx['global'].getArray(mach, 'storageControllers')
|
---|
585 | if controllers:
|
---|
586 | print
|
---|
587 | print " Controllers:"
|
---|
588 | for controller in controllers:
|
---|
589 | print " %s %s bus: %d" % (controller.name, asEnumElem(ctx,"StorageControllerType", controller.controllerType), controller.bus)
|
---|
590 |
|
---|
591 | attaches = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
592 | if attaches:
|
---|
593 | print
|
---|
594 | print " Mediums:"
|
---|
595 | for a in attaches:
|
---|
596 | print " Controller: %s port: %d device: %d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
|
---|
597 | m = a.medium
|
---|
598 | if a.type == ctx['global'].constants.DeviceType_HardDisk:
|
---|
599 | print " HDD:"
|
---|
600 | print " Id: %s" %(m.id)
|
---|
601 | print " Location: %s" %(m.location)
|
---|
602 | print " Name: %s" %(m.name)
|
---|
603 | print " Format: %s" %(m.format)
|
---|
604 |
|
---|
605 | if a.type == ctx['global'].constants.DeviceType_DVD:
|
---|
606 | print " DVD:"
|
---|
607 | if m:
|
---|
608 | print " Id: %s" %(m.id)
|
---|
609 | print " Name: %s" %(m.name)
|
---|
610 | if m.hostDrive:
|
---|
611 | print " Host DVD %s" %(m.location)
|
---|
612 | if a.passthrough:
|
---|
613 | print " [passthrough mode]"
|
---|
614 | else:
|
---|
615 | print " Virtual image at %s" %(m.location)
|
---|
616 | print " Size: %s" %(m.size)
|
---|
617 |
|
---|
618 | if a.type == ctx['global'].constants.DeviceType_Floppy:
|
---|
619 | print " Floppy:"
|
---|
620 | if m:
|
---|
621 | print " Id: %s" %(m.id)
|
---|
622 | print " Name: %s" %(m.name)
|
---|
623 | if m.hostDrive:
|
---|
624 | print " Host floppy %s" %(m.location)
|
---|
625 | else:
|
---|
626 | print " Virtual image at %s" %(m.location)
|
---|
627 | print " Size: %s" %(m.size)
|
---|
628 |
|
---|
629 | return 0
|
---|
630 |
|
---|
631 | def startCmd(ctx, args):
|
---|
632 | mach = argsToMach(ctx,args)
|
---|
633 | if mach == None:
|
---|
634 | return 0
|
---|
635 | if len(args) > 2:
|
---|
636 | type = args[2]
|
---|
637 | else:
|
---|
638 | type = "gui"
|
---|
639 | startVm(ctx, mach, type)
|
---|
640 | return 0
|
---|
641 |
|
---|
642 | def createCmd(ctx, args):
|
---|
643 | if (len(args) < 3 or len(args) > 4):
|
---|
644 | print "usage: create name ostype <basefolder>"
|
---|
645 | return 0
|
---|
646 | name = args[1]
|
---|
647 | oskind = args[2]
|
---|
648 | if len(args) == 4:
|
---|
649 | base = args[3]
|
---|
650 | else:
|
---|
651 | base = ''
|
---|
652 | try:
|
---|
653 | ctx['vb'].getGuestOSType(oskind)
|
---|
654 | except Exception, e:
|
---|
655 | print 'Unknown OS type:',oskind
|
---|
656 | return 0
|
---|
657 | createVm(ctx, name, oskind, base)
|
---|
658 | return 0
|
---|
659 |
|
---|
660 | def removeCmd(ctx, args):
|
---|
661 | mach = argsToMach(ctx,args)
|
---|
662 | if mach == None:
|
---|
663 | return 0
|
---|
664 | removeVm(ctx, mach)
|
---|
665 | return 0
|
---|
666 |
|
---|
667 | def pauseCmd(ctx, args):
|
---|
668 | mach = argsToMach(ctx,args)
|
---|
669 | if mach == None:
|
---|
670 | return 0
|
---|
671 | cmdExistingVm(ctx, mach, 'pause', '')
|
---|
672 | return 0
|
---|
673 |
|
---|
674 | def powerdownCmd(ctx, args):
|
---|
675 | mach = argsToMach(ctx,args)
|
---|
676 | if mach == None:
|
---|
677 | return 0
|
---|
678 | cmdExistingVm(ctx, mach, 'powerdown', '')
|
---|
679 | return 0
|
---|
680 |
|
---|
681 | def powerbuttonCmd(ctx, args):
|
---|
682 | mach = argsToMach(ctx,args)
|
---|
683 | if mach == None:
|
---|
684 | return 0
|
---|
685 | cmdExistingVm(ctx, mach, 'powerbutton', '')
|
---|
686 | return 0
|
---|
687 |
|
---|
688 | def resumeCmd(ctx, args):
|
---|
689 | mach = argsToMach(ctx,args)
|
---|
690 | if mach == None:
|
---|
691 | return 0
|
---|
692 | cmdExistingVm(ctx, mach, 'resume', '')
|
---|
693 | return 0
|
---|
694 |
|
---|
695 | def saveCmd(ctx, args):
|
---|
696 | mach = argsToMach(ctx,args)
|
---|
697 | if mach == None:
|
---|
698 | return 0
|
---|
699 | cmdExistingVm(ctx, mach, 'save', '')
|
---|
700 | return 0
|
---|
701 |
|
---|
702 | def statsCmd(ctx, args):
|
---|
703 | mach = argsToMach(ctx,args)
|
---|
704 | if mach == None:
|
---|
705 | return 0
|
---|
706 | cmdExistingVm(ctx, mach, 'stats', '')
|
---|
707 | return 0
|
---|
708 |
|
---|
709 | def guestCmd(ctx, args):
|
---|
710 | if (len(args) < 3):
|
---|
711 | print "usage: guest name commands"
|
---|
712 | return 0
|
---|
713 | mach = argsToMach(ctx,args)
|
---|
714 | if mach == None:
|
---|
715 | return 0
|
---|
716 | cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
|
---|
717 | return 0
|
---|
718 |
|
---|
719 | def screenshotCmd(ctx, args):
|
---|
720 | if (len(args) < 3):
|
---|
721 | print "usage: screenshot name file <width> <height>"
|
---|
722 | return 0
|
---|
723 | mach = argsToMach(ctx,args)
|
---|
724 | if mach == None:
|
---|
725 | return 0
|
---|
726 | cmdExistingVm(ctx, mach, 'screenshot', args[2:])
|
---|
727 | return 0
|
---|
728 |
|
---|
729 | def teleportCmd(ctx, args):
|
---|
730 | if (len(args) < 3):
|
---|
731 | print "usage: teleport name host:port <password>"
|
---|
732 | return 0
|
---|
733 | mach = argsToMach(ctx,args)
|
---|
734 | if mach == None:
|
---|
735 | return 0
|
---|
736 | cmdExistingVm(ctx, mach, 'teleport', args[2:])
|
---|
737 | return 0
|
---|
738 |
|
---|
739 | def openportalCmd(ctx, args):
|
---|
740 | if (len(args) < 3):
|
---|
741 | print "usage: openportal name port <password>"
|
---|
742 | return 0
|
---|
743 | mach = argsToMach(ctx,args)
|
---|
744 | if mach == None:
|
---|
745 | return 0
|
---|
746 | port = int(args[2])
|
---|
747 | if (len(args) > 3):
|
---|
748 | passwd = args[3]
|
---|
749 | else:
|
---|
750 | passwd = ""
|
---|
751 | if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
|
---|
752 | session = ctx['global'].openMachineSession(mach.id)
|
---|
753 | mach1 = session.machine
|
---|
754 | mach1.teleporterEnabled = True
|
---|
755 | mach1.teleporterPort = port
|
---|
756 | mach1.teleporterPassword = passwd
|
---|
757 | mach1.saveSettings()
|
---|
758 | session.close()
|
---|
759 | startVm(ctx, mach, "gui")
|
---|
760 | return 0
|
---|
761 |
|
---|
762 | def closeportalCmd(ctx, args):
|
---|
763 | if (len(args) < 2):
|
---|
764 | print "usage: closeportal name"
|
---|
765 | return 0
|
---|
766 | mach = argsToMach(ctx,args)
|
---|
767 | if mach == None:
|
---|
768 | return 0
|
---|
769 | if mach.teleporterEnabled:
|
---|
770 | session = ctx['global'].openMachineSession(mach.id)
|
---|
771 | mach1 = session.machine
|
---|
772 | mach1.teleporterEnabled = False
|
---|
773 | mach1.saveSettings()
|
---|
774 | session.close()
|
---|
775 | return 0
|
---|
776 |
|
---|
777 | def gueststatsCmd(ctx, args):
|
---|
778 | if (len(args) < 2):
|
---|
779 | print "usage: gueststats name <check interval>"
|
---|
780 | return 0
|
---|
781 | mach = argsToMach(ctx,args)
|
---|
782 | if mach == None:
|
---|
783 | return 0
|
---|
784 | cmdExistingVm(ctx, mach, 'gueststats', args[2:])
|
---|
785 | return 0
|
---|
786 |
|
---|
787 | def plugcpuCmd(ctx, args):
|
---|
788 | if (len(args) < 2):
|
---|
789 | print "usage: plugcpu name cpuid"
|
---|
790 | return 0
|
---|
791 | mach = argsToMach(ctx,args)
|
---|
792 | if mach == None:
|
---|
793 | return 0
|
---|
794 | if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
|
---|
795 | if mach.CPUHotPlugEnabled:
|
---|
796 | session = ctx['global'].openMachineSession(mach.id)
|
---|
797 | try:
|
---|
798 | mach1 = session.machine
|
---|
799 | cpu = int(args[2])
|
---|
800 | print "Adding CPU %d..." %(cpu)
|
---|
801 | mach1.hotPlugCPU(cpu)
|
---|
802 | mach1.saveSettings()
|
---|
803 | except:
|
---|
804 | session.close()
|
---|
805 | raise
|
---|
806 | session.close()
|
---|
807 | else:
|
---|
808 | cmdExistingVm(ctx, mach, 'plugcpu', args[2])
|
---|
809 | return 0
|
---|
810 |
|
---|
811 | def unplugcpuCmd(ctx, args):
|
---|
812 | if (len(args) < 2):
|
---|
813 | print "usage: unplugcpu name cpuid"
|
---|
814 | return 0
|
---|
815 | mach = argsToMach(ctx,args)
|
---|
816 | if mach == None:
|
---|
817 | return 0
|
---|
818 | if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
|
---|
819 | if mach.CPUHotPlugEnabled:
|
---|
820 | session = ctx['global'].openMachineSession(mach.id)
|
---|
821 | try:
|
---|
822 | mach1 = session.machine
|
---|
823 | cpu = int(args[2])
|
---|
824 | print "Removing CPU %d..." %(cpu)
|
---|
825 | mach1.hotUnplugCPU(cpu)
|
---|
826 | mach1.saveSettings()
|
---|
827 | except:
|
---|
828 | session.close()
|
---|
829 | raise
|
---|
830 | session.close()
|
---|
831 | else:
|
---|
832 | cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
|
---|
833 | return 0
|
---|
834 |
|
---|
835 | def setvarCmd(ctx, args):
|
---|
836 | if (len(args) < 4):
|
---|
837 | print "usage: setvar [vmname|uuid] expr value"
|
---|
838 | return 0
|
---|
839 | mach = argsToMach(ctx,args)
|
---|
840 | if mach == None:
|
---|
841 | return 0
|
---|
842 | session = ctx['global'].openMachineSession(mach.id)
|
---|
843 | mach = session.machine
|
---|
844 | expr = 'mach.'+args[2]+' = '+args[3]
|
---|
845 | print "Executing",expr
|
---|
846 | try:
|
---|
847 | exec expr
|
---|
848 | except Exception, e:
|
---|
849 | print 'failed: ',e
|
---|
850 | if g_verbose:
|
---|
851 | traceback.print_exc()
|
---|
852 | mach.saveSettings()
|
---|
853 | session.close()
|
---|
854 | return 0
|
---|
855 |
|
---|
856 |
|
---|
857 | def setExtraDataCmd(ctx, args):
|
---|
858 | if (len(args) < 3):
|
---|
859 | print "usage: setextra [vmname|uuid|global] key <value>"
|
---|
860 | return 0
|
---|
861 | key = args[2]
|
---|
862 | if len(args) == 4:
|
---|
863 | value = args[3]
|
---|
864 | else:
|
---|
865 | value = None
|
---|
866 | if args[1] == 'global':
|
---|
867 | ctx['vb'].setExtraData(key, value)
|
---|
868 | return 0
|
---|
869 |
|
---|
870 | mach = argsToMach(ctx,args)
|
---|
871 | if mach == None:
|
---|
872 | return 0
|
---|
873 | session = ctx['global'].openMachineSession(mach.id)
|
---|
874 | mach = session.machine
|
---|
875 | mach.setExtraData(key, value)
|
---|
876 | mach.saveSettings()
|
---|
877 | session.close()
|
---|
878 | return 0
|
---|
879 |
|
---|
880 | def printExtraKey(obj, key, value):
|
---|
881 | print "%s: '%s' = '%s'" %(obj, key, value)
|
---|
882 |
|
---|
883 | def getExtraDataCmd(ctx, args):
|
---|
884 | if (len(args) < 2):
|
---|
885 | print "usage: getextra [vmname|uuid|global] <key>"
|
---|
886 | return 0
|
---|
887 | if len(args) == 3:
|
---|
888 | key = args[2]
|
---|
889 | else:
|
---|
890 | key = None
|
---|
891 |
|
---|
892 | if args[1] == 'global':
|
---|
893 | obj = ctx['vb']
|
---|
894 | else:
|
---|
895 | obj = argsToMach(ctx,args)
|
---|
896 | if obj == None:
|
---|
897 | return 0
|
---|
898 |
|
---|
899 | if key == None:
|
---|
900 | keys = obj.getExtraDataKeys()
|
---|
901 | else:
|
---|
902 | keys = [ key ]
|
---|
903 | for k in keys:
|
---|
904 | printExtraKey(args[1], k, ctx['vb'].getExtraData(k))
|
---|
905 |
|
---|
906 | return 0
|
---|
907 |
|
---|
908 | def quitCmd(ctx, args):
|
---|
909 | return 1
|
---|
910 |
|
---|
911 | def aliasCmd(ctx, args):
|
---|
912 | if (len(args) == 3):
|
---|
913 | aliases[args[1]] = args[2]
|
---|
914 | return 0
|
---|
915 |
|
---|
916 | for (k,v) in aliases.items():
|
---|
917 | print "'%s' is an alias for '%s'" %(k,v)
|
---|
918 | return 0
|
---|
919 |
|
---|
920 | def verboseCmd(ctx, args):
|
---|
921 | global g_verbose
|
---|
922 | g_verbose = not g_verbose
|
---|
923 | return 0
|
---|
924 |
|
---|
925 | def getUSBStateString(state):
|
---|
926 | if state == 0:
|
---|
927 | return "NotSupported"
|
---|
928 | elif state == 1:
|
---|
929 | return "Unavailable"
|
---|
930 | elif state == 2:
|
---|
931 | return "Busy"
|
---|
932 | elif state == 3:
|
---|
933 | return "Available"
|
---|
934 | elif state == 4:
|
---|
935 | return "Held"
|
---|
936 | elif state == 5:
|
---|
937 | return "Captured"
|
---|
938 | else:
|
---|
939 | return "Unknown"
|
---|
940 |
|
---|
941 | def hostCmd(ctx, args):
|
---|
942 | host = ctx['vb'].host
|
---|
943 | cnt = host.processorCount
|
---|
944 | print "Processor count:",cnt
|
---|
945 | for i in range(0,cnt):
|
---|
946 | print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
|
---|
947 |
|
---|
948 | print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
|
---|
949 | print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
|
---|
950 | if host.Acceleration3DAvailable:
|
---|
951 | print "3D acceleration available"
|
---|
952 | else:
|
---|
953 | print "3D acceleration NOT available"
|
---|
954 |
|
---|
955 | print "Network interfaces:"
|
---|
956 | for ni in ctx['global'].getArray(host, 'networkInterfaces'):
|
---|
957 | print " %s (%s)" %(ni.name, ni.IPAddress)
|
---|
958 |
|
---|
959 | print "DVD drives:"
|
---|
960 | for dd in ctx['global'].getArray(host, 'DVDDrives'):
|
---|
961 | print " %s - %s" %(dd.name, dd.description)
|
---|
962 |
|
---|
963 | print "USB devices:"
|
---|
964 | for ud in ctx['global'].getArray(host, 'USBDevices'):
|
---|
965 | print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
|
---|
966 |
|
---|
967 | if ctx['perf']:
|
---|
968 | for metric in ctx['perf'].query(["*"], [host]):
|
---|
969 | print metric['name'], metric['values_as_string']
|
---|
970 |
|
---|
971 | return 0
|
---|
972 |
|
---|
973 | def monitorGuestCmd(ctx, args):
|
---|
974 | if (len(args) < 2):
|
---|
975 | print "usage: monitorGuest name (duration)"
|
---|
976 | return 0
|
---|
977 | mach = argsToMach(ctx,args)
|
---|
978 | if mach == None:
|
---|
979 | return 0
|
---|
980 | dur = 5
|
---|
981 | if len(args) > 2:
|
---|
982 | dur = float(args[2])
|
---|
983 | cmdExistingVm(ctx, mach, 'monitorGuest', dur)
|
---|
984 | return 0
|
---|
985 |
|
---|
986 | def monitorVBoxCmd(ctx, args):
|
---|
987 | if (len(args) > 2):
|
---|
988 | print "usage: monitorVBox (duration)"
|
---|
989 | return 0
|
---|
990 | dur = 5
|
---|
991 | if len(args) > 1:
|
---|
992 | dur = float(args[1])
|
---|
993 | monitorVBox(ctx, dur)
|
---|
994 | return 0
|
---|
995 |
|
---|
996 | def getAdapterType(ctx, type):
|
---|
997 | if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
|
---|
998 | type == ctx['global'].constants.NetworkAdapterType_Am79C973):
|
---|
999 | return "pcnet"
|
---|
1000 | elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
|
---|
1001 | type == ctx['global'].constants.NetworkAdapterType_I82545EM or
|
---|
1002 | type == ctx['global'].constants.NetworkAdapterType_I82543GC):
|
---|
1003 | return "e1000"
|
---|
1004 | elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
|
---|
1005 | return "virtio"
|
---|
1006 | elif (type == ctx['global'].constants.NetworkAdapterType_Null):
|
---|
1007 | return None
|
---|
1008 | else:
|
---|
1009 | raise Exception("Unknown adapter type: "+type)
|
---|
1010 |
|
---|
1011 |
|
---|
1012 | def portForwardCmd(ctx, args):
|
---|
1013 | if (len(args) != 5):
|
---|
1014 | print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
|
---|
1015 | return 0
|
---|
1016 | mach = argsToMach(ctx,args)
|
---|
1017 | if mach == None:
|
---|
1018 | return 0
|
---|
1019 | adapterNum = int(args[2])
|
---|
1020 | hostPort = int(args[3])
|
---|
1021 | guestPort = int(args[4])
|
---|
1022 | proto = "TCP"
|
---|
1023 | session = ctx['global'].openMachineSession(mach.id)
|
---|
1024 | mach = session.machine
|
---|
1025 |
|
---|
1026 | adapter = mach.getNetworkAdapter(adapterNum)
|
---|
1027 | adapterType = getAdapterType(ctx, adapter.adapterType)
|
---|
1028 |
|
---|
1029 | profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
|
---|
1030 | config = "VBoxInternal/Devices/" + adapterType + "/"
|
---|
1031 | config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
|
---|
1032 |
|
---|
1033 | mach.setExtraData(config + "/Protocol", proto)
|
---|
1034 | mach.setExtraData(config + "/HostPort", str(hostPort))
|
---|
1035 | mach.setExtraData(config + "/GuestPort", str(guestPort))
|
---|
1036 |
|
---|
1037 | mach.saveSettings()
|
---|
1038 | session.close()
|
---|
1039 |
|
---|
1040 | return 0
|
---|
1041 |
|
---|
1042 |
|
---|
1043 | def showLogCmd(ctx, args):
|
---|
1044 | if (len(args) < 2):
|
---|
1045 | print "usage: showLog <vm> <num>"
|
---|
1046 | return 0
|
---|
1047 | mach = argsToMach(ctx,args)
|
---|
1048 | if mach == None:
|
---|
1049 | return 0
|
---|
1050 |
|
---|
1051 | log = "VBox.log"
|
---|
1052 | if (len(args) > 2):
|
---|
1053 | log += "."+args[2]
|
---|
1054 | fileName = os.path.join(mach.logFolder, log)
|
---|
1055 |
|
---|
1056 | try:
|
---|
1057 | lf = open(fileName, 'r')
|
---|
1058 | except IOError,e:
|
---|
1059 | print "cannot open: ",e
|
---|
1060 | return 0
|
---|
1061 |
|
---|
1062 | for line in lf:
|
---|
1063 | print line,
|
---|
1064 | lf.close()
|
---|
1065 |
|
---|
1066 | return 0
|
---|
1067 |
|
---|
1068 | def evalCmd(ctx, args):
|
---|
1069 | expr = ' '.join(args[1:])
|
---|
1070 | try:
|
---|
1071 | exec expr
|
---|
1072 | except Exception, e:
|
---|
1073 | print 'failed: ',e
|
---|
1074 | if g_verbose:
|
---|
1075 | traceback.print_exc()
|
---|
1076 | return 0
|
---|
1077 |
|
---|
1078 | def reloadExtCmd(ctx, args):
|
---|
1079 | # maybe will want more args smartness
|
---|
1080 | checkUserExtensions(ctx, commands, getHomeFolder(ctx))
|
---|
1081 | autoCompletion(commands, ctx)
|
---|
1082 | return 0
|
---|
1083 |
|
---|
1084 |
|
---|
1085 | def runScriptCmd(ctx, args):
|
---|
1086 | if (len(args) != 2):
|
---|
1087 | print "usage: runScript <script>"
|
---|
1088 | return 0
|
---|
1089 | try:
|
---|
1090 | lf = open(args[1], 'r')
|
---|
1091 | except IOError,e:
|
---|
1092 | print "cannot open:",args[1], ":",e
|
---|
1093 | return 0
|
---|
1094 |
|
---|
1095 | try:
|
---|
1096 | for line in lf:
|
---|
1097 | done = runCommand(ctx, line)
|
---|
1098 | if done != 0: break
|
---|
1099 | except Exception,e:
|
---|
1100 | print "error:",e
|
---|
1101 | if g_verbose:
|
---|
1102 | traceback.print_exc()
|
---|
1103 | lf.close()
|
---|
1104 | return 0
|
---|
1105 |
|
---|
1106 | def sleepCmd(ctx, args):
|
---|
1107 | if (len(args) != 2):
|
---|
1108 | print "usage: sleep <secs>"
|
---|
1109 | return 0
|
---|
1110 |
|
---|
1111 | try:
|
---|
1112 | time.sleep(float(args[1]))
|
---|
1113 | except:
|
---|
1114 | # to allow sleep interrupt
|
---|
1115 | pass
|
---|
1116 | return 0
|
---|
1117 |
|
---|
1118 |
|
---|
1119 | def shellCmd(ctx, args):
|
---|
1120 | if (len(args) < 2):
|
---|
1121 | print "usage: shell <commands>"
|
---|
1122 | return 0
|
---|
1123 | cmd = ' '.join(args[1:])
|
---|
1124 | try:
|
---|
1125 | os.system(cmd)
|
---|
1126 | except KeyboardInterrupt:
|
---|
1127 | # to allow shell command interruption
|
---|
1128 | pass
|
---|
1129 | return 0
|
---|
1130 |
|
---|
1131 |
|
---|
1132 | def connectCmd(ctx, args):
|
---|
1133 | if (len(args) > 4):
|
---|
1134 | print "usage: connect [url] [username] [passwd]"
|
---|
1135 | return 0
|
---|
1136 |
|
---|
1137 | if ctx['vb'] is not None:
|
---|
1138 | print "Already connected, disconnect first..."
|
---|
1139 | return 0
|
---|
1140 |
|
---|
1141 | if (len(args) > 1):
|
---|
1142 | url = args[1]
|
---|
1143 | else:
|
---|
1144 | url = None
|
---|
1145 |
|
---|
1146 | if (len(args) > 2):
|
---|
1147 | user = args[2]
|
---|
1148 | else:
|
---|
1149 | user = ""
|
---|
1150 |
|
---|
1151 | if (len(args) > 3):
|
---|
1152 | passwd = args[3]
|
---|
1153 | else:
|
---|
1154 | passwd = ""
|
---|
1155 |
|
---|
1156 | vbox = ctx['global'].platform.connect(url, user, passwd)
|
---|
1157 | ctx['vb'] = vbox
|
---|
1158 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1159 | ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
|
---|
1160 | return 0
|
---|
1161 |
|
---|
1162 | def disconnectCmd(ctx, args):
|
---|
1163 | if (len(args) != 1):
|
---|
1164 | print "usage: disconnect"
|
---|
1165 | return 0
|
---|
1166 |
|
---|
1167 | if ctx['vb'] is None:
|
---|
1168 | print "Not connected yet."
|
---|
1169 | return 0
|
---|
1170 |
|
---|
1171 | try:
|
---|
1172 | ctx['global'].platform.disconnect()
|
---|
1173 | except:
|
---|
1174 | ctx['vb'] = None
|
---|
1175 | raise
|
---|
1176 |
|
---|
1177 | ctx['vb'] = None
|
---|
1178 | return 0
|
---|
1179 |
|
---|
1180 | def exportVMCmd(ctx, args):
|
---|
1181 | import sys
|
---|
1182 |
|
---|
1183 | if len(args) < 3:
|
---|
1184 | print "usage: exportVm <machine> <path> <format> <license>"
|
---|
1185 | return 0
|
---|
1186 | mach = ctx['machById'](args[1])
|
---|
1187 | if mach is None:
|
---|
1188 | return 0
|
---|
1189 | path = args[2]
|
---|
1190 | if (len(args) > 3):
|
---|
1191 | format = args[3]
|
---|
1192 | else:
|
---|
1193 | format = "ovf-1.0"
|
---|
1194 | if (len(args) > 4):
|
---|
1195 | license = args[4]
|
---|
1196 | else:
|
---|
1197 | license = "GPL"
|
---|
1198 |
|
---|
1199 | app = ctx['vb'].createAppliance()
|
---|
1200 | desc = mach.export(app)
|
---|
1201 | desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
|
---|
1202 | p = app.write(format, path)
|
---|
1203 | progressBar(ctx, p)
|
---|
1204 | print "Exported to %s in format %s" %(path, format)
|
---|
1205 | return 0
|
---|
1206 |
|
---|
1207 | # PC XT scancodes
|
---|
1208 | scancodes = {
|
---|
1209 | 'a': 0x1e,
|
---|
1210 | 'b': 0x30,
|
---|
1211 | 'c': 0x2e,
|
---|
1212 | 'd': 0x20,
|
---|
1213 | 'e': 0x12,
|
---|
1214 | 'f': 0x21,
|
---|
1215 | 'g': 0x22,
|
---|
1216 | 'h': 0x23,
|
---|
1217 | 'i': 0x17,
|
---|
1218 | 'j': 0x24,
|
---|
1219 | 'k': 0x25,
|
---|
1220 | 'l': 0x26,
|
---|
1221 | 'm': 0x32,
|
---|
1222 | 'n': 0x31,
|
---|
1223 | 'o': 0x18,
|
---|
1224 | 'p': 0x19,
|
---|
1225 | 'q': 0x10,
|
---|
1226 | 'r': 0x13,
|
---|
1227 | 's': 0x1f,
|
---|
1228 | 't': 0x14,
|
---|
1229 | 'u': 0x16,
|
---|
1230 | 'v': 0x2f,
|
---|
1231 | 'w': 0x11,
|
---|
1232 | 'x': 0x2d,
|
---|
1233 | 'y': 0x15,
|
---|
1234 | 'z': 0x2c,
|
---|
1235 | '0': 0x0b,
|
---|
1236 | '1': 0x02,
|
---|
1237 | '2': 0x03,
|
---|
1238 | '3': 0x04,
|
---|
1239 | '4': 0x05,
|
---|
1240 | '5': 0x06,
|
---|
1241 | '6': 0x07,
|
---|
1242 | '7': 0x08,
|
---|
1243 | '8': 0x09,
|
---|
1244 | '9': 0x0a,
|
---|
1245 | ' ': 0x39,
|
---|
1246 | '-': 0xc,
|
---|
1247 | '=': 0xd,
|
---|
1248 | '[': 0x1a,
|
---|
1249 | ']': 0x1b,
|
---|
1250 | ';': 0x27,
|
---|
1251 | '\'': 0x28,
|
---|
1252 | ',': 0x33,
|
---|
1253 | '.': 0x34,
|
---|
1254 | '/': 0x35,
|
---|
1255 | '\t': 0xf,
|
---|
1256 | '\n': 0x1c,
|
---|
1257 | '`': 0x29
|
---|
1258 | };
|
---|
1259 |
|
---|
1260 | extScancodes = {
|
---|
1261 | 'ESC' : [0x01],
|
---|
1262 | 'BKSP': [0xe],
|
---|
1263 | 'SPACE': [0x39],
|
---|
1264 | 'TAB': [0x0f],
|
---|
1265 | 'CAPS': [0x3a],
|
---|
1266 | 'ENTER': [0x1c],
|
---|
1267 | 'LSHIFT': [0x2a],
|
---|
1268 | 'RSHIFT': [0x36],
|
---|
1269 | 'INS': [0xe0, 0x52],
|
---|
1270 | 'DEL': [0xe0, 0x53],
|
---|
1271 | 'END': [0xe0, 0x4f],
|
---|
1272 | 'HOME': [0xe0, 0x47],
|
---|
1273 | 'PGUP': [0xe0, 0x49],
|
---|
1274 | 'PGDOWN': [0xe0, 0x51],
|
---|
1275 | 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
|
---|
1276 | 'RGUI': [0xe0, 0x5c],
|
---|
1277 | 'LCTR': [0x1d],
|
---|
1278 | 'RCTR': [0xe0, 0x1d],
|
---|
1279 | 'LALT': [0x38],
|
---|
1280 | 'RALT': [0xe0, 0x38],
|
---|
1281 | 'APPS': [0xe0, 0x5d],
|
---|
1282 | 'F1': [0x3b],
|
---|
1283 | 'F2': [0x3c],
|
---|
1284 | 'F3': [0x3d],
|
---|
1285 | 'F4': [0x3e],
|
---|
1286 | 'F5': [0x3f],
|
---|
1287 | 'F6': [0x40],
|
---|
1288 | 'F7': [0x41],
|
---|
1289 | 'F8': [0x42],
|
---|
1290 | 'F9': [0x43],
|
---|
1291 | 'F10': [0x44 ],
|
---|
1292 | 'F11': [0x57],
|
---|
1293 | 'F12': [0x58],
|
---|
1294 | 'UP': [0xe0, 0x48],
|
---|
1295 | 'LEFT': [0xe0, 0x4b],
|
---|
1296 | 'DOWN': [0xe0, 0x50],
|
---|
1297 | 'RIGHT': [0xe0, 0x4d],
|
---|
1298 | };
|
---|
1299 |
|
---|
1300 | def keyDown(ch):
|
---|
1301 | code = scancodes.get(ch, 0x0)
|
---|
1302 | if code != 0:
|
---|
1303 | return [code]
|
---|
1304 | extCode = extScancodes.get(ch, [])
|
---|
1305 | if len(extCode) == 0:
|
---|
1306 | print "bad ext",ch
|
---|
1307 | return extCode
|
---|
1308 |
|
---|
1309 | def keyUp(ch):
|
---|
1310 | codes = keyDown(ch)[:] # make a copy
|
---|
1311 | if len(codes) > 0:
|
---|
1312 | codes[len(codes)-1] += 0x80
|
---|
1313 | return codes
|
---|
1314 |
|
---|
1315 | def typeInGuest(console, text, delay):
|
---|
1316 | import time
|
---|
1317 | pressed = []
|
---|
1318 | group = False
|
---|
1319 | modGroupEnd = True
|
---|
1320 | i = 0
|
---|
1321 | while i < len(text):
|
---|
1322 | ch = text[i]
|
---|
1323 | i = i+1
|
---|
1324 | if ch == '{':
|
---|
1325 | # start group, all keys to be pressed at the same time
|
---|
1326 | group = True
|
---|
1327 | continue
|
---|
1328 | if ch == '}':
|
---|
1329 | # end group, release all keys
|
---|
1330 | for c in pressed:
|
---|
1331 | console.keyboard.putScancodes(keyUp(c))
|
---|
1332 | pressed = []
|
---|
1333 | group = False
|
---|
1334 | continue
|
---|
1335 | if ch == 'W':
|
---|
1336 | # just wait a bit
|
---|
1337 | time.sleep(0.3)
|
---|
1338 | continue
|
---|
1339 | if ch == '^' or ch == '|' or ch == '$' or ch == '_':
|
---|
1340 | if ch == '^':
|
---|
1341 | ch = 'LCTR'
|
---|
1342 | if ch == '|':
|
---|
1343 | ch = 'LSHIFT'
|
---|
1344 | if ch == '_':
|
---|
1345 | ch = 'LALT'
|
---|
1346 | if ch == '$':
|
---|
1347 | ch = 'LGUI'
|
---|
1348 | if not group:
|
---|
1349 | modGroupEnd = False
|
---|
1350 | else:
|
---|
1351 | if ch == '\\':
|
---|
1352 | if i < len(text):
|
---|
1353 | ch = text[i]
|
---|
1354 | i = i+1
|
---|
1355 | if ch == 'n':
|
---|
1356 | ch = '\n'
|
---|
1357 | elif ch == '&':
|
---|
1358 | combo = ""
|
---|
1359 | while i < len(text):
|
---|
1360 | ch = text[i]
|
---|
1361 | i = i+1
|
---|
1362 | if ch == ';':
|
---|
1363 | break
|
---|
1364 | combo += ch
|
---|
1365 | ch = combo
|
---|
1366 | modGroupEnd = True
|
---|
1367 | console.keyboard.putScancodes(keyDown(ch))
|
---|
1368 | pressed.insert(0, ch)
|
---|
1369 | if not group and modGroupEnd:
|
---|
1370 | for c in pressed:
|
---|
1371 | console.keyboard.putScancodes(keyUp(c))
|
---|
1372 | pressed = []
|
---|
1373 | modGroupEnd = True
|
---|
1374 | time.sleep(delay)
|
---|
1375 |
|
---|
1376 | def typeGuestCmd(ctx, args):
|
---|
1377 | import sys
|
---|
1378 |
|
---|
1379 | if len(args) < 3:
|
---|
1380 | print "usage: typeGuest <machine> <text> <charDelay>"
|
---|
1381 | return 0
|
---|
1382 | mach = ctx['machById'](args[1])
|
---|
1383 | if mach is None:
|
---|
1384 | return 0
|
---|
1385 |
|
---|
1386 | text = args[2]
|
---|
1387 |
|
---|
1388 | if len(args) > 3:
|
---|
1389 | delay = float(args[3])
|
---|
1390 | else:
|
---|
1391 | delay = 0.1
|
---|
1392 |
|
---|
1393 | args = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
|
---|
1394 | cmdExistingVm(ctx, mach, 'guestlambda', args)
|
---|
1395 |
|
---|
1396 | return 0
|
---|
1397 |
|
---|
1398 |
|
---|
1399 | aliases = {'s':'start',
|
---|
1400 | 'i':'info',
|
---|
1401 | 'l':'list',
|
---|
1402 | 'h':'help',
|
---|
1403 | 'a':'alias',
|
---|
1404 | 'q':'quit', 'exit':'quit',
|
---|
1405 | 'tg': 'typeGuest',
|
---|
1406 | 'v':'verbose'}
|
---|
1407 |
|
---|
1408 | commands = {'help':['Prints help information', helpCmd, 0],
|
---|
1409 | 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
|
---|
1410 | 'create':['Create virtual machine', createCmd, 0],
|
---|
1411 | 'remove':['Remove virtual machine', removeCmd, 0],
|
---|
1412 | 'pause':['Pause virtual machine', pauseCmd, 0],
|
---|
1413 | 'resume':['Resume virtual machine', resumeCmd, 0],
|
---|
1414 | 'save':['Save execution state of virtual machine', saveCmd, 0],
|
---|
1415 | 'stats':['Stats for virtual machine', statsCmd, 0],
|
---|
1416 | 'powerdown':['Power down virtual machine', powerdownCmd, 0],
|
---|
1417 | 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
|
---|
1418 | 'list':['Shows known virtual machines', listCmd, 0],
|
---|
1419 | 'info':['Shows info on machine', infoCmd, 0],
|
---|
1420 | 'alias':['Control aliases', aliasCmd, 0],
|
---|
1421 | 'verbose':['Toggle verbosity', verboseCmd, 0],
|
---|
1422 | 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
|
---|
1423 | 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
|
---|
1424 | 'quit':['Exits', quitCmd, 0],
|
---|
1425 | 'host':['Show host information', hostCmd, 0],
|
---|
1426 | 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
|
---|
1427 | 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
|
---|
1428 | 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
|
---|
1429 | 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
|
---|
1430 | 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
|
---|
1431 | 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
|
---|
1432 | 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
|
---|
1433 | 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
|
---|
1434 | 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
|
---|
1435 | 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
|
---|
1436 | 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
|
---|
1437 | 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
|
---|
1438 | 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
|
---|
1439 | 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
|
---|
1440 | 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
|
---|
1441 | 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
|
---|
1442 | 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
|
---|
1443 | 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
|
---|
1444 | 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
|
---|
1445 | 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
|
---|
1446 | }
|
---|
1447 |
|
---|
1448 | def runCommandArgs(ctx, args):
|
---|
1449 | c = args[0]
|
---|
1450 | if aliases.get(c, None) != None:
|
---|
1451 | c = aliases[c]
|
---|
1452 | ci = commands.get(c,None)
|
---|
1453 | if ci == None:
|
---|
1454 | print "Unknown command: '%s', type 'help' for list of known commands" %(c)
|
---|
1455 | return 0
|
---|
1456 | return ci[1](ctx, args)
|
---|
1457 |
|
---|
1458 |
|
---|
1459 | def runCommand(ctx, cmd):
|
---|
1460 | if len(cmd) == 0: return 0
|
---|
1461 | args = split_no_quotes(cmd)
|
---|
1462 | if len(args) == 0: return 0
|
---|
1463 | return runCommandArgs(ctx, args)
|
---|
1464 |
|
---|
1465 | #
|
---|
1466 | # To write your own custom commands to vboxshell, create
|
---|
1467 | # file ~/.VirtualBox/shellext.py with content like
|
---|
1468 | #
|
---|
1469 | # def runTestCmd(ctx, args):
|
---|
1470 | # print "Testy test", ctx['vb']
|
---|
1471 | # return 0
|
---|
1472 | #
|
---|
1473 | # commands = {
|
---|
1474 | # 'test': ['Test help', runTestCmd]
|
---|
1475 | # }
|
---|
1476 | # and issue reloadExt shell command.
|
---|
1477 | # This file also will be read automatically on startup or 'reloadExt'.
|
---|
1478 | #
|
---|
1479 | # Also one can put shell extensions into ~/.VirtualBox/shexts and
|
---|
1480 | # they will also be picked up, so this way one can exchange
|
---|
1481 | # shell extensions easily.
|
---|
1482 | def addExtsFromFile(ctx, cmds, file):
|
---|
1483 | if not os.path.isfile(file):
|
---|
1484 | return
|
---|
1485 | d = {}
|
---|
1486 | try:
|
---|
1487 | execfile(file, d, d)
|
---|
1488 | for (k,v) in d['commands'].items():
|
---|
1489 | if g_verbose:
|
---|
1490 | print "customize: adding \"%s\" - %s" %(k, v[0])
|
---|
1491 | cmds[k] = [v[0], v[1], file]
|
---|
1492 | except:
|
---|
1493 | print "Error loading user extensions from %s" %(file)
|
---|
1494 | traceback.print_exc()
|
---|
1495 |
|
---|
1496 |
|
---|
1497 | def checkUserExtensions(ctx, cmds, folder):
|
---|
1498 | folder = str(folder)
|
---|
1499 | name = os.path.join(folder, "shellext.py")
|
---|
1500 | addExtsFromFile(ctx, cmds, name)
|
---|
1501 | # also check 'exts' directory for all files
|
---|
1502 | shextdir = os.path.join(folder, "shexts")
|
---|
1503 | if not os.path.isdir(shextdir):
|
---|
1504 | return
|
---|
1505 | exts = os.listdir(shextdir)
|
---|
1506 | for e in exts:
|
---|
1507 | addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
|
---|
1508 |
|
---|
1509 | def getHomeFolder(ctx):
|
---|
1510 | if ctx['remote'] or ctx['vb'] is None:
|
---|
1511 | return os.path.join(os.path.expanduser("~"), ".VirtualBox")
|
---|
1512 | else:
|
---|
1513 | return ctx['vb'].homeFolder
|
---|
1514 |
|
---|
1515 | def interpret(ctx):
|
---|
1516 | if ctx['remote']:
|
---|
1517 | commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
|
---|
1518 | commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
|
---|
1519 |
|
---|
1520 | vbox = ctx['vb']
|
---|
1521 |
|
---|
1522 | if vbox is not None:
|
---|
1523 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1524 | ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
|
---|
1525 | else:
|
---|
1526 | ctx['perf'] = None
|
---|
1527 |
|
---|
1528 | home = getHomeFolder(ctx)
|
---|
1529 | checkUserExtensions(ctx, commands, home)
|
---|
1530 |
|
---|
1531 | autoCompletion(commands, ctx)
|
---|
1532 |
|
---|
1533 | # to allow to print actual host information, we collect info for
|
---|
1534 | # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
|
---|
1535 | if ctx['perf']:
|
---|
1536 | try:
|
---|
1537 | ctx['perf'].setup(['*'], [vbox.host], 10, 15)
|
---|
1538 | except:
|
---|
1539 | pass
|
---|
1540 |
|
---|
1541 | while True:
|
---|
1542 | try:
|
---|
1543 | cmd = raw_input("vbox> ")
|
---|
1544 | done = runCommand(ctx, cmd)
|
---|
1545 | if done != 0: break
|
---|
1546 | except KeyboardInterrupt:
|
---|
1547 | print '====== You can type quit or q to leave'
|
---|
1548 | break
|
---|
1549 | except EOFError:
|
---|
1550 | break;
|
---|
1551 | except Exception,e:
|
---|
1552 | print e
|
---|
1553 | if g_verbose:
|
---|
1554 | traceback.print_exc()
|
---|
1555 | ctx['global'].waitForEvents(0)
|
---|
1556 | try:
|
---|
1557 | # There is no need to disable metric collection. This is just an example.
|
---|
1558 | if ct['perf']:
|
---|
1559 | ctx['perf'].disable(['*'], [vbox.host])
|
---|
1560 | except:
|
---|
1561 | pass
|
---|
1562 |
|
---|
1563 | def runCommandCb(ctx, cmd, args):
|
---|
1564 | args.insert(0, cmd)
|
---|
1565 | return runCommandArgs(ctx, args)
|
---|
1566 |
|
---|
1567 | def runGuestCommandCb(ctx, id, guestLambda, args):
|
---|
1568 | mach = machById(ctx,id)
|
---|
1569 | if mach == None:
|
---|
1570 | return 0
|
---|
1571 | args.insert(0, guestLambda)
|
---|
1572 | cmdExistingVm(ctx, mach, 'guestlambda', args)
|
---|
1573 | return 0
|
---|
1574 |
|
---|
1575 | def main(argv):
|
---|
1576 | style = None
|
---|
1577 | autopath = False
|
---|
1578 | argv.pop(0)
|
---|
1579 | while len(argv) > 0:
|
---|
1580 | if argv[0] == "-w":
|
---|
1581 | style = "WEBSERVICE"
|
---|
1582 | if argv[0] == "-a":
|
---|
1583 | autopath = True
|
---|
1584 | argv.pop(0)
|
---|
1585 |
|
---|
1586 | if autopath:
|
---|
1587 | cwd = os.getcwd()
|
---|
1588 | vpp = os.environ.get("VBOX_PROGRAM_PATH")
|
---|
1589 | if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
|
---|
1590 | vpp = cwd
|
---|
1591 | print "Autodetected VBOX_PROGRAM_PATH as",vpp
|
---|
1592 | os.environ["VBOX_PROGRAM_PATH"] = cwd
|
---|
1593 | sys.path.append(os.path.join(vpp, "sdk", "installer"))
|
---|
1594 |
|
---|
1595 | from vboxapi import VirtualBoxManager
|
---|
1596 | g_virtualBoxManager = VirtualBoxManager(style, None)
|
---|
1597 | ctx = {'global':g_virtualBoxManager,
|
---|
1598 | 'mgr':g_virtualBoxManager.mgr,
|
---|
1599 | 'vb':g_virtualBoxManager.vbox,
|
---|
1600 | 'ifaces':g_virtualBoxManager.constants,
|
---|
1601 | 'remote':g_virtualBoxManager.remote,
|
---|
1602 | 'type':g_virtualBoxManager.type,
|
---|
1603 | 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
|
---|
1604 | 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
|
---|
1605 | 'machById': lambda id: machById(ctx,id),
|
---|
1606 | 'argsToMach': lambda args: argsToMach(ctx,args),
|
---|
1607 | 'progressBar': lambda p: progressBar(ctx,p),
|
---|
1608 | 'typeInGuest': typeInGuest,
|
---|
1609 | '_machlist':None
|
---|
1610 | }
|
---|
1611 | interpret(ctx)
|
---|
1612 | g_virtualBoxManager.deinit()
|
---|
1613 | del g_virtualBoxManager
|
---|
1614 |
|
---|
1615 | if __name__ == '__main__':
|
---|
1616 | main(sys.argv)
|
---|