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