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 onSnapshotDeleted(self, mach, id):
|
---|
129 | print "onSnapshotDeleted: %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, "", False)
|
---|
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 | cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
|
---|
248 | mach = vb.unregisterMachine(id)
|
---|
249 | if mach:
|
---|
250 | mach.deleteSettings()
|
---|
251 | # update cache
|
---|
252 | getMachines(ctx, True)
|
---|
253 |
|
---|
254 | def startVm(ctx,mach,type):
|
---|
255 | mgr = ctx['mgr']
|
---|
256 | vb = ctx['vb']
|
---|
257 | perf = ctx['perf']
|
---|
258 | session = mgr.getSessionObject(vb)
|
---|
259 | uuid = mach.id
|
---|
260 | progress = vb.openRemoteSession(session, uuid, type, "")
|
---|
261 | progressBar(ctx, progress, 100)
|
---|
262 | completed = progress.completed
|
---|
263 | rc = int(progress.resultCode)
|
---|
264 | print "Completed:", completed, "rc:",hex(rc&0xffffffff)
|
---|
265 | if rc == 0:
|
---|
266 | # we ignore exceptions to allow starting VM even if
|
---|
267 | # perf collector cannot be started
|
---|
268 | if perf:
|
---|
269 | try:
|
---|
270 | perf.setup(['*'], [mach], 10, 15)
|
---|
271 | except Exception,e:
|
---|
272 | print e
|
---|
273 | if g_verbose:
|
---|
274 | traceback.print_exc()
|
---|
275 | # if session not opened, close doesn't make sense
|
---|
276 | session.close()
|
---|
277 | else:
|
---|
278 | reportError(ctx,session,rc)
|
---|
279 |
|
---|
280 | def getMachines(ctx, invalidate = False):
|
---|
281 | if ctx['vb'] is not None:
|
---|
282 | if ctx['_machlist'] is None or invalidate:
|
---|
283 | ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
|
---|
284 | return ctx['_machlist']
|
---|
285 | else:
|
---|
286 | return []
|
---|
287 |
|
---|
288 | def asState(var):
|
---|
289 | if var:
|
---|
290 | return 'on'
|
---|
291 | else:
|
---|
292 | return 'off'
|
---|
293 |
|
---|
294 | def asFlag(var):
|
---|
295 | if var:
|
---|
296 | return 'yes'
|
---|
297 | else:
|
---|
298 | return 'no'
|
---|
299 |
|
---|
300 | def perfStats(ctx,mach):
|
---|
301 | if not ctx['perf']:
|
---|
302 | return
|
---|
303 | for metric in ctx['perf'].query(["*"], [mach]):
|
---|
304 | print metric['name'], metric['values_as_string']
|
---|
305 |
|
---|
306 | def guestExec(ctx, machine, console, cmds):
|
---|
307 | exec cmds
|
---|
308 |
|
---|
309 | def monitorGuest(ctx, machine, console, dur):
|
---|
310 | cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
|
---|
311 | console.registerCallback(cb)
|
---|
312 | if dur == -1:
|
---|
313 | # not infinity, but close enough
|
---|
314 | dur = 100000
|
---|
315 | try:
|
---|
316 | end = time.time() + dur
|
---|
317 | while time.time() < end:
|
---|
318 | ctx['global'].waitForEvents(500)
|
---|
319 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
320 | except:
|
---|
321 | pass
|
---|
322 | console.unregisterCallback(cb)
|
---|
323 |
|
---|
324 |
|
---|
325 | def monitorVBox(ctx, dur):
|
---|
326 | vbox = ctx['vb']
|
---|
327 | isMscom = (ctx['global'].type == 'MSCOM')
|
---|
328 | cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
|
---|
329 | vbox.registerCallback(cb)
|
---|
330 | if dur == -1:
|
---|
331 | # not infinity, but close enough
|
---|
332 | dur = 100000
|
---|
333 | try:
|
---|
334 | end = time.time() + dur
|
---|
335 | while time.time() < end:
|
---|
336 | ctx['global'].waitForEvents(500)
|
---|
337 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
338 | except:
|
---|
339 | pass
|
---|
340 | vbox.unregisterCallback(cb)
|
---|
341 |
|
---|
342 |
|
---|
343 | def takeScreenshot(ctx,console,args):
|
---|
344 | from PIL import Image
|
---|
345 | display = console.display
|
---|
346 | if len(args) > 0:
|
---|
347 | f = args[0]
|
---|
348 | else:
|
---|
349 | f = "/tmp/screenshot.png"
|
---|
350 | if len(args) > 3:
|
---|
351 | screen = int(args[3])
|
---|
352 | else:
|
---|
353 | screen = 0
|
---|
354 | (fb,xorig,yorig) = display.getFramebuffer(screen)
|
---|
355 | if len(args) > 1:
|
---|
356 | w = int(args[1])
|
---|
357 | else:
|
---|
358 | w = fb.width
|
---|
359 | if len(args) > 2:
|
---|
360 | h = int(args[2])
|
---|
361 | else:
|
---|
362 | h = fb.height
|
---|
363 |
|
---|
364 | print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
|
---|
365 | data = display.takeScreenShotToArray(screen, w,h)
|
---|
366 | size = (w,h)
|
---|
367 | mode = "RGBA"
|
---|
368 | im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
|
---|
369 | im.save(f, "PNG")
|
---|
370 |
|
---|
371 |
|
---|
372 | def teleport(ctx,session,console,args):
|
---|
373 | if args[0].find(":") == -1:
|
---|
374 | print "Use host:port format for teleport target"
|
---|
375 | return
|
---|
376 | (host,port) = args[0].split(":")
|
---|
377 | if len(args) > 1:
|
---|
378 | passwd = args[1]
|
---|
379 | else:
|
---|
380 | passwd = ""
|
---|
381 |
|
---|
382 | if len(args) > 2:
|
---|
383 | maxDowntime = int(args[2])
|
---|
384 | else:
|
---|
385 | maxDowntime = 250
|
---|
386 |
|
---|
387 | port = int(port)
|
---|
388 | print "Teleporting to %s:%d..." %(host,port)
|
---|
389 | progress = console.teleport(host, port, passwd, maxDowntime)
|
---|
390 | progressBar(ctx, progress, 100)
|
---|
391 | completed = progress.completed
|
---|
392 | rc = int(progress.resultCode)
|
---|
393 | if rc == 0:
|
---|
394 | print "Success!"
|
---|
395 | else:
|
---|
396 | reportError(ctx,session,rc)
|
---|
397 |
|
---|
398 |
|
---|
399 | def guestStats(ctx,console,args):
|
---|
400 | guest = console.guest
|
---|
401 | # we need to set up guest statistics
|
---|
402 | if len(args) > 0 :
|
---|
403 | update = args[0]
|
---|
404 | else:
|
---|
405 | update = 1
|
---|
406 | if guest.statisticsUpdateInterval != update:
|
---|
407 | guest.statisticsUpdateInterval = update
|
---|
408 | try:
|
---|
409 | time.sleep(float(update)+0.1)
|
---|
410 | except:
|
---|
411 | # to allow sleep interruption
|
---|
412 | pass
|
---|
413 | all_stats = ctx['ifaces'].all_values('GuestStatisticType')
|
---|
414 | cpu = 0
|
---|
415 | for s in all_stats.keys():
|
---|
416 | try:
|
---|
417 | val = guest.getStatistic( cpu, all_stats[s])
|
---|
418 | print "%s: %d" %(s, val)
|
---|
419 | except:
|
---|
420 | # likely not implemented
|
---|
421 | pass
|
---|
422 |
|
---|
423 | def plugCpu(ctx,machine,session,args):
|
---|
424 | cpu = int(args[0])
|
---|
425 | print "Adding CPU %d..." %(cpu)
|
---|
426 | machine.hotPlugCPU(cpu)
|
---|
427 |
|
---|
428 | def unplugCpu(ctx,machine,session,args):
|
---|
429 | cpu = int(args[0])
|
---|
430 | print "Removing CPU %d..." %(cpu)
|
---|
431 | machine.hotUnplugCPU(cpu)
|
---|
432 |
|
---|
433 | def mountIso(ctx,machine,session,args):
|
---|
434 | machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
|
---|
435 | machine.saveSettings()
|
---|
436 |
|
---|
437 | def ginfo(ctx,console, args):
|
---|
438 | guest = console.guest
|
---|
439 | if guest.additionsActive:
|
---|
440 | vers = int(guest.additionsVersion)
|
---|
441 | print "Additions active, version %d.%d" %(vers >> 16, vers & 0xffff)
|
---|
442 | print "Support seamless: %s" %(asFlag(guest.supportsSeamless))
|
---|
443 | print "Support graphics: %s" %(asFlag(guest.supportsGraphics))
|
---|
444 | print "Baloon size: %d" %(guest.memoryBalloonSize)
|
---|
445 | print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
|
---|
446 | else:
|
---|
447 | print "No additions"
|
---|
448 |
|
---|
449 | def cmdExistingVm(ctx,mach,cmd,args):
|
---|
450 | mgr=ctx['mgr']
|
---|
451 | vb=ctx['vb']
|
---|
452 | session = mgr.getSessionObject(vb)
|
---|
453 | uuid = mach.id
|
---|
454 | try:
|
---|
455 | progress = vb.openExistingSession(session, uuid)
|
---|
456 | except Exception,e:
|
---|
457 | print "Session to '%s' not open: %s" %(mach.name,e)
|
---|
458 | if g_verbose:
|
---|
459 | traceback.print_exc()
|
---|
460 | return
|
---|
461 | if str(session.state) != str(ctx['ifaces'].SessionState_Open):
|
---|
462 | print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
|
---|
463 | return
|
---|
464 | # this could be an example how to handle local only (i.e. unavailable
|
---|
465 | # in Webservices) functionality
|
---|
466 | if ctx['remote'] and cmd == 'some_local_only_command':
|
---|
467 | print 'Trying to use local only functionality, ignored'
|
---|
468 | return
|
---|
469 | console=session.console
|
---|
470 | ops={'pause': lambda: console.pause(),
|
---|
471 | 'resume': lambda: console.resume(),
|
---|
472 | 'powerdown': lambda: console.powerDown(),
|
---|
473 | 'powerbutton': lambda: console.powerButton(),
|
---|
474 | 'stats': lambda: perfStats(ctx, mach),
|
---|
475 | 'guest': lambda: guestExec(ctx, mach, console, args),
|
---|
476 | 'ginfo': lambda: ginfo(ctx, console, args),
|
---|
477 | 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
|
---|
478 | 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
|
---|
479 | 'save': lambda: progressBar(ctx,console.saveState()),
|
---|
480 | 'screenshot': lambda: takeScreenshot(ctx,console,args),
|
---|
481 | 'teleport': lambda: teleport(ctx,session,console,args),
|
---|
482 | 'gueststats': lambda: guestStats(ctx, console, args),
|
---|
483 | 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
|
---|
484 | 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
|
---|
485 | 'mountiso': lambda: mountIso(ctx, session.machine, session, args)
|
---|
486 | }
|
---|
487 | try:
|
---|
488 | ops[cmd]()
|
---|
489 | except Exception, e:
|
---|
490 | print 'failed: ',e
|
---|
491 | if g_verbose:
|
---|
492 | traceback.print_exc()
|
---|
493 |
|
---|
494 | session.close()
|
---|
495 |
|
---|
496 |
|
---|
497 | def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
|
---|
498 | session = ctx['global'].openMachineSession(mach.id)
|
---|
499 | mach = session.machine
|
---|
500 | try:
|
---|
501 | cmd(ctx, mach, args)
|
---|
502 | except Exception, e:
|
---|
503 | print 'failed: ',e
|
---|
504 | if g_verbose:
|
---|
505 | traceback.print_exc()
|
---|
506 | if save:
|
---|
507 | mach.saveSettings()
|
---|
508 | session.close()
|
---|
509 |
|
---|
510 | def machById(ctx,id):
|
---|
511 | mach = None
|
---|
512 | for m in getMachines(ctx):
|
---|
513 | if m.name == id:
|
---|
514 | mach = m
|
---|
515 | break
|
---|
516 | mid = str(m.id)
|
---|
517 | if mid[0] == '{':
|
---|
518 | mid = mid[1:-1]
|
---|
519 | if mid == id:
|
---|
520 | mach = m
|
---|
521 | break
|
---|
522 | return mach
|
---|
523 |
|
---|
524 | def argsToMach(ctx,args):
|
---|
525 | if len(args) < 2:
|
---|
526 | print "usage: %s [vmname|uuid]" %(args[0])
|
---|
527 | return None
|
---|
528 | id = args[1]
|
---|
529 | m = machById(ctx, id)
|
---|
530 | if m == None:
|
---|
531 | print "Machine '%s' is unknown, use list command to find available machines" %(id)
|
---|
532 | return m
|
---|
533 |
|
---|
534 | def helpSingleCmd(cmd,h,sp):
|
---|
535 | if sp != 0:
|
---|
536 | spec = " [ext from "+sp+"]"
|
---|
537 | else:
|
---|
538 | spec = ""
|
---|
539 | print " %s: %s%s" %(cmd,h,spec)
|
---|
540 |
|
---|
541 | def helpCmd(ctx, args):
|
---|
542 | if len(args) == 1:
|
---|
543 | print "Help page:"
|
---|
544 | names = commands.keys()
|
---|
545 | names.sort()
|
---|
546 | for i in names:
|
---|
547 | helpSingleCmd(i, commands[i][0], commands[i][2])
|
---|
548 | else:
|
---|
549 | cmd = args[1]
|
---|
550 | c = commands.get(cmd)
|
---|
551 | if c == None:
|
---|
552 | print "Command '%s' not known" %(cmd)
|
---|
553 | else:
|
---|
554 | helpSingleCmd(cmd, c[0], c[2])
|
---|
555 | return 0
|
---|
556 |
|
---|
557 | def asEnumElem(ctx,enum,elem):
|
---|
558 | all = ctx['ifaces'].all_values(enum)
|
---|
559 | for e in all.keys():
|
---|
560 | if str(elem) == str(all[e]):
|
---|
561 | return e
|
---|
562 | return "<unknown>"
|
---|
563 |
|
---|
564 | def enumFromString(ctx,enum,str):
|
---|
565 | all = ctx['ifaces'].all_values(enum)
|
---|
566 | return all.get(str, None)
|
---|
567 |
|
---|
568 | def listCmd(ctx, args):
|
---|
569 | for m in getMachines(ctx, True):
|
---|
570 | if m.teleporterEnabled:
|
---|
571 | tele = "[T] "
|
---|
572 | else:
|
---|
573 | tele = " "
|
---|
574 | print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,asEnumElem(ctx,"SessionState", m.sessionState))
|
---|
575 | return 0
|
---|
576 |
|
---|
577 | def infoCmd(ctx,args):
|
---|
578 | if (len(args) < 2):
|
---|
579 | print "usage: info [vmname|uuid]"
|
---|
580 | return 0
|
---|
581 | mach = argsToMach(ctx,args)
|
---|
582 | if mach == None:
|
---|
583 | return 0
|
---|
584 | os = ctx['vb'].getGuestOSType(mach.OSTypeId)
|
---|
585 | print " One can use setvar <mach> <var> <value> to change variable, using name in []."
|
---|
586 | print " Name [name]: %s" %(mach.name)
|
---|
587 | print " Description [description]: %s" %(mach.description)
|
---|
588 | print " ID [n/a]: %s" %(mach.id)
|
---|
589 | print " OS Type [via OSTypeId]: %s" %(os.description)
|
---|
590 | print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
|
---|
591 | print
|
---|
592 | print " CPUs [CPUCount]: %d" %(mach.CPUCount)
|
---|
593 | print " RAM [memorySize]: %dM" %(mach.memorySize)
|
---|
594 | print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
|
---|
595 | print " Monitors [monitorCount]: %d" %(mach.monitorCount)
|
---|
596 | print
|
---|
597 | print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
|
---|
598 | print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
|
---|
599 | print
|
---|
600 | if mach.teleporterEnabled:
|
---|
601 | print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
|
---|
602 | print
|
---|
603 | bios = mach.BIOSSettings
|
---|
604 | print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
|
---|
605 | print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
|
---|
606 | hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
|
---|
607 | print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
|
---|
608 | hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
|
---|
609 | print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
|
---|
610 | hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
|
---|
611 | print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
|
---|
612 |
|
---|
613 | print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
|
---|
614 | print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
|
---|
615 |
|
---|
616 | print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
|
---|
617 | if mach.audioAdapter.enabled:
|
---|
618 | print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
|
---|
619 | print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
|
---|
620 |
|
---|
621 | print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
|
---|
622 | print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
|
---|
623 | print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
|
---|
624 | print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
|
---|
625 |
|
---|
626 | controllers = ctx['global'].getArray(mach, 'storageControllers')
|
---|
627 | if controllers:
|
---|
628 | print
|
---|
629 | print " Controllers:"
|
---|
630 | for controller in controllers:
|
---|
631 | print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
|
---|
632 |
|
---|
633 | attaches = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
634 | if attaches:
|
---|
635 | print
|
---|
636 | print " Mediums:"
|
---|
637 | for a in attaches:
|
---|
638 | print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
|
---|
639 | m = a.medium
|
---|
640 | if a.type == ctx['global'].constants.DeviceType_HardDisk:
|
---|
641 | print " HDD:"
|
---|
642 | print " Id: %s" %(m.id)
|
---|
643 | print " Location: %s" %(m.location)
|
---|
644 | print " Name: %s" %(m.name)
|
---|
645 | print " Format: %s" %(m.format)
|
---|
646 |
|
---|
647 | if a.type == ctx['global'].constants.DeviceType_DVD:
|
---|
648 | print " DVD:"
|
---|
649 | if m:
|
---|
650 | print " Id: %s" %(m.id)
|
---|
651 | print " Name: %s" %(m.name)
|
---|
652 | if m.hostDrive:
|
---|
653 | print " Host DVD %s" %(m.location)
|
---|
654 | if a.passthrough:
|
---|
655 | print " [passthrough mode]"
|
---|
656 | else:
|
---|
657 | print " Virtual image at %s" %(m.location)
|
---|
658 | print " Size: %s" %(m.size)
|
---|
659 |
|
---|
660 | if a.type == ctx['global'].constants.DeviceType_Floppy:
|
---|
661 | print " Floppy:"
|
---|
662 | if m:
|
---|
663 | print " Id: %s" %(m.id)
|
---|
664 | print " Name: %s" %(m.name)
|
---|
665 | if m.hostDrive:
|
---|
666 | print " Host floppy %s" %(m.location)
|
---|
667 | else:
|
---|
668 | print " Virtual image at %s" %(m.location)
|
---|
669 | print " Size: %s" %(m.size)
|
---|
670 |
|
---|
671 | return 0
|
---|
672 |
|
---|
673 | def startCmd(ctx, args):
|
---|
674 | mach = argsToMach(ctx,args)
|
---|
675 | if mach == None:
|
---|
676 | return 0
|
---|
677 | if len(args) > 2:
|
---|
678 | type = args[2]
|
---|
679 | else:
|
---|
680 | type = "gui"
|
---|
681 | startVm(ctx, mach, type)
|
---|
682 | return 0
|
---|
683 |
|
---|
684 | def createVmCmd(ctx, args):
|
---|
685 | if (len(args) < 3 or len(args) > 4):
|
---|
686 | print "usage: createvm name ostype <basefolder>"
|
---|
687 | return 0
|
---|
688 | name = args[1]
|
---|
689 | oskind = args[2]
|
---|
690 | if len(args) == 4:
|
---|
691 | base = args[3]
|
---|
692 | else:
|
---|
693 | base = ''
|
---|
694 | try:
|
---|
695 | ctx['vb'].getGuestOSType(oskind)
|
---|
696 | except Exception, e:
|
---|
697 | print 'Unknown OS type:',oskind
|
---|
698 | return 0
|
---|
699 | createVm(ctx, name, oskind, base)
|
---|
700 | return 0
|
---|
701 |
|
---|
702 | def ginfoCmd(ctx,args):
|
---|
703 | if (len(args) < 2):
|
---|
704 | print "usage: ginfo [vmname|uuid]"
|
---|
705 | return 0
|
---|
706 | mach = argsToMach(ctx,args)
|
---|
707 | if mach == None:
|
---|
708 | return 0
|
---|
709 | cmdExistingVm(ctx, mach, 'ginfo', '')
|
---|
710 | return 0
|
---|
711 |
|
---|
712 | def execInGuest(ctx,console,args):
|
---|
713 | if len(args) < 1:
|
---|
714 | print "exec in guest needs at least program name"
|
---|
715 | return
|
---|
716 | user = ""
|
---|
717 | passwd = ""
|
---|
718 | tmo = 0
|
---|
719 | print "executing %s with %s" %(args[0], args[1:])
|
---|
720 | (progress, pid) = console.guest.executeProcess(args[0], 0, args[1:], [], "", "", "", user, passwd, tmo)
|
---|
721 | print "executed with pid %d" %(pid)
|
---|
722 |
|
---|
723 | def gexecCmd(ctx,args):
|
---|
724 | if (len(args) < 2):
|
---|
725 | print "usage: gexec [vmname|uuid] command args"
|
---|
726 | return 0
|
---|
727 | mach = argsToMach(ctx,args)
|
---|
728 | if mach == None:
|
---|
729 | return 0
|
---|
730 | gargs = args[2:]
|
---|
731 | gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args))
|
---|
732 | cmdExistingVm(ctx, mach, 'guestlambda', gargs)
|
---|
733 | return 0
|
---|
734 |
|
---|
735 | def removeVmCmd(ctx, args):
|
---|
736 | mach = argsToMach(ctx,args)
|
---|
737 | if mach == None:
|
---|
738 | return 0
|
---|
739 | removeVm(ctx, mach)
|
---|
740 | return 0
|
---|
741 |
|
---|
742 | def pauseCmd(ctx, args):
|
---|
743 | mach = argsToMach(ctx,args)
|
---|
744 | if mach == None:
|
---|
745 | return 0
|
---|
746 | cmdExistingVm(ctx, mach, 'pause', '')
|
---|
747 | return 0
|
---|
748 |
|
---|
749 | def powerdownCmd(ctx, args):
|
---|
750 | mach = argsToMach(ctx,args)
|
---|
751 | if mach == None:
|
---|
752 | return 0
|
---|
753 | cmdExistingVm(ctx, mach, 'powerdown', '')
|
---|
754 | return 0
|
---|
755 |
|
---|
756 | def powerbuttonCmd(ctx, args):
|
---|
757 | mach = argsToMach(ctx,args)
|
---|
758 | if mach == None:
|
---|
759 | return 0
|
---|
760 | cmdExistingVm(ctx, mach, 'powerbutton', '')
|
---|
761 | return 0
|
---|
762 |
|
---|
763 | def resumeCmd(ctx, args):
|
---|
764 | mach = argsToMach(ctx,args)
|
---|
765 | if mach == None:
|
---|
766 | return 0
|
---|
767 | cmdExistingVm(ctx, mach, 'resume', '')
|
---|
768 | return 0
|
---|
769 |
|
---|
770 | def saveCmd(ctx, args):
|
---|
771 | mach = argsToMach(ctx,args)
|
---|
772 | if mach == None:
|
---|
773 | return 0
|
---|
774 | cmdExistingVm(ctx, mach, 'save', '')
|
---|
775 | return 0
|
---|
776 |
|
---|
777 | def statsCmd(ctx, args):
|
---|
778 | mach = argsToMach(ctx,args)
|
---|
779 | if mach == None:
|
---|
780 | return 0
|
---|
781 | cmdExistingVm(ctx, mach, 'stats', '')
|
---|
782 | return 0
|
---|
783 |
|
---|
784 | def guestCmd(ctx, args):
|
---|
785 | if (len(args) < 3):
|
---|
786 | print "usage: guest name commands"
|
---|
787 | return 0
|
---|
788 | mach = argsToMach(ctx,args)
|
---|
789 | if mach == None:
|
---|
790 | return 0
|
---|
791 | cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
|
---|
792 | return 0
|
---|
793 |
|
---|
794 | def screenshotCmd(ctx, args):
|
---|
795 | if (len(args) < 2):
|
---|
796 | print "usage: screenshot vm <file> <width> <height> <monitor>"
|
---|
797 | return 0
|
---|
798 | mach = argsToMach(ctx,args)
|
---|
799 | if mach == None:
|
---|
800 | return 0
|
---|
801 | cmdExistingVm(ctx, mach, 'screenshot', args[2:])
|
---|
802 | return 0
|
---|
803 |
|
---|
804 | def teleportCmd(ctx, args):
|
---|
805 | if (len(args) < 3):
|
---|
806 | print "usage: teleport name host:port <password>"
|
---|
807 | return 0
|
---|
808 | mach = argsToMach(ctx,args)
|
---|
809 | if mach == None:
|
---|
810 | return 0
|
---|
811 | cmdExistingVm(ctx, mach, 'teleport', args[2:])
|
---|
812 | return 0
|
---|
813 |
|
---|
814 | def portalsettings(ctx,mach,args):
|
---|
815 | enabled = args[0]
|
---|
816 | mach.teleporterEnabled = enabled
|
---|
817 | if enabled:
|
---|
818 | port = args[1]
|
---|
819 | passwd = args[2]
|
---|
820 | mach.teleporterPort = port
|
---|
821 | mach.teleporterPassword = passwd
|
---|
822 |
|
---|
823 | def openportalCmd(ctx, args):
|
---|
824 | if (len(args) < 3):
|
---|
825 | print "usage: openportal name port <password>"
|
---|
826 | return 0
|
---|
827 | mach = argsToMach(ctx,args)
|
---|
828 | if mach == None:
|
---|
829 | return 0
|
---|
830 | port = int(args[2])
|
---|
831 | if (len(args) > 3):
|
---|
832 | passwd = args[3]
|
---|
833 | else:
|
---|
834 | passwd = ""
|
---|
835 | if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
|
---|
836 | cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
|
---|
837 | startVm(ctx, mach, "gui")
|
---|
838 | return 0
|
---|
839 |
|
---|
840 | def closeportalCmd(ctx, args):
|
---|
841 | if (len(args) < 2):
|
---|
842 | print "usage: closeportal name"
|
---|
843 | return 0
|
---|
844 | mach = argsToMach(ctx,args)
|
---|
845 | if mach == None:
|
---|
846 | return 0
|
---|
847 | if mach.teleporterEnabled:
|
---|
848 | cmdClosedVm(ctx, mach, portalsettings, [False])
|
---|
849 | return 0
|
---|
850 |
|
---|
851 | def gueststatsCmd(ctx, args):
|
---|
852 | if (len(args) < 2):
|
---|
853 | print "usage: gueststats name <check interval>"
|
---|
854 | return 0
|
---|
855 | mach = argsToMach(ctx,args)
|
---|
856 | if mach == None:
|
---|
857 | return 0
|
---|
858 | cmdExistingVm(ctx, mach, 'gueststats', args[2:])
|
---|
859 | return 0
|
---|
860 |
|
---|
861 | def plugcpu(ctx,mach,args):
|
---|
862 | plug = args[0]
|
---|
863 | cpu = args[1]
|
---|
864 | if plug:
|
---|
865 | print "Adding CPU %d..." %(cpu)
|
---|
866 | mach.hotPlugCPU(cpu)
|
---|
867 | else:
|
---|
868 | print "Removing CPU %d..." %(cpu)
|
---|
869 | mach.hotUnplugCPU(cpu)
|
---|
870 |
|
---|
871 | def plugcpuCmd(ctx, args):
|
---|
872 | if (len(args) < 2):
|
---|
873 | print "usage: plugcpu name cpuid"
|
---|
874 | return 0
|
---|
875 | mach = argsToMach(ctx,args)
|
---|
876 | if mach == None:
|
---|
877 | return 0
|
---|
878 | if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
|
---|
879 | if mach.CPUHotPlugEnabled:
|
---|
880 | cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
|
---|
881 | else:
|
---|
882 | cmdExistingVm(ctx, mach, 'plugcpu', args[2])
|
---|
883 | return 0
|
---|
884 |
|
---|
885 | def unplugcpuCmd(ctx, args):
|
---|
886 | if (len(args) < 2):
|
---|
887 | print "usage: unplugcpu name cpuid"
|
---|
888 | return 0
|
---|
889 | mach = argsToMach(ctx,args)
|
---|
890 | if mach == None:
|
---|
891 | return 0
|
---|
892 | if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
|
---|
893 | if mach.CPUHotPlugEnabled:
|
---|
894 | cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
|
---|
895 | else:
|
---|
896 | cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
|
---|
897 | return 0
|
---|
898 |
|
---|
899 | def setvar(ctx,mach,args):
|
---|
900 | expr = 'mach.'+args[0]+' = '+args[1]
|
---|
901 | print "Executing",expr
|
---|
902 | exec expr
|
---|
903 |
|
---|
904 | def setvarCmd(ctx, args):
|
---|
905 | if (len(args) < 4):
|
---|
906 | print "usage: setvar [vmname|uuid] expr value"
|
---|
907 | return 0
|
---|
908 | mach = argsToMach(ctx,args)
|
---|
909 | if mach == None:
|
---|
910 | return 0
|
---|
911 | cmdClosedVm(ctx, mach, setvar, args[2:])
|
---|
912 | return 0
|
---|
913 |
|
---|
914 | def setvmextra(ctx,mach,args):
|
---|
915 | key = args[0]
|
---|
916 | value = args[1]
|
---|
917 | print "%s: setting %s to %s" %(mach.name, key, value)
|
---|
918 | mach.setExtraData(key, value)
|
---|
919 |
|
---|
920 | def setExtraDataCmd(ctx, args):
|
---|
921 | if (len(args) < 3):
|
---|
922 | print "usage: setextra [vmname|uuid|global] key <value>"
|
---|
923 | return 0
|
---|
924 | key = args[2]
|
---|
925 | if len(args) == 4:
|
---|
926 | value = args[3]
|
---|
927 | else:
|
---|
928 | value = None
|
---|
929 | if args[1] == 'global':
|
---|
930 | ctx['vb'].setExtraData(key, value)
|
---|
931 | return 0
|
---|
932 |
|
---|
933 | mach = argsToMach(ctx,args)
|
---|
934 | if mach == None:
|
---|
935 | return 0
|
---|
936 | cmdClosedVm(ctx, mach, setvmextra, [key, value])
|
---|
937 | return 0
|
---|
938 |
|
---|
939 | def printExtraKey(obj, key, value):
|
---|
940 | print "%s: '%s' = '%s'" %(obj, key, value)
|
---|
941 |
|
---|
942 | def getExtraDataCmd(ctx, args):
|
---|
943 | if (len(args) < 2):
|
---|
944 | print "usage: getextra [vmname|uuid|global] <key>"
|
---|
945 | return 0
|
---|
946 | if len(args) == 3:
|
---|
947 | key = args[2]
|
---|
948 | else:
|
---|
949 | key = None
|
---|
950 |
|
---|
951 | if args[1] == 'global':
|
---|
952 | obj = ctx['vb']
|
---|
953 | else:
|
---|
954 | obj = argsToMach(ctx,args)
|
---|
955 | if obj == None:
|
---|
956 | return 0
|
---|
957 |
|
---|
958 | if key == None:
|
---|
959 | keys = obj.getExtraDataKeys()
|
---|
960 | else:
|
---|
961 | keys = [ key ]
|
---|
962 | for k in keys:
|
---|
963 | printExtraKey(args[1], k, obj.getExtraData(k))
|
---|
964 |
|
---|
965 | return 0
|
---|
966 |
|
---|
967 | def quitCmd(ctx, args):
|
---|
968 | return 1
|
---|
969 |
|
---|
970 | def aliasCmd(ctx, args):
|
---|
971 | if (len(args) == 3):
|
---|
972 | aliases[args[1]] = args[2]
|
---|
973 | return 0
|
---|
974 |
|
---|
975 | for (k,v) in aliases.items():
|
---|
976 | print "'%s' is an alias for '%s'" %(k,v)
|
---|
977 | return 0
|
---|
978 |
|
---|
979 | def verboseCmd(ctx, args):
|
---|
980 | global g_verbose
|
---|
981 | g_verbose = not g_verbose
|
---|
982 | return 0
|
---|
983 |
|
---|
984 | def getUSBStateString(state):
|
---|
985 | if state == 0:
|
---|
986 | return "NotSupported"
|
---|
987 | elif state == 1:
|
---|
988 | return "Unavailable"
|
---|
989 | elif state == 2:
|
---|
990 | return "Busy"
|
---|
991 | elif state == 3:
|
---|
992 | return "Available"
|
---|
993 | elif state == 4:
|
---|
994 | return "Held"
|
---|
995 | elif state == 5:
|
---|
996 | return "Captured"
|
---|
997 | else:
|
---|
998 | return "Unknown"
|
---|
999 |
|
---|
1000 | def hostCmd(ctx, args):
|
---|
1001 | host = ctx['vb'].host
|
---|
1002 | cnt = host.processorCount
|
---|
1003 | print "Processor count:",cnt
|
---|
1004 | for i in range(0,cnt):
|
---|
1005 | print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
|
---|
1006 |
|
---|
1007 | print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
|
---|
1008 | print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
|
---|
1009 | if host.Acceleration3DAvailable:
|
---|
1010 | print "3D acceleration available"
|
---|
1011 | else:
|
---|
1012 | print "3D acceleration NOT available"
|
---|
1013 |
|
---|
1014 | print "Network interfaces:"
|
---|
1015 | for ni in ctx['global'].getArray(host, 'networkInterfaces'):
|
---|
1016 | print " %s (%s)" %(ni.name, ni.IPAddress)
|
---|
1017 |
|
---|
1018 | print "DVD drives:"
|
---|
1019 | for dd in ctx['global'].getArray(host, 'DVDDrives'):
|
---|
1020 | print " %s - %s" %(dd.name, dd.description)
|
---|
1021 |
|
---|
1022 | print "USB devices:"
|
---|
1023 | for ud in ctx['global'].getArray(host, 'USBDevices'):
|
---|
1024 | print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
|
---|
1025 |
|
---|
1026 | if ctx['perf']:
|
---|
1027 | for metric in ctx['perf'].query(["*"], [host]):
|
---|
1028 | print metric['name'], metric['values_as_string']
|
---|
1029 |
|
---|
1030 | return 0
|
---|
1031 |
|
---|
1032 | def monitorGuestCmd(ctx, args):
|
---|
1033 | if (len(args) < 2):
|
---|
1034 | print "usage: monitorGuest name (duration)"
|
---|
1035 | return 0
|
---|
1036 | mach = argsToMach(ctx,args)
|
---|
1037 | if mach == None:
|
---|
1038 | return 0
|
---|
1039 | dur = 5
|
---|
1040 | if len(args) > 2:
|
---|
1041 | dur = float(args[2])
|
---|
1042 | cmdExistingVm(ctx, mach, 'monitorGuest', dur)
|
---|
1043 | return 0
|
---|
1044 |
|
---|
1045 | def monitorVBoxCmd(ctx, args):
|
---|
1046 | if (len(args) > 2):
|
---|
1047 | print "usage: monitorVBox (duration)"
|
---|
1048 | return 0
|
---|
1049 | dur = 5
|
---|
1050 | if len(args) > 1:
|
---|
1051 | dur = float(args[1])
|
---|
1052 | monitorVBox(ctx, dur)
|
---|
1053 | return 0
|
---|
1054 |
|
---|
1055 | def getAdapterType(ctx, type):
|
---|
1056 | if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
|
---|
1057 | type == ctx['global'].constants.NetworkAdapterType_Am79C973):
|
---|
1058 | return "pcnet"
|
---|
1059 | elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
|
---|
1060 | type == ctx['global'].constants.NetworkAdapterType_I82545EM or
|
---|
1061 | type == ctx['global'].constants.NetworkAdapterType_I82543GC):
|
---|
1062 | return "e1000"
|
---|
1063 | elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
|
---|
1064 | return "virtio"
|
---|
1065 | elif (type == ctx['global'].constants.NetworkAdapterType_Null):
|
---|
1066 | return None
|
---|
1067 | else:
|
---|
1068 | raise Exception("Unknown adapter type: "+type)
|
---|
1069 |
|
---|
1070 |
|
---|
1071 | def portForwardCmd(ctx, args):
|
---|
1072 | if (len(args) != 5):
|
---|
1073 | print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
|
---|
1074 | return 0
|
---|
1075 | mach = argsToMach(ctx,args)
|
---|
1076 | if mach == None:
|
---|
1077 | return 0
|
---|
1078 | adapterNum = int(args[2])
|
---|
1079 | hostPort = int(args[3])
|
---|
1080 | guestPort = int(args[4])
|
---|
1081 | proto = "TCP"
|
---|
1082 | session = ctx['global'].openMachineSession(mach.id)
|
---|
1083 | mach = session.machine
|
---|
1084 |
|
---|
1085 | adapter = mach.getNetworkAdapter(adapterNum)
|
---|
1086 | adapterType = getAdapterType(ctx, adapter.adapterType)
|
---|
1087 |
|
---|
1088 | profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
|
---|
1089 | config = "VBoxInternal/Devices/" + adapterType + "/"
|
---|
1090 | config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
|
---|
1091 |
|
---|
1092 | mach.setExtraData(config + "/Protocol", proto)
|
---|
1093 | mach.setExtraData(config + "/HostPort", str(hostPort))
|
---|
1094 | mach.setExtraData(config + "/GuestPort", str(guestPort))
|
---|
1095 |
|
---|
1096 | mach.saveSettings()
|
---|
1097 | session.close()
|
---|
1098 |
|
---|
1099 | return 0
|
---|
1100 |
|
---|
1101 |
|
---|
1102 | def showLogCmd(ctx, args):
|
---|
1103 | if (len(args) < 2):
|
---|
1104 | print "usage: showLog <vm> <num>"
|
---|
1105 | return 0
|
---|
1106 | mach = argsToMach(ctx,args)
|
---|
1107 | if mach == None:
|
---|
1108 | return 0
|
---|
1109 |
|
---|
1110 | log = 0;
|
---|
1111 | if (len(args) > 2):
|
---|
1112 | log = args[2];
|
---|
1113 |
|
---|
1114 | uOffset = 0;
|
---|
1115 | while True:
|
---|
1116 | data = mach.readLog(log, uOffset, 1024*1024)
|
---|
1117 | if (len(data) == 0):
|
---|
1118 | break
|
---|
1119 | # print adds either NL or space to chunks not ending with a NL
|
---|
1120 | sys.stdout.write(data)
|
---|
1121 | uOffset += len(data)
|
---|
1122 |
|
---|
1123 | return 0
|
---|
1124 |
|
---|
1125 | def evalCmd(ctx, args):
|
---|
1126 | expr = ' '.join(args[1:])
|
---|
1127 | try:
|
---|
1128 | exec expr
|
---|
1129 | except Exception, e:
|
---|
1130 | print 'failed: ',e
|
---|
1131 | if g_verbose:
|
---|
1132 | traceback.print_exc()
|
---|
1133 | return 0
|
---|
1134 |
|
---|
1135 | def reloadExtCmd(ctx, args):
|
---|
1136 | # maybe will want more args smartness
|
---|
1137 | checkUserExtensions(ctx, commands, getHomeFolder(ctx))
|
---|
1138 | autoCompletion(commands, ctx)
|
---|
1139 | return 0
|
---|
1140 |
|
---|
1141 |
|
---|
1142 | def runScriptCmd(ctx, args):
|
---|
1143 | if (len(args) != 2):
|
---|
1144 | print "usage: runScript <script>"
|
---|
1145 | return 0
|
---|
1146 | try:
|
---|
1147 | lf = open(args[1], 'r')
|
---|
1148 | except IOError,e:
|
---|
1149 | print "cannot open:",args[1], ":",e
|
---|
1150 | return 0
|
---|
1151 |
|
---|
1152 | try:
|
---|
1153 | for line in lf:
|
---|
1154 | done = runCommand(ctx, line)
|
---|
1155 | if done != 0: break
|
---|
1156 | except Exception,e:
|
---|
1157 | print "error:",e
|
---|
1158 | if g_verbose:
|
---|
1159 | traceback.print_exc()
|
---|
1160 | lf.close()
|
---|
1161 | return 0
|
---|
1162 |
|
---|
1163 | def sleepCmd(ctx, args):
|
---|
1164 | if (len(args) != 2):
|
---|
1165 | print "usage: sleep <secs>"
|
---|
1166 | return 0
|
---|
1167 |
|
---|
1168 | try:
|
---|
1169 | time.sleep(float(args[1]))
|
---|
1170 | except:
|
---|
1171 | # to allow sleep interrupt
|
---|
1172 | pass
|
---|
1173 | return 0
|
---|
1174 |
|
---|
1175 |
|
---|
1176 | def shellCmd(ctx, args):
|
---|
1177 | if (len(args) < 2):
|
---|
1178 | print "usage: shell <commands>"
|
---|
1179 | return 0
|
---|
1180 | cmd = ' '.join(args[1:])
|
---|
1181 | try:
|
---|
1182 | os.system(cmd)
|
---|
1183 | except KeyboardInterrupt:
|
---|
1184 | # to allow shell command interruption
|
---|
1185 | pass
|
---|
1186 | return 0
|
---|
1187 |
|
---|
1188 |
|
---|
1189 | def connectCmd(ctx, args):
|
---|
1190 | if (len(args) > 4):
|
---|
1191 | print "usage: connect [url] [username] [passwd]"
|
---|
1192 | return 0
|
---|
1193 |
|
---|
1194 | if ctx['vb'] is not None:
|
---|
1195 | print "Already connected, disconnect first..."
|
---|
1196 | return 0
|
---|
1197 |
|
---|
1198 | if (len(args) > 1):
|
---|
1199 | url = args[1]
|
---|
1200 | else:
|
---|
1201 | url = None
|
---|
1202 |
|
---|
1203 | if (len(args) > 2):
|
---|
1204 | user = args[2]
|
---|
1205 | else:
|
---|
1206 | user = ""
|
---|
1207 |
|
---|
1208 | if (len(args) > 3):
|
---|
1209 | passwd = args[3]
|
---|
1210 | else:
|
---|
1211 | passwd = ""
|
---|
1212 |
|
---|
1213 | vbox = ctx['global'].platform.connect(url, user, passwd)
|
---|
1214 | ctx['vb'] = vbox
|
---|
1215 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1216 | ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
|
---|
1217 | return 0
|
---|
1218 |
|
---|
1219 | def disconnectCmd(ctx, args):
|
---|
1220 | if (len(args) != 1):
|
---|
1221 | print "usage: disconnect"
|
---|
1222 | return 0
|
---|
1223 |
|
---|
1224 | if ctx['vb'] is None:
|
---|
1225 | print "Not connected yet."
|
---|
1226 | return 0
|
---|
1227 |
|
---|
1228 | try:
|
---|
1229 | ctx['global'].platform.disconnect()
|
---|
1230 | except:
|
---|
1231 | ctx['vb'] = None
|
---|
1232 | raise
|
---|
1233 |
|
---|
1234 | ctx['vb'] = None
|
---|
1235 | return 0
|
---|
1236 |
|
---|
1237 | def exportVMCmd(ctx, args):
|
---|
1238 | import sys
|
---|
1239 |
|
---|
1240 | if len(args) < 3:
|
---|
1241 | print "usage: exportVm <machine> <path> <format> <license>"
|
---|
1242 | return 0
|
---|
1243 | mach = ctx['machById'](args[1])
|
---|
1244 | if mach is None:
|
---|
1245 | return 0
|
---|
1246 | path = args[2]
|
---|
1247 | if (len(args) > 3):
|
---|
1248 | format = args[3]
|
---|
1249 | else:
|
---|
1250 | format = "ovf-1.0"
|
---|
1251 | if (len(args) > 4):
|
---|
1252 | license = args[4]
|
---|
1253 | else:
|
---|
1254 | license = "GPL"
|
---|
1255 |
|
---|
1256 | app = ctx['vb'].createAppliance()
|
---|
1257 | desc = mach.export(app)
|
---|
1258 | desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
|
---|
1259 | p = app.write(format, path)
|
---|
1260 | progressBar(ctx, p)
|
---|
1261 | print "Exported to %s in format %s" %(path, format)
|
---|
1262 | return 0
|
---|
1263 |
|
---|
1264 | # PC XT scancodes
|
---|
1265 | scancodes = {
|
---|
1266 | 'a': 0x1e,
|
---|
1267 | 'b': 0x30,
|
---|
1268 | 'c': 0x2e,
|
---|
1269 | 'd': 0x20,
|
---|
1270 | 'e': 0x12,
|
---|
1271 | 'f': 0x21,
|
---|
1272 | 'g': 0x22,
|
---|
1273 | 'h': 0x23,
|
---|
1274 | 'i': 0x17,
|
---|
1275 | 'j': 0x24,
|
---|
1276 | 'k': 0x25,
|
---|
1277 | 'l': 0x26,
|
---|
1278 | 'm': 0x32,
|
---|
1279 | 'n': 0x31,
|
---|
1280 | 'o': 0x18,
|
---|
1281 | 'p': 0x19,
|
---|
1282 | 'q': 0x10,
|
---|
1283 | 'r': 0x13,
|
---|
1284 | 's': 0x1f,
|
---|
1285 | 't': 0x14,
|
---|
1286 | 'u': 0x16,
|
---|
1287 | 'v': 0x2f,
|
---|
1288 | 'w': 0x11,
|
---|
1289 | 'x': 0x2d,
|
---|
1290 | 'y': 0x15,
|
---|
1291 | 'z': 0x2c,
|
---|
1292 | '0': 0x0b,
|
---|
1293 | '1': 0x02,
|
---|
1294 | '2': 0x03,
|
---|
1295 | '3': 0x04,
|
---|
1296 | '4': 0x05,
|
---|
1297 | '5': 0x06,
|
---|
1298 | '6': 0x07,
|
---|
1299 | '7': 0x08,
|
---|
1300 | '8': 0x09,
|
---|
1301 | '9': 0x0a,
|
---|
1302 | ' ': 0x39,
|
---|
1303 | '-': 0xc,
|
---|
1304 | '=': 0xd,
|
---|
1305 | '[': 0x1a,
|
---|
1306 | ']': 0x1b,
|
---|
1307 | ';': 0x27,
|
---|
1308 | '\'': 0x28,
|
---|
1309 | ',': 0x33,
|
---|
1310 | '.': 0x34,
|
---|
1311 | '/': 0x35,
|
---|
1312 | '\t': 0xf,
|
---|
1313 | '\n': 0x1c,
|
---|
1314 | '`': 0x29
|
---|
1315 | };
|
---|
1316 |
|
---|
1317 | extScancodes = {
|
---|
1318 | 'ESC' : [0x01],
|
---|
1319 | 'BKSP': [0xe],
|
---|
1320 | 'SPACE': [0x39],
|
---|
1321 | 'TAB': [0x0f],
|
---|
1322 | 'CAPS': [0x3a],
|
---|
1323 | 'ENTER': [0x1c],
|
---|
1324 | 'LSHIFT': [0x2a],
|
---|
1325 | 'RSHIFT': [0x36],
|
---|
1326 | 'INS': [0xe0, 0x52],
|
---|
1327 | 'DEL': [0xe0, 0x53],
|
---|
1328 | 'END': [0xe0, 0x4f],
|
---|
1329 | 'HOME': [0xe0, 0x47],
|
---|
1330 | 'PGUP': [0xe0, 0x49],
|
---|
1331 | 'PGDOWN': [0xe0, 0x51],
|
---|
1332 | 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
|
---|
1333 | 'RGUI': [0xe0, 0x5c],
|
---|
1334 | 'LCTR': [0x1d],
|
---|
1335 | 'RCTR': [0xe0, 0x1d],
|
---|
1336 | 'LALT': [0x38],
|
---|
1337 | 'RALT': [0xe0, 0x38],
|
---|
1338 | 'APPS': [0xe0, 0x5d],
|
---|
1339 | 'F1': [0x3b],
|
---|
1340 | 'F2': [0x3c],
|
---|
1341 | 'F3': [0x3d],
|
---|
1342 | 'F4': [0x3e],
|
---|
1343 | 'F5': [0x3f],
|
---|
1344 | 'F6': [0x40],
|
---|
1345 | 'F7': [0x41],
|
---|
1346 | 'F8': [0x42],
|
---|
1347 | 'F9': [0x43],
|
---|
1348 | 'F10': [0x44 ],
|
---|
1349 | 'F11': [0x57],
|
---|
1350 | 'F12': [0x58],
|
---|
1351 | 'UP': [0xe0, 0x48],
|
---|
1352 | 'LEFT': [0xe0, 0x4b],
|
---|
1353 | 'DOWN': [0xe0, 0x50],
|
---|
1354 | 'RIGHT': [0xe0, 0x4d],
|
---|
1355 | };
|
---|
1356 |
|
---|
1357 | def keyDown(ch):
|
---|
1358 | code = scancodes.get(ch, 0x0)
|
---|
1359 | if code != 0:
|
---|
1360 | return [code]
|
---|
1361 | extCode = extScancodes.get(ch, [])
|
---|
1362 | if len(extCode) == 0:
|
---|
1363 | print "bad ext",ch
|
---|
1364 | return extCode
|
---|
1365 |
|
---|
1366 | def keyUp(ch):
|
---|
1367 | codes = keyDown(ch)[:] # make a copy
|
---|
1368 | if len(codes) > 0:
|
---|
1369 | codes[len(codes)-1] += 0x80
|
---|
1370 | return codes
|
---|
1371 |
|
---|
1372 | def typeInGuest(console, text, delay):
|
---|
1373 | import time
|
---|
1374 | pressed = []
|
---|
1375 | group = False
|
---|
1376 | modGroupEnd = True
|
---|
1377 | i = 0
|
---|
1378 | while i < len(text):
|
---|
1379 | ch = text[i]
|
---|
1380 | i = i+1
|
---|
1381 | if ch == '{':
|
---|
1382 | # start group, all keys to be pressed at the same time
|
---|
1383 | group = True
|
---|
1384 | continue
|
---|
1385 | if ch == '}':
|
---|
1386 | # end group, release all keys
|
---|
1387 | for c in pressed:
|
---|
1388 | console.keyboard.putScancodes(keyUp(c))
|
---|
1389 | pressed = []
|
---|
1390 | group = False
|
---|
1391 | continue
|
---|
1392 | if ch == 'W':
|
---|
1393 | # just wait a bit
|
---|
1394 | time.sleep(0.3)
|
---|
1395 | continue
|
---|
1396 | if ch == '^' or ch == '|' or ch == '$' or ch == '_':
|
---|
1397 | if ch == '^':
|
---|
1398 | ch = 'LCTR'
|
---|
1399 | if ch == '|':
|
---|
1400 | ch = 'LSHIFT'
|
---|
1401 | if ch == '_':
|
---|
1402 | ch = 'LALT'
|
---|
1403 | if ch == '$':
|
---|
1404 | ch = 'LGUI'
|
---|
1405 | if not group:
|
---|
1406 | modGroupEnd = False
|
---|
1407 | else:
|
---|
1408 | if ch == '\\':
|
---|
1409 | if i < len(text):
|
---|
1410 | ch = text[i]
|
---|
1411 | i = i+1
|
---|
1412 | if ch == 'n':
|
---|
1413 | ch = '\n'
|
---|
1414 | elif ch == '&':
|
---|
1415 | combo = ""
|
---|
1416 | while i < len(text):
|
---|
1417 | ch = text[i]
|
---|
1418 | i = i+1
|
---|
1419 | if ch == ';':
|
---|
1420 | break
|
---|
1421 | combo += ch
|
---|
1422 | ch = combo
|
---|
1423 | modGroupEnd = True
|
---|
1424 | console.keyboard.putScancodes(keyDown(ch))
|
---|
1425 | pressed.insert(0, ch)
|
---|
1426 | if not group and modGroupEnd:
|
---|
1427 | for c in pressed:
|
---|
1428 | console.keyboard.putScancodes(keyUp(c))
|
---|
1429 | pressed = []
|
---|
1430 | modGroupEnd = True
|
---|
1431 | time.sleep(delay)
|
---|
1432 |
|
---|
1433 | def typeGuestCmd(ctx, args):
|
---|
1434 | import sys
|
---|
1435 |
|
---|
1436 | if len(args) < 3:
|
---|
1437 | print "usage: typeGuest <machine> <text> <charDelay>"
|
---|
1438 | return 0
|
---|
1439 | mach = ctx['machById'](args[1])
|
---|
1440 | if mach is None:
|
---|
1441 | return 0
|
---|
1442 |
|
---|
1443 | text = args[2]
|
---|
1444 |
|
---|
1445 | if len(args) > 3:
|
---|
1446 | delay = float(args[3])
|
---|
1447 | else:
|
---|
1448 | delay = 0.1
|
---|
1449 |
|
---|
1450 | gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
|
---|
1451 | cmdExistingVm(ctx, mach, 'guestlambda', gargs)
|
---|
1452 |
|
---|
1453 | return 0
|
---|
1454 |
|
---|
1455 | def optId(verbose,id):
|
---|
1456 | if verbose:
|
---|
1457 | return ": "+id
|
---|
1458 | else:
|
---|
1459 | return ""
|
---|
1460 |
|
---|
1461 | def asSize(val,inBytes):
|
---|
1462 | if inBytes:
|
---|
1463 | return int(val)/(1024*1024)
|
---|
1464 | else:
|
---|
1465 | return int(val)
|
---|
1466 |
|
---|
1467 | def listMediumsCmd(ctx,args):
|
---|
1468 | if len(args) > 1:
|
---|
1469 | verbose = int(args[1])
|
---|
1470 | else:
|
---|
1471 | verbose = False
|
---|
1472 | hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
|
---|
1473 | print "Hard disks:"
|
---|
1474 | for hdd in hdds:
|
---|
1475 | if hdd.state != ctx['global'].constants.MediumState_Created:
|
---|
1476 | hdd.refreshState()
|
---|
1477 | print " %s (%s)%s %dM [logical %dM]" %(hdd.location, hdd.format, optId(verbose,hdd.id),asSize(hdd.size, True), asSize(hdd.logicalSize, False))
|
---|
1478 |
|
---|
1479 | dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
|
---|
1480 | print "CD/DVD disks:"
|
---|
1481 | for dvd in dvds:
|
---|
1482 | if dvd.state != ctx['global'].constants.MediumState_Created:
|
---|
1483 | dvd.refreshState()
|
---|
1484 | print " %s (%s)%s %dM" %(dvd.location, dvd.format,optId(verbose,hdd.id),asSize(hdd.size, True))
|
---|
1485 |
|
---|
1486 | floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
|
---|
1487 | print "Floopy disks:"
|
---|
1488 | for floppy in floppys:
|
---|
1489 | if floppy.state != ctx['global'].constants.MediumState_Created:
|
---|
1490 | floppy.refreshState()
|
---|
1491 | print " %s (%s)%s %dM" %(floppy.location, floppy.format,optId(verbose,hdd.id), asSize(hdd.size, True))
|
---|
1492 |
|
---|
1493 | return 0
|
---|
1494 |
|
---|
1495 | def createHddCmd(ctx,args):
|
---|
1496 | if (len(args) < 3):
|
---|
1497 | print "usage: createHdd sizeM location type"
|
---|
1498 | return 0
|
---|
1499 |
|
---|
1500 | size = int(args[1])
|
---|
1501 | loc = args[2]
|
---|
1502 | if len(args) > 3:
|
---|
1503 | format = args[3]
|
---|
1504 | else:
|
---|
1505 | format = "vdi"
|
---|
1506 |
|
---|
1507 | hdd = ctx['vb'].createHardDisk(format, loc)
|
---|
1508 | progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
|
---|
1509 | ctx['progressBar'](progress)
|
---|
1510 |
|
---|
1511 | if not hdd.id:
|
---|
1512 | print "cannot create disk (file %s exist?)" %(loc)
|
---|
1513 | return 0
|
---|
1514 |
|
---|
1515 | print "created HDD at %s as %s" %(hdd.location, hdd.id)
|
---|
1516 |
|
---|
1517 | return 0
|
---|
1518 |
|
---|
1519 | def registerHddCmd(ctx,args):
|
---|
1520 | if (len(args) < 2):
|
---|
1521 | print "usage: registerHdd location"
|
---|
1522 | return 0
|
---|
1523 |
|
---|
1524 | vb = ctx['vb']
|
---|
1525 | loc = args[1]
|
---|
1526 | setImageId = False
|
---|
1527 | imageId = ""
|
---|
1528 | setParentId = False
|
---|
1529 | parentId = ""
|
---|
1530 | hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
|
---|
1531 | print "registered HDD as %s" %(hdd.id)
|
---|
1532 | return 0
|
---|
1533 |
|
---|
1534 | def controldevice(ctx,mach,args):
|
---|
1535 | [ctr,port,slot,type,id] = args
|
---|
1536 | mach.attachDevice(ctr, port, slot,type,id)
|
---|
1537 |
|
---|
1538 | def attachHddCmd(ctx,args):
|
---|
1539 | if (len(args) < 4):
|
---|
1540 | print "usage: attachHdd vm hdd controller port:slot"
|
---|
1541 | return 0
|
---|
1542 |
|
---|
1543 | mach = ctx['machById'](args[1])
|
---|
1544 | if mach is None:
|
---|
1545 | return 0
|
---|
1546 | vb = ctx['vb']
|
---|
1547 | loc = args[2]
|
---|
1548 | try:
|
---|
1549 | hdd = vb.findHardDisk(loc)
|
---|
1550 | except:
|
---|
1551 | print "no HDD with path %s registered" %(loc)
|
---|
1552 | return 0
|
---|
1553 | ctr = args[3]
|
---|
1554 | (port,slot) = args[4].split(":")
|
---|
1555 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
|
---|
1556 | return 0
|
---|
1557 |
|
---|
1558 | def detachVmDevice(ctx,mach,args):
|
---|
1559 | atts = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
1560 | hid = args[0]
|
---|
1561 | for a in atts:
|
---|
1562 | if a.medium:
|
---|
1563 | if hid == "ALL" or a.medium.id == hid:
|
---|
1564 | mach.detachDevice(a.controller, a.port, a.device)
|
---|
1565 |
|
---|
1566 | def detachMedium(ctx,mid,medium):
|
---|
1567 | cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
|
---|
1568 |
|
---|
1569 | def detachHddCmd(ctx,args):
|
---|
1570 | if (len(args) < 3):
|
---|
1571 | print "usage: detachHdd vm hdd"
|
---|
1572 | return 0
|
---|
1573 |
|
---|
1574 | mach = ctx['machById'](args[1])
|
---|
1575 | if mach is None:
|
---|
1576 | return 0
|
---|
1577 | vb = ctx['vb']
|
---|
1578 | loc = args[2]
|
---|
1579 | try:
|
---|
1580 | hdd = vb.findHardDisk(loc)
|
---|
1581 | except:
|
---|
1582 | print "no HDD with path %s registered" %(loc)
|
---|
1583 | return 0
|
---|
1584 |
|
---|
1585 | detachMedium(ctx,mach.id,hdd)
|
---|
1586 | return 0
|
---|
1587 |
|
---|
1588 | def unregisterHddCmd(ctx,args):
|
---|
1589 | if (len(args) < 2):
|
---|
1590 | print "usage: unregisterHdd path <vmunreg>"
|
---|
1591 | return 0
|
---|
1592 |
|
---|
1593 | vb = ctx['vb']
|
---|
1594 | loc = args[1]
|
---|
1595 | if (len(args) > 2):
|
---|
1596 | vmunreg = int(args[2])
|
---|
1597 | else:
|
---|
1598 | vmunreg = 0
|
---|
1599 | try:
|
---|
1600 | hdd = vb.findHardDisk(loc)
|
---|
1601 | except:
|
---|
1602 | print "no HDD with path %s registered" %(loc)
|
---|
1603 | return 0
|
---|
1604 |
|
---|
1605 | if vmunreg != 0:
|
---|
1606 | machs = ctx['global'].getArray(hdd, 'machineIds')
|
---|
1607 | try:
|
---|
1608 | for m in machs:
|
---|
1609 | print "Trying to detach from %s" %(m)
|
---|
1610 | detachMedium(ctx,m,hdd)
|
---|
1611 | except Exception, e:
|
---|
1612 | print 'failed: ',e
|
---|
1613 | return 0
|
---|
1614 | hdd.close()
|
---|
1615 | return 0
|
---|
1616 |
|
---|
1617 | def removeHddCmd(ctx,args):
|
---|
1618 | if (len(args) != 2):
|
---|
1619 | print "usage: removeHdd path"
|
---|
1620 | return 0
|
---|
1621 |
|
---|
1622 | vb = ctx['vb']
|
---|
1623 | loc = args[1]
|
---|
1624 | try:
|
---|
1625 | hdd = vb.findHardDisk(loc)
|
---|
1626 | except:
|
---|
1627 | print "no HDD with path %s registered" %(loc)
|
---|
1628 | return 0
|
---|
1629 |
|
---|
1630 | progress = hdd.deleteStorage()
|
---|
1631 | ctx['progressBar'](progress)
|
---|
1632 |
|
---|
1633 | return 0
|
---|
1634 |
|
---|
1635 | def registerIsoCmd(ctx,args):
|
---|
1636 | if (len(args) < 2):
|
---|
1637 | print "usage: registerIso location"
|
---|
1638 | return 0
|
---|
1639 | vb = ctx['vb']
|
---|
1640 | loc = args[1]
|
---|
1641 | id = ""
|
---|
1642 | iso = vb.openDVDImage(loc, id)
|
---|
1643 | print "registered ISO as %s" %(iso.id)
|
---|
1644 | return 0
|
---|
1645 |
|
---|
1646 | def unregisterIsoCmd(ctx,args):
|
---|
1647 | if (len(args) != 2):
|
---|
1648 | print "usage: unregisterIso path"
|
---|
1649 | return 0
|
---|
1650 |
|
---|
1651 | vb = ctx['vb']
|
---|
1652 | loc = args[1]
|
---|
1653 | try:
|
---|
1654 | dvd = vb.findDVDImage(loc)
|
---|
1655 | except:
|
---|
1656 | print "no DVD with path %s registered" %(loc)
|
---|
1657 | return 0
|
---|
1658 |
|
---|
1659 | progress = dvd.close()
|
---|
1660 | print "Unregistered ISO at %s" %(dvd.location)
|
---|
1661 |
|
---|
1662 | return 0
|
---|
1663 |
|
---|
1664 | def removeIsoCmd(ctx,args):
|
---|
1665 | if (len(args) != 2):
|
---|
1666 | print "usage: removeIso path"
|
---|
1667 | return 0
|
---|
1668 |
|
---|
1669 | vb = ctx['vb']
|
---|
1670 | loc = args[1]
|
---|
1671 | try:
|
---|
1672 | dvd = vb.findDVDImage(loc)
|
---|
1673 | except:
|
---|
1674 | print "no DVD with path %s registered" %(loc)
|
---|
1675 | return 0
|
---|
1676 |
|
---|
1677 | progress = dvd.deleteStorage()
|
---|
1678 | ctx['progressBar'](progress)
|
---|
1679 | print "Removed ISO at %s" %(dvd.location)
|
---|
1680 |
|
---|
1681 | return 0
|
---|
1682 |
|
---|
1683 | def attachIsoCmd(ctx,args):
|
---|
1684 | if (len(args) < 5):
|
---|
1685 | print "usage: attachIso vm iso controller port:slot"
|
---|
1686 | return 0
|
---|
1687 |
|
---|
1688 | mach = ctx['machById'](args[1])
|
---|
1689 | if mach is None:
|
---|
1690 | return 0
|
---|
1691 | vb = ctx['vb']
|
---|
1692 | loc = args[2]
|
---|
1693 | try:
|
---|
1694 | dvd = vb.findDVDImage(loc)
|
---|
1695 | except:
|
---|
1696 | print "no DVD with path %s registered" %(loc)
|
---|
1697 | return 0
|
---|
1698 | ctr = args[3]
|
---|
1699 | (port,slot) = args[4].split(":")
|
---|
1700 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
|
---|
1701 | return 0
|
---|
1702 |
|
---|
1703 | def detachIsoCmd(ctx,args):
|
---|
1704 | if (len(args) < 3):
|
---|
1705 | print "usage: detachIso vm iso"
|
---|
1706 | return 0
|
---|
1707 |
|
---|
1708 | mach = ctx['machById'](args[1])
|
---|
1709 | if mach is None:
|
---|
1710 | return 0
|
---|
1711 | vb = ctx['vb']
|
---|
1712 | loc = args[2]
|
---|
1713 | try:
|
---|
1714 | dvd = vb.findDVDImage(loc)
|
---|
1715 | except:
|
---|
1716 | print "no DVD with path %s registered" %(loc)
|
---|
1717 | return 0
|
---|
1718 |
|
---|
1719 | detachMedium(ctx,mach.id,dvd)
|
---|
1720 | return 0
|
---|
1721 |
|
---|
1722 | def mountIsoCmd(ctx,args):
|
---|
1723 | if (len(args) < 5):
|
---|
1724 | print "usage: mountIso vm iso controller port:slot"
|
---|
1725 | return 0
|
---|
1726 |
|
---|
1727 | mach = ctx['machById'](args[1])
|
---|
1728 | if mach is None:
|
---|
1729 | return 0
|
---|
1730 | vb = ctx['vb']
|
---|
1731 | loc = args[2]
|
---|
1732 | try:
|
---|
1733 | dvd = vb.findDVDImage(loc)
|
---|
1734 | except:
|
---|
1735 | print "no DVD with path %s registered" %(loc)
|
---|
1736 | return 0
|
---|
1737 |
|
---|
1738 | ctr = args[3]
|
---|
1739 | (port,slot) = args[4].split(":")
|
---|
1740 |
|
---|
1741 | cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
|
---|
1742 |
|
---|
1743 | return 0
|
---|
1744 |
|
---|
1745 | def unmountIsoCmd(ctx,args):
|
---|
1746 | if (len(args) < 4):
|
---|
1747 | print "usage: unmountIso vm controller port:slot"
|
---|
1748 | return 0
|
---|
1749 |
|
---|
1750 | mach = ctx['machById'](args[1])
|
---|
1751 | if mach is None:
|
---|
1752 | return 0
|
---|
1753 | vb = ctx['vb']
|
---|
1754 |
|
---|
1755 | ctr = args[2]
|
---|
1756 | (port,slot) = args[3].split(":")
|
---|
1757 |
|
---|
1758 | cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
|
---|
1759 |
|
---|
1760 | return 0
|
---|
1761 |
|
---|
1762 | def attachCtr(ctx,mach,args):
|
---|
1763 | [name, bus, type] = args
|
---|
1764 | ctr = mach.addStorageController(name, bus)
|
---|
1765 | if type != None:
|
---|
1766 | ctr.controllerType = type
|
---|
1767 |
|
---|
1768 | def attachCtrCmd(ctx,args):
|
---|
1769 | if (len(args) < 4):
|
---|
1770 | print "usage: attachCtr vm cname bus <type>"
|
---|
1771 | return 0
|
---|
1772 |
|
---|
1773 | if len(args) > 4:
|
---|
1774 | type = enumFromString(ctx,'StorageControllerType', args[4])
|
---|
1775 | if type == None:
|
---|
1776 | print "Controller type %s unknown" %(args[4])
|
---|
1777 | return 0
|
---|
1778 | else:
|
---|
1779 | type = None
|
---|
1780 |
|
---|
1781 | mach = ctx['machById'](args[1])
|
---|
1782 | if mach is None:
|
---|
1783 | return 0
|
---|
1784 | bus = enumFromString(ctx,'StorageBus', args[3])
|
---|
1785 | if bus is None:
|
---|
1786 | print "Bus type %s unknown" %(args[3])
|
---|
1787 | return 0
|
---|
1788 | name = args[2]
|
---|
1789 | cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
|
---|
1790 | return 0
|
---|
1791 |
|
---|
1792 | def detachCtrCmd(ctx,args):
|
---|
1793 | if (len(args) < 3):
|
---|
1794 | print "usage: detachCtr vm name"
|
---|
1795 | return 0
|
---|
1796 |
|
---|
1797 | mach = ctx['machById'](args[1])
|
---|
1798 | if mach is None:
|
---|
1799 | return 0
|
---|
1800 | ctr = args[2]
|
---|
1801 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
|
---|
1802 | return 0
|
---|
1803 |
|
---|
1804 |
|
---|
1805 | aliases = {'s':'start',
|
---|
1806 | 'i':'info',
|
---|
1807 | 'l':'list',
|
---|
1808 | 'h':'help',
|
---|
1809 | 'a':'alias',
|
---|
1810 | 'q':'quit', 'exit':'quit',
|
---|
1811 | 'tg': 'typeGuest',
|
---|
1812 | 'v':'verbose'}
|
---|
1813 |
|
---|
1814 | commands = {'help':['Prints help information', helpCmd, 0],
|
---|
1815 | 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
|
---|
1816 | 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
|
---|
1817 | 'removeVm':['Remove virtual machine', removeVmCmd, 0],
|
---|
1818 | 'pause':['Pause virtual machine', pauseCmd, 0],
|
---|
1819 | 'resume':['Resume virtual machine', resumeCmd, 0],
|
---|
1820 | 'save':['Save execution state of virtual machine', saveCmd, 0],
|
---|
1821 | 'stats':['Stats for virtual machine', statsCmd, 0],
|
---|
1822 | 'powerdown':['Power down virtual machine', powerdownCmd, 0],
|
---|
1823 | 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
|
---|
1824 | 'list':['Shows known virtual machines', listCmd, 0],
|
---|
1825 | 'info':['Shows info on machine', infoCmd, 0],
|
---|
1826 | 'ginfo':['Shows info on guest', ginfoCmd, 0],
|
---|
1827 | 'gexec':['Executes program in the guest', gexecCmd, 0],
|
---|
1828 | 'alias':['Control aliases', aliasCmd, 0],
|
---|
1829 | 'verbose':['Toggle verbosity', verboseCmd, 0],
|
---|
1830 | 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
|
---|
1831 | 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
|
---|
1832 | 'quit':['Exits', quitCmd, 0],
|
---|
1833 | 'host':['Show host information', hostCmd, 0],
|
---|
1834 | 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
|
---|
1835 | 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
|
---|
1836 | 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
|
---|
1837 | 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
|
---|
1838 | 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
|
---|
1839 | 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
|
---|
1840 | 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
|
---|
1841 | 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
|
---|
1842 | 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
|
---|
1843 | 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
|
---|
1844 | 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
|
---|
1845 | 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
|
---|
1846 | 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
|
---|
1847 | 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
|
---|
1848 | 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
|
---|
1849 | 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
|
---|
1850 | 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
|
---|
1851 | 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
|
---|
1852 | 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
|
---|
1853 | 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
|
---|
1854 | 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
|
---|
1855 | 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
|
---|
1856 | 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
|
---|
1857 | 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
|
---|
1858 | 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
|
---|
1859 | 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
|
---|
1860 | 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
|
---|
1861 | 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
|
---|
1862 | 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
|
---|
1863 | 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
|
---|
1864 | 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
|
---|
1865 | 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
|
---|
1866 | 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
|
---|
1867 | 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
|
---|
1868 | 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
|
---|
1869 | 'listMediums': ['List mediums known to this VBox instance', listMediumsCmd, 0]
|
---|
1870 | }
|
---|
1871 |
|
---|
1872 | def runCommandArgs(ctx, args):
|
---|
1873 | c = args[0]
|
---|
1874 | if aliases.get(c, None) != None:
|
---|
1875 | c = aliases[c]
|
---|
1876 | ci = commands.get(c,None)
|
---|
1877 | if ci == None:
|
---|
1878 | print "Unknown command: '%s', type 'help' for list of known commands" %(c)
|
---|
1879 | return 0
|
---|
1880 | return ci[1](ctx, args)
|
---|
1881 |
|
---|
1882 |
|
---|
1883 | def runCommand(ctx, cmd):
|
---|
1884 | if len(cmd) == 0: return 0
|
---|
1885 | args = split_no_quotes(cmd)
|
---|
1886 | if len(args) == 0: return 0
|
---|
1887 | return runCommandArgs(ctx, args)
|
---|
1888 |
|
---|
1889 | #
|
---|
1890 | # To write your own custom commands to vboxshell, create
|
---|
1891 | # file ~/.VirtualBox/shellext.py with content like
|
---|
1892 | #
|
---|
1893 | # def runTestCmd(ctx, args):
|
---|
1894 | # print "Testy test", ctx['vb']
|
---|
1895 | # return 0
|
---|
1896 | #
|
---|
1897 | # commands = {
|
---|
1898 | # 'test': ['Test help', runTestCmd]
|
---|
1899 | # }
|
---|
1900 | # and issue reloadExt shell command.
|
---|
1901 | # This file also will be read automatically on startup or 'reloadExt'.
|
---|
1902 | #
|
---|
1903 | # Also one can put shell extensions into ~/.VirtualBox/shexts and
|
---|
1904 | # they will also be picked up, so this way one can exchange
|
---|
1905 | # shell extensions easily.
|
---|
1906 | def addExtsFromFile(ctx, cmds, file):
|
---|
1907 | if not os.path.isfile(file):
|
---|
1908 | return
|
---|
1909 | d = {}
|
---|
1910 | try:
|
---|
1911 | execfile(file, d, d)
|
---|
1912 | for (k,v) in d['commands'].items():
|
---|
1913 | if g_verbose:
|
---|
1914 | print "customize: adding \"%s\" - %s" %(k, v[0])
|
---|
1915 | cmds[k] = [v[0], v[1], file]
|
---|
1916 | except:
|
---|
1917 | print "Error loading user extensions from %s" %(file)
|
---|
1918 | traceback.print_exc()
|
---|
1919 |
|
---|
1920 |
|
---|
1921 | def checkUserExtensions(ctx, cmds, folder):
|
---|
1922 | folder = str(folder)
|
---|
1923 | name = os.path.join(folder, "shellext.py")
|
---|
1924 | addExtsFromFile(ctx, cmds, name)
|
---|
1925 | # also check 'exts' directory for all files
|
---|
1926 | shextdir = os.path.join(folder, "shexts")
|
---|
1927 | if not os.path.isdir(shextdir):
|
---|
1928 | return
|
---|
1929 | exts = os.listdir(shextdir)
|
---|
1930 | for e in exts:
|
---|
1931 | addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
|
---|
1932 |
|
---|
1933 | def getHomeFolder(ctx):
|
---|
1934 | if ctx['remote'] or ctx['vb'] is None:
|
---|
1935 | return os.path.join(os.path.expanduser("~"), ".VirtualBox")
|
---|
1936 | else:
|
---|
1937 | return ctx['vb'].homeFolder
|
---|
1938 |
|
---|
1939 | def interpret(ctx):
|
---|
1940 | if ctx['remote']:
|
---|
1941 | commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
|
---|
1942 | commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
|
---|
1943 |
|
---|
1944 | vbox = ctx['vb']
|
---|
1945 |
|
---|
1946 | if vbox is not None:
|
---|
1947 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1948 | ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
|
---|
1949 | else:
|
---|
1950 | ctx['perf'] = None
|
---|
1951 |
|
---|
1952 | home = getHomeFolder(ctx)
|
---|
1953 | checkUserExtensions(ctx, commands, home)
|
---|
1954 |
|
---|
1955 | autoCompletion(commands, ctx)
|
---|
1956 |
|
---|
1957 | # to allow to print actual host information, we collect info for
|
---|
1958 | # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
|
---|
1959 | if ctx['perf']:
|
---|
1960 | try:
|
---|
1961 | ctx['perf'].setup(['*'], [vbox.host], 10, 15)
|
---|
1962 | except:
|
---|
1963 | pass
|
---|
1964 |
|
---|
1965 | while True:
|
---|
1966 | try:
|
---|
1967 | cmd = raw_input("vbox> ")
|
---|
1968 | done = runCommand(ctx, cmd)
|
---|
1969 | if done != 0: break
|
---|
1970 | except KeyboardInterrupt:
|
---|
1971 | print '====== You can type quit or q to leave'
|
---|
1972 | break
|
---|
1973 | except EOFError:
|
---|
1974 | break;
|
---|
1975 | except Exception,e:
|
---|
1976 | print e
|
---|
1977 | if g_verbose:
|
---|
1978 | traceback.print_exc()
|
---|
1979 | ctx['global'].waitForEvents(0)
|
---|
1980 | try:
|
---|
1981 | # There is no need to disable metric collection. This is just an example.
|
---|
1982 | if ct['perf']:
|
---|
1983 | ctx['perf'].disable(['*'], [vbox.host])
|
---|
1984 | except:
|
---|
1985 | pass
|
---|
1986 |
|
---|
1987 | def runCommandCb(ctx, cmd, args):
|
---|
1988 | args.insert(0, cmd)
|
---|
1989 | return runCommandArgs(ctx, args)
|
---|
1990 |
|
---|
1991 | def runGuestCommandCb(ctx, id, guestLambda, args):
|
---|
1992 | mach = machById(ctx,id)
|
---|
1993 | if mach == None:
|
---|
1994 | return 0
|
---|
1995 | args.insert(0, guestLambda)
|
---|
1996 | cmdExistingVm(ctx, mach, 'guestlambda', args)
|
---|
1997 | return 0
|
---|
1998 |
|
---|
1999 | def main(argv):
|
---|
2000 | style = None
|
---|
2001 | autopath = False
|
---|
2002 | argv.pop(0)
|
---|
2003 | while len(argv) > 0:
|
---|
2004 | if argv[0] == "-w":
|
---|
2005 | style = "WEBSERVICE"
|
---|
2006 | if argv[0] == "-a":
|
---|
2007 | autopath = True
|
---|
2008 | argv.pop(0)
|
---|
2009 |
|
---|
2010 | if autopath:
|
---|
2011 | cwd = os.getcwd()
|
---|
2012 | vpp = os.environ.get("VBOX_PROGRAM_PATH")
|
---|
2013 | if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
|
---|
2014 | vpp = cwd
|
---|
2015 | print "Autodetected VBOX_PROGRAM_PATH as",vpp
|
---|
2016 | os.environ["VBOX_PROGRAM_PATH"] = cwd
|
---|
2017 | sys.path.append(os.path.join(vpp, "sdk", "installer"))
|
---|
2018 |
|
---|
2019 | from vboxapi import VirtualBoxManager
|
---|
2020 | g_virtualBoxManager = VirtualBoxManager(style, None)
|
---|
2021 | ctx = {'global':g_virtualBoxManager,
|
---|
2022 | 'mgr':g_virtualBoxManager.mgr,
|
---|
2023 | 'vb':g_virtualBoxManager.vbox,
|
---|
2024 | 'ifaces':g_virtualBoxManager.constants,
|
---|
2025 | 'remote':g_virtualBoxManager.remote,
|
---|
2026 | 'type':g_virtualBoxManager.type,
|
---|
2027 | 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
|
---|
2028 | 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
|
---|
2029 | 'machById': lambda id: machById(ctx,id),
|
---|
2030 | 'argsToMach': lambda args: argsToMach(ctx,args),
|
---|
2031 | 'progressBar': lambda p: progressBar(ctx,p),
|
---|
2032 | 'typeInGuest': typeInGuest,
|
---|
2033 | '_machlist':None
|
---|
2034 | }
|
---|
2035 | interpret(ctx)
|
---|
2036 | g_virtualBoxManager.deinit()
|
---|
2037 | del g_virtualBoxManager
|
---|
2038 |
|
---|
2039 | if __name__ == '__main__':
|
---|
2040 | main(sys.argv)
|
---|