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