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