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