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 | from optparse import OptionParser
|
---|
33 |
|
---|
34 | g_batchmode = False
|
---|
35 | g_scripfile = None
|
---|
36 | g_cmd = None
|
---|
37 | g_hasreadline = True
|
---|
38 | try:
|
---|
39 | if g_hasreadline:
|
---|
40 | import readline
|
---|
41 | import rlcompleter
|
---|
42 | except:
|
---|
43 | g_hasreadline = False
|
---|
44 |
|
---|
45 |
|
---|
46 | g_prompt = "vbox> "
|
---|
47 |
|
---|
48 | g_hascolors = True
|
---|
49 | term_colors = {
|
---|
50 | 'red':'\033[31m',
|
---|
51 | 'blue':'\033[94m',
|
---|
52 | 'green':'\033[92m',
|
---|
53 | 'yellow':'\033[93m',
|
---|
54 | 'magenta':'\033[35m',
|
---|
55 | 'cyan':'\033[36m'
|
---|
56 | }
|
---|
57 | def colored(string,color):
|
---|
58 | if not g_hascolors:
|
---|
59 | return string
|
---|
60 | global term_colors
|
---|
61 | col = term_colors.get(color,None)
|
---|
62 | if col:
|
---|
63 | return col+str(string)+'\033[0m'
|
---|
64 | else:
|
---|
65 | return string
|
---|
66 |
|
---|
67 | if g_hasreadline:
|
---|
68 | import string
|
---|
69 | class CompleterNG(rlcompleter.Completer):
|
---|
70 | def __init__(self, dic, ctx):
|
---|
71 | self.ctx = ctx
|
---|
72 | return rlcompleter.Completer.__init__(self,dic)
|
---|
73 |
|
---|
74 | def complete(self, text, state):
|
---|
75 | """
|
---|
76 | taken from:
|
---|
77 | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
|
---|
78 | """
|
---|
79 | if False and text == "":
|
---|
80 | return ['\t',None][state]
|
---|
81 | else:
|
---|
82 | return rlcompleter.Completer.complete(self,text,state)
|
---|
83 |
|
---|
84 | def canBePath(self, phrase,word):
|
---|
85 | return word.startswith('/')
|
---|
86 |
|
---|
87 | def canBeCommand(self, phrase, word):
|
---|
88 | spaceIdx = phrase.find(" ")
|
---|
89 | begIdx = readline.get_begidx()
|
---|
90 | firstWord = (spaceIdx == -1 or begIdx < spaceIdx)
|
---|
91 | if firstWord:
|
---|
92 | return True
|
---|
93 | if phrase.startswith('help'):
|
---|
94 | return True
|
---|
95 | return False
|
---|
96 |
|
---|
97 | def canBeMachine(self,phrase,word):
|
---|
98 | return not self.canBePath(phrase,word) and not self.canBeCommand(phrase, word)
|
---|
99 |
|
---|
100 | def global_matches(self, text):
|
---|
101 | """
|
---|
102 | Compute matches when text is a simple name.
|
---|
103 | Return a list of all names currently defined
|
---|
104 | in self.namespace that match.
|
---|
105 | """
|
---|
106 |
|
---|
107 | matches = []
|
---|
108 | phrase = readline.get_line_buffer()
|
---|
109 |
|
---|
110 | try:
|
---|
111 | if self.canBePath(phrase,text):
|
---|
112 | (dir,rest) = os.path.split(text)
|
---|
113 | n = len(rest)
|
---|
114 | for word in os.listdir(dir):
|
---|
115 | if n == 0 or word[:n] == rest:
|
---|
116 | matches.append(os.path.join(dir,word))
|
---|
117 |
|
---|
118 | if self.canBeCommand(phrase,text):
|
---|
119 | n = len(text)
|
---|
120 | for list in [ self.namespace ]:
|
---|
121 | for word in list:
|
---|
122 | if word[:n] == text:
|
---|
123 | matches.append(word)
|
---|
124 |
|
---|
125 | if self.canBeMachine(phrase,text):
|
---|
126 | n = len(text)
|
---|
127 | for m in getMachines(self.ctx, False, True):
|
---|
128 | # although it has autoconversion, we need to cast
|
---|
129 | # explicitly for subscripts to work
|
---|
130 | word = re.sub("(?<!\\\\) ", "\\ ", str(m.name))
|
---|
131 | if word[:n] == text:
|
---|
132 | matches.append(word)
|
---|
133 | word = str(m.id)
|
---|
134 | if word[:n] == text:
|
---|
135 | matches.append(word)
|
---|
136 |
|
---|
137 | except Exception,e:
|
---|
138 | printErr(e)
|
---|
139 | if g_verbose:
|
---|
140 | traceback.print_exc()
|
---|
141 |
|
---|
142 | return matches
|
---|
143 |
|
---|
144 | def autoCompletion(commands, ctx):
|
---|
145 | if not g_hasreadline:
|
---|
146 | return
|
---|
147 |
|
---|
148 | comps = {}
|
---|
149 | for (k,v) in commands.items():
|
---|
150 | comps[k] = None
|
---|
151 | completer = CompleterNG(comps, ctx)
|
---|
152 | readline.set_completer(completer.complete)
|
---|
153 | delims = readline.get_completer_delims()
|
---|
154 | readline.set_completer_delims(re.sub("[\\./-]", "", delims)) # remove some of the delimiters
|
---|
155 | readline.parse_and_bind("set editing-mode emacs")
|
---|
156 | # OSX need it
|
---|
157 | if platform.system() == 'Darwin':
|
---|
158 | # see http://www.certif.com/spec_help/readline.html
|
---|
159 | readline.parse_and_bind ("bind ^I rl_complete")
|
---|
160 | readline.parse_and_bind ("bind ^W ed-delete-prev-word")
|
---|
161 | # Doesn't work well
|
---|
162 | # readline.parse_and_bind ("bind ^R em-inc-search-prev")
|
---|
163 | readline.parse_and_bind("tab: complete")
|
---|
164 |
|
---|
165 |
|
---|
166 | g_verbose = False
|
---|
167 |
|
---|
168 | def split_no_quotes(s):
|
---|
169 | return shlex.split(s)
|
---|
170 |
|
---|
171 | def progressBar(ctx,p,wait=1000):
|
---|
172 | try:
|
---|
173 | while not p.completed:
|
---|
174 | print "%s %%\r" %(colored(str(p.percent),'red')),
|
---|
175 | sys.stdout.flush()
|
---|
176 | p.waitForCompletion(wait)
|
---|
177 | ctx['global'].waitForEvents(0)
|
---|
178 | if int(p.resultCode) != 0:
|
---|
179 | reportError(ctx, p)
|
---|
180 | return 1
|
---|
181 | except KeyboardInterrupt:
|
---|
182 | print "Interrupted."
|
---|
183 | ctx['interrupt'] = True
|
---|
184 | if p.cancelable:
|
---|
185 | print "Canceling task..."
|
---|
186 | p.cancel()
|
---|
187 | return 0
|
---|
188 |
|
---|
189 | def printErr(ctx,e):
|
---|
190 | print colored(str(e), 'red')
|
---|
191 |
|
---|
192 | def reportError(ctx,progress):
|
---|
193 | ei = progress.errorInfo
|
---|
194 | if ei:
|
---|
195 | print colored("Error in %s: %s" %(ei.component, ei.text), 'red')
|
---|
196 |
|
---|
197 | def colCat(ctx,str):
|
---|
198 | return colored(str, 'magenta')
|
---|
199 |
|
---|
200 | def colVm(ctx,vm):
|
---|
201 | return colored(vm, 'blue')
|
---|
202 |
|
---|
203 | def colPath(ctx,p):
|
---|
204 | return colored(p, 'green')
|
---|
205 |
|
---|
206 | def colSize(ctx,m):
|
---|
207 | return colored(m, 'red')
|
---|
208 |
|
---|
209 | def colPci(ctx,vm):
|
---|
210 | return colored(vm, 'green')
|
---|
211 |
|
---|
212 | def colDev(ctx,vm):
|
---|
213 | return colored(vm, 'cyan')
|
---|
214 |
|
---|
215 | def colSizeM(ctx,m):
|
---|
216 | return colored(str(m)+'M', 'red')
|
---|
217 |
|
---|
218 | def createVm(ctx,name,kind,base):
|
---|
219 | mgr = ctx['mgr']
|
---|
220 | vb = ctx['vb']
|
---|
221 | mach = vb.createMachine(name, kind, base, "", False)
|
---|
222 | mach.saveSettings()
|
---|
223 | print "created machine with UUID",mach.id
|
---|
224 | vb.registerMachine(mach)
|
---|
225 | # update cache
|
---|
226 | getMachines(ctx, True)
|
---|
227 |
|
---|
228 | def removeVm(ctx,mach):
|
---|
229 | mgr = ctx['mgr']
|
---|
230 | vb = ctx['vb']
|
---|
231 | id = mach.id
|
---|
232 | print "removing machine ",mach.name,"with UUID",id
|
---|
233 | cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
|
---|
234 | mach = mach.unregister(ctx['global'].constants.CleanupMode_Full)
|
---|
235 | if mach:
|
---|
236 | mach.deleteSettings()
|
---|
237 | # update cache
|
---|
238 | getMachines(ctx, True)
|
---|
239 |
|
---|
240 | def startVm(ctx,mach,type):
|
---|
241 | mgr = ctx['mgr']
|
---|
242 | vb = ctx['vb']
|
---|
243 | perf = ctx['perf']
|
---|
244 | session = mgr.getSessionObject(vb)
|
---|
245 | progress = mach.launchVMProcess(session, type, "")
|
---|
246 | if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
|
---|
247 | # we ignore exceptions to allow starting VM even if
|
---|
248 | # perf collector cannot be started
|
---|
249 | if perf:
|
---|
250 | try:
|
---|
251 | perf.setup(['*'], [mach], 10, 15)
|
---|
252 | except Exception,e:
|
---|
253 | printErr(ctx, e)
|
---|
254 | if g_verbose:
|
---|
255 | traceback.print_exc()
|
---|
256 | # if session not opened, close doesn't make sense
|
---|
257 | session.unlockMachine()
|
---|
258 | else:
|
---|
259 | reportError(ctx,progress)
|
---|
260 |
|
---|
261 | class CachedMach:
|
---|
262 | def __init__(self, mach):
|
---|
263 | self.name = mach.name
|
---|
264 | self.id = mach.id
|
---|
265 |
|
---|
266 | def cacheMachines(ctx,list):
|
---|
267 | result = []
|
---|
268 | for m in list:
|
---|
269 | try:
|
---|
270 | elem = CachedMach(m)
|
---|
271 | result.append(elem)
|
---|
272 | except:
|
---|
273 | pass
|
---|
274 | return result
|
---|
275 |
|
---|
276 | def getMachines(ctx, invalidate = False, simple=False):
|
---|
277 | if ctx['vb'] is not None:
|
---|
278 | if ctx['_machlist'] is None or invalidate:
|
---|
279 | ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
|
---|
280 | ctx['_machlistsimple'] = cacheMachines(ctx,ctx['_machlist'])
|
---|
281 | if simple:
|
---|
282 | return ctx['_machlistsimple']
|
---|
283 | else:
|
---|
284 | return ctx['_machlist']
|
---|
285 | else:
|
---|
286 | return []
|
---|
287 |
|
---|
288 | def asState(var):
|
---|
289 | if var:
|
---|
290 | return colored('on', 'green')
|
---|
291 | else:
|
---|
292 | return colored('off', 'green')
|
---|
293 |
|
---|
294 | def asFlag(var):
|
---|
295 | if var:
|
---|
296 | return 'yes'
|
---|
297 | else:
|
---|
298 | return 'no'
|
---|
299 |
|
---|
300 | def perfStats(ctx,mach):
|
---|
301 | if not ctx['perf']:
|
---|
302 | return
|
---|
303 | for metric in ctx['perf'].query(["*"], [mach]):
|
---|
304 | print metric['name'], metric['values_as_string']
|
---|
305 |
|
---|
306 | def guestExec(ctx, machine, console, cmds):
|
---|
307 | exec cmds
|
---|
308 |
|
---|
309 | def printMouseEvent(ctx, mev):
|
---|
310 | print "Mouse : absolute=%d x=%d y=%d z=%d buttons=%x" %(mev.absolute, mev.x, mev.y, mev.z, mev.buttons)
|
---|
311 |
|
---|
312 | def printKbdEvent(ctx, kev):
|
---|
313 | print "Kbd: ", ctx['global'].getArray(kev, 'scancodes')
|
---|
314 |
|
---|
315 | def monitorSource(ctx, es, active, dur):
|
---|
316 | def handleEventImpl(ev):
|
---|
317 | type = ev.type
|
---|
318 | print "got event: %s %s" %(str(type), asEnumElem(ctx, 'VBoxEventType', type))
|
---|
319 | if type == ctx['global'].constants.VBoxEventType_OnMachineStateChanged:
|
---|
320 | scev = ctx['global'].queryInterface(ev, 'IMachineStateChangedEvent')
|
---|
321 | if scev:
|
---|
322 | print "machine state event: mach=%s state=%s" %(scev.machineId, scev.state)
|
---|
323 | elif type == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged:
|
---|
324 | gpcev = ctx['global'].queryInterface(ev, 'IGuestPropertyChangedEvent')
|
---|
325 | if gpcev:
|
---|
326 | print "guest property change: name=%s value=%s" %(gpcev.name, gpcev.value)
|
---|
327 | elif type == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged:
|
---|
328 | psev = ctx['global'].queryInterface(ev, 'IMousePointerShapeChangedEvent')
|
---|
329 | if psev:
|
---|
330 | shape = ctx['global'].getArray(psev, 'shape')
|
---|
331 | if shape is None:
|
---|
332 | print "pointer shape event - empty shape"
|
---|
333 | else:
|
---|
334 | print "pointer shape event: w=%d h=%d shape len=%d" %(psev.width, psev.height, len(shape))
|
---|
335 | elif type == ctx['global'].constants.VBoxEventType_OnGuestMouse:
|
---|
336 | mev = ctx['global'].queryInterface(ev, 'IGuestMouseEvent')
|
---|
337 | if mev:
|
---|
338 | printMouseEvent(ctx, mev)
|
---|
339 | elif type == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
|
---|
340 | kev = ctx['global'].queryInterface(ev, 'IGuestKeyboardEvent')
|
---|
341 | if kev:
|
---|
342 | printKbdEvent(ctx, kev)
|
---|
343 |
|
---|
344 | class EventListener:
|
---|
345 | def __init__(self, arg):
|
---|
346 | pass
|
---|
347 |
|
---|
348 | def handleEvent(self, ev):
|
---|
349 | try:
|
---|
350 | # a bit convoluted QI to make it work with MS COM
|
---|
351 | handleEventImpl(ctx['global'].queryInterface(ev, 'IEvent'))
|
---|
352 | except:
|
---|
353 | traceback.print_exc()
|
---|
354 | pass
|
---|
355 |
|
---|
356 | if active:
|
---|
357 | listener = ctx['global'].createListener(EventListener)
|
---|
358 | else:
|
---|
359 | listener = es.createListener()
|
---|
360 | registered = False
|
---|
361 | if dur == -1:
|
---|
362 | # not infinity, but close enough
|
---|
363 | dur = 100000
|
---|
364 | try:
|
---|
365 | es.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], active)
|
---|
366 | registered = True
|
---|
367 | end = time.time() + dur
|
---|
368 | while time.time() < end:
|
---|
369 | if active:
|
---|
370 | ctx['global'].waitForEvents(500)
|
---|
371 | else:
|
---|
372 | ev = es.getEvent(listener, 500)
|
---|
373 | if ev:
|
---|
374 | handleEventImpl(ev)
|
---|
375 | # otherwise waitable events will leak (active listeners ACK automatically)
|
---|
376 | es.eventProcessed(listener, ev)
|
---|
377 | # We need to catch all exceptions here, otherwise listener will never be unregistered
|
---|
378 | except:
|
---|
379 | traceback.print_exc()
|
---|
380 | pass
|
---|
381 | if listener and registered:
|
---|
382 | es.unregisterListener(listener)
|
---|
383 |
|
---|
384 |
|
---|
385 | tsLast = 0
|
---|
386 | def recordDemo(ctx, console, file, dur):
|
---|
387 | demo = open(file, 'w')
|
---|
388 | header="VM="+console.machine.name+"\n"
|
---|
389 | demo.write(header)
|
---|
390 |
|
---|
391 | global tsLast
|
---|
392 | tsLast = time.time()
|
---|
393 |
|
---|
394 | def stamp():
|
---|
395 | global tsLast
|
---|
396 | tsCur = time.time()
|
---|
397 | rv = int((tsCur-tsLast)*1000)
|
---|
398 | tsLast = tsCur
|
---|
399 | return rv
|
---|
400 |
|
---|
401 | def handleEventImpl(ev):
|
---|
402 | type = ev.type
|
---|
403 | #print "got event: %s %s" %(str(type), asEnumElem(ctx, 'VBoxEventType', type))
|
---|
404 | if type == ctx['global'].constants.VBoxEventType_OnGuestMouse:
|
---|
405 | mev = ctx['global'].queryInterface(ev, 'IGuestMouseEvent')
|
---|
406 | if mev:
|
---|
407 | l = "%d: m %d %d %d %d %d %d\n" %(stamp(), mev.absolute, mev.x, mev.y, mev.z, mev.w, mev.buttons)
|
---|
408 | demo.write(l)
|
---|
409 | elif type == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
|
---|
410 | kev = ctx['global'].queryInterface(ev, 'IGuestKeyboardEvent')
|
---|
411 | if kev:
|
---|
412 | l = "%d: k %s\n" %(stamp(), str(ctx['global'].getArray(kev, 'scancodes')))
|
---|
413 | demo.write(l)
|
---|
414 |
|
---|
415 | listener = console.eventSource.createListener()
|
---|
416 | registered = False
|
---|
417 | # we create an aggregated event source to listen for multiple event sources (keyboard and mouse in our case)
|
---|
418 | agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource])
|
---|
419 | demo = open(file, 'w')
|
---|
420 | header="VM="+console.machine.name+"\n"
|
---|
421 | demo.write(header)
|
---|
422 | if dur == -1:
|
---|
423 | # not infinity, but close enough
|
---|
424 | dur = 100000
|
---|
425 | try:
|
---|
426 | agg.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], False)
|
---|
427 | registered = True
|
---|
428 | end = time.time() + dur
|
---|
429 | while time.time() < end:
|
---|
430 | ev = agg.getEvent(listener, 1000)
|
---|
431 | if ev:
|
---|
432 | handleEventImpl(ev)
|
---|
433 | # keyboard/mouse events aren't waitable, so no need for eventProcessed
|
---|
434 | # We need to catch all exceptions here, otherwise listener will never be unregistered
|
---|
435 | except:
|
---|
436 | traceback.print_exc()
|
---|
437 | pass
|
---|
438 | demo.close()
|
---|
439 | if listener and registered:
|
---|
440 | agg.unregisterListener(listener)
|
---|
441 |
|
---|
442 |
|
---|
443 | def playbackDemo(ctx, console, file, dur):
|
---|
444 | demo = open(file, 'r')
|
---|
445 |
|
---|
446 | if dur == -1:
|
---|
447 | # not infinity, but close enough
|
---|
448 | dur = 100000
|
---|
449 |
|
---|
450 | header = demo.readline()
|
---|
451 | print "Header is", header
|
---|
452 | basere = re.compile(r'(?P<s>\d+): (?P<t>[km]) (?P<p>.*)')
|
---|
453 | mre = re.compile(r'(?P<a>\d+) (?P<x>-*\d+) (?P<y>-*\d+) (?P<z>-*\d+) (?P<w>-*\d+) (?P<b>-*\d+)')
|
---|
454 | kre = re.compile(r'\d+')
|
---|
455 |
|
---|
456 | kbd = console.keyboard
|
---|
457 | mouse = console.mouse
|
---|
458 |
|
---|
459 | try:
|
---|
460 | end = time.time() + dur
|
---|
461 | for line in demo:
|
---|
462 | if time.time() > end:
|
---|
463 | break
|
---|
464 | m = basere.search(line)
|
---|
465 | if m is None:
|
---|
466 | continue
|
---|
467 |
|
---|
468 | dict = m.groupdict()
|
---|
469 | stamp = dict['s']
|
---|
470 | params = dict['p']
|
---|
471 | type = dict['t']
|
---|
472 |
|
---|
473 | time.sleep(float(stamp)/1000)
|
---|
474 |
|
---|
475 | if type == 'k':
|
---|
476 | codes=kre.findall(params)
|
---|
477 | #print "KBD:",codes
|
---|
478 | kbd.putScancodes(codes)
|
---|
479 | elif type == 'm':
|
---|
480 | mm = mre.search(params)
|
---|
481 | if mm is not None:
|
---|
482 | mdict = mm.groupdict()
|
---|
483 | if mdict['a'] == '1':
|
---|
484 | # absolute
|
---|
485 | #print "MA: ",mdict['x'],mdict['y'],mdict['z'],mdict['b']
|
---|
486 | mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))
|
---|
487 | else:
|
---|
488 | #print "MR: ",mdict['x'],mdict['y'],mdict['b']
|
---|
489 | mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))
|
---|
490 |
|
---|
491 | # We need to catch all exceptions here, to close file
|
---|
492 | except KeyboardInterrupt:
|
---|
493 | ctx['interrupt'] = True
|
---|
494 | except:
|
---|
495 | traceback.print_exc()
|
---|
496 | pass
|
---|
497 | demo.close()
|
---|
498 |
|
---|
499 |
|
---|
500 | def takeScreenshotOld(ctx,console,args):
|
---|
501 | from PIL import Image
|
---|
502 | display = console.display
|
---|
503 | if len(args) > 0:
|
---|
504 | f = args[0]
|
---|
505 | else:
|
---|
506 | f = "/tmp/screenshot.png"
|
---|
507 | if len(args) > 3:
|
---|
508 | screen = int(args[3])
|
---|
509 | else:
|
---|
510 | screen = 0
|
---|
511 | (fbw, fbh, fbbpp) = display.getScreenResolution(screen)
|
---|
512 | if len(args) > 1:
|
---|
513 | w = int(args[1])
|
---|
514 | else:
|
---|
515 | w = fbw
|
---|
516 | if len(args) > 2:
|
---|
517 | h = int(args[2])
|
---|
518 | else:
|
---|
519 | h = fbh
|
---|
520 |
|
---|
521 | print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
|
---|
522 | data = display.takeScreenShotToArray(screen, w,h)
|
---|
523 | size = (w,h)
|
---|
524 | mode = "RGBA"
|
---|
525 | im = Image.frombuffer(mode, size, str(data), "raw", mode, 0, 1)
|
---|
526 | im.save(f, "PNG")
|
---|
527 |
|
---|
528 | def takeScreenshot(ctx,console,args):
|
---|
529 | display = console.display
|
---|
530 | if len(args) > 0:
|
---|
531 | f = args[0]
|
---|
532 | else:
|
---|
533 | f = "/tmp/screenshot.png"
|
---|
534 | if len(args) > 3:
|
---|
535 | screen = int(args[3])
|
---|
536 | else:
|
---|
537 | screen = 0
|
---|
538 | (fbw, fbh, fbbpp) = display.getScreenResolution(screen)
|
---|
539 | if len(args) > 1:
|
---|
540 | w = int(args[1])
|
---|
541 | else:
|
---|
542 | w = fbw
|
---|
543 | if len(args) > 2:
|
---|
544 | h = int(args[2])
|
---|
545 | else:
|
---|
546 | h = fbh
|
---|
547 |
|
---|
548 | print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
|
---|
549 | data = display.takeScreenShotPNGToArray(screen, w,h)
|
---|
550 | size = (w,h)
|
---|
551 | file = open(f, 'wb')
|
---|
552 | file.write(data)
|
---|
553 | file.close()
|
---|
554 |
|
---|
555 | def teleport(ctx,session,console,args):
|
---|
556 | if args[0].find(":") == -1:
|
---|
557 | print "Use host:port format for teleport target"
|
---|
558 | return
|
---|
559 | (host,port) = args[0].split(":")
|
---|
560 | if len(args) > 1:
|
---|
561 | passwd = args[1]
|
---|
562 | else:
|
---|
563 | passwd = ""
|
---|
564 |
|
---|
565 | if len(args) > 2:
|
---|
566 | maxDowntime = int(args[2])
|
---|
567 | else:
|
---|
568 | maxDowntime = 250
|
---|
569 |
|
---|
570 | port = int(port)
|
---|
571 | print "Teleporting to %s:%d..." %(host,port)
|
---|
572 | progress = console.teleport(host, port, passwd, maxDowntime)
|
---|
573 | if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
|
---|
574 | print "Success!"
|
---|
575 | else:
|
---|
576 | reportError(ctx,progress)
|
---|
577 |
|
---|
578 |
|
---|
579 | def guestStats(ctx,console,args):
|
---|
580 | guest = console.guest
|
---|
581 | # we need to set up guest statistics
|
---|
582 | if len(args) > 0 :
|
---|
583 | update = args[0]
|
---|
584 | else:
|
---|
585 | update = 1
|
---|
586 | if guest.statisticsUpdateInterval != update:
|
---|
587 | guest.statisticsUpdateInterval = update
|
---|
588 | try:
|
---|
589 | time.sleep(float(update)+0.1)
|
---|
590 | except:
|
---|
591 | # to allow sleep interruption
|
---|
592 | pass
|
---|
593 | all_stats = ctx['const'].all_values('GuestStatisticType')
|
---|
594 | cpu = 0
|
---|
595 | for s in all_stats.keys():
|
---|
596 | try:
|
---|
597 | val = guest.getStatistic( cpu, all_stats[s])
|
---|
598 | print "%s: %d" %(s, val)
|
---|
599 | except:
|
---|
600 | # likely not implemented
|
---|
601 | pass
|
---|
602 |
|
---|
603 | def plugCpu(ctx,machine,session,args):
|
---|
604 | cpu = int(args[0])
|
---|
605 | print "Adding CPU %d..." %(cpu)
|
---|
606 | machine.hotPlugCPU(cpu)
|
---|
607 |
|
---|
608 | def unplugCpu(ctx,machine,session,args):
|
---|
609 | cpu = int(args[0])
|
---|
610 | print "Removing CPU %d..." %(cpu)
|
---|
611 | machine.hotUnplugCPU(cpu)
|
---|
612 |
|
---|
613 | def mountIso(ctx,machine,session,args):
|
---|
614 | machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
|
---|
615 | machine.saveSettings()
|
---|
616 |
|
---|
617 | def cond(c,v1,v2):
|
---|
618 | if c:
|
---|
619 | return v1
|
---|
620 | else:
|
---|
621 | return v2
|
---|
622 |
|
---|
623 | def printHostUsbDev(ctx,ud):
|
---|
624 | 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))
|
---|
625 |
|
---|
626 | def printUsbDev(ctx,ud):
|
---|
627 | print " %s: %s (vendorId=%d productId=%d serial=%s)" %(ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber)
|
---|
628 |
|
---|
629 | def printSf(ctx,sf):
|
---|
630 | print " name=%s host=%s %s %s" %(sf.name, colPath(ctx,sf.hostPath), cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))
|
---|
631 |
|
---|
632 | def ginfo(ctx,console, args):
|
---|
633 | guest = console.guest
|
---|
634 | if guest.additionsActive:
|
---|
635 | vers = int(str(guest.additionsVersion))
|
---|
636 | print "Additions active, version %d.%d" %(vers >> 16, vers & 0xffff)
|
---|
637 | print "Support seamless: %s" %(asFlag(guest.supportsSeamless))
|
---|
638 | print "Support graphics: %s" %(asFlag(guest.supportsGraphics))
|
---|
639 | print "Baloon size: %d" %(guest.memoryBalloonSize)
|
---|
640 | print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
|
---|
641 | else:
|
---|
642 | print "No additions"
|
---|
643 | usbs = ctx['global'].getArray(console, 'USBDevices')
|
---|
644 | print "Attached USB:"
|
---|
645 | for ud in usbs:
|
---|
646 | printUsbDev(ctx,ud)
|
---|
647 | rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
|
---|
648 | print "Remote USB:"
|
---|
649 | for ud in rusbs:
|
---|
650 | printHostUsbDev(ctx,ud)
|
---|
651 | print "Transient shared folders:"
|
---|
652 | sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
|
---|
653 | for sf in sfs:
|
---|
654 | printSf(ctx,sf)
|
---|
655 |
|
---|
656 | def cmdExistingVm(ctx,mach,cmd,args):
|
---|
657 | session = None
|
---|
658 | try:
|
---|
659 | vb = ctx['vb']
|
---|
660 | session = ctx['mgr'].getSessionObject(vb)
|
---|
661 | mach.lockMachine(session, ctx['global'].constants.LockType_Shared)
|
---|
662 | except Exception,e:
|
---|
663 | printErr(ctx, "Session to '%s' not open: %s" %(mach.name,str(e)))
|
---|
664 | if g_verbose:
|
---|
665 | traceback.print_exc()
|
---|
666 | return
|
---|
667 | if session.state != ctx['const'].SessionState_Locked:
|
---|
668 | print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
|
---|
669 | session.unlockMachine()
|
---|
670 | return
|
---|
671 | # this could be an example how to handle local only (i.e. unavailable
|
---|
672 | # in Webservices) functionality
|
---|
673 | if ctx['remote'] and cmd == 'some_local_only_command':
|
---|
674 | print 'Trying to use local only functionality, ignored'
|
---|
675 | session.unlockMachine()
|
---|
676 | return
|
---|
677 | console=session.console
|
---|
678 | ops={'pause': lambda: console.pause(),
|
---|
679 | 'resume': lambda: console.resume(),
|
---|
680 | 'powerdown': lambda: console.powerDown(),
|
---|
681 | 'powerbutton': lambda: console.powerButton(),
|
---|
682 | 'stats': lambda: perfStats(ctx, mach),
|
---|
683 | 'guest': lambda: guestExec(ctx, mach, console, args),
|
---|
684 | 'ginfo': lambda: ginfo(ctx, console, args),
|
---|
685 | 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
|
---|
686 | 'save': lambda: progressBar(ctx,console.saveState()),
|
---|
687 | 'screenshot': lambda: takeScreenshot(ctx,console,args),
|
---|
688 | 'teleport': lambda: teleport(ctx,session,console,args),
|
---|
689 | 'gueststats': lambda: guestStats(ctx, console, args),
|
---|
690 | 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
|
---|
691 | 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
|
---|
692 | 'mountiso': lambda: mountIso(ctx, session.machine, session, args),
|
---|
693 | }
|
---|
694 | try:
|
---|
695 | ops[cmd]()
|
---|
696 | except KeyboardInterrupt:
|
---|
697 | ctx['interrupt'] = True
|
---|
698 | except Exception, e:
|
---|
699 | printErr(ctx,e)
|
---|
700 | if g_verbose:
|
---|
701 | traceback.print_exc()
|
---|
702 |
|
---|
703 | session.unlockMachine()
|
---|
704 |
|
---|
705 |
|
---|
706 | def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
|
---|
707 | session = ctx['global'].openMachineSession(mach, True)
|
---|
708 | mach = session.machine
|
---|
709 | try:
|
---|
710 | cmd(ctx, mach, args)
|
---|
711 | except Exception, e:
|
---|
712 | save = False
|
---|
713 | printErr(ctx,e)
|
---|
714 | if g_verbose:
|
---|
715 | traceback.print_exc()
|
---|
716 | if save:
|
---|
717 | try:
|
---|
718 | mach.saveSettings()
|
---|
719 | except Exception, e:
|
---|
720 | printErr(ctx,e)
|
---|
721 | if g_verbose:
|
---|
722 | traceback.print_exc()
|
---|
723 | ctx['global'].closeMachineSession(session)
|
---|
724 |
|
---|
725 |
|
---|
726 | def cmdAnyVm(ctx,mach,cmd, args=[],save=False):
|
---|
727 | session = ctx['global'].openMachineSession(mach)
|
---|
728 | mach = session.machine
|
---|
729 | try:
|
---|
730 | cmd(ctx, mach, session.console, args)
|
---|
731 | except Exception, e:
|
---|
732 | save = False;
|
---|
733 | printErr(ctx,e)
|
---|
734 | if g_verbose:
|
---|
735 | traceback.print_exc()
|
---|
736 | if save:
|
---|
737 | mach.saveSettings()
|
---|
738 | ctx['global'].closeMachineSession(session)
|
---|
739 |
|
---|
740 | def machById(ctx,id):
|
---|
741 | try:
|
---|
742 | mach = ctx['vb'].getMachine(id)
|
---|
743 | except:
|
---|
744 | mach = ctx['vb'].findMachine(id)
|
---|
745 | return mach
|
---|
746 |
|
---|
747 | class XPathNode:
|
---|
748 | def __init__(self, parent, obj, type):
|
---|
749 | self.parent = parent
|
---|
750 | self.obj = obj
|
---|
751 | self.type = type
|
---|
752 | def lookup(self, subpath):
|
---|
753 | children = self.enum()
|
---|
754 | matches = []
|
---|
755 | for e in children:
|
---|
756 | if e.matches(subpath):
|
---|
757 | matches.append(e)
|
---|
758 | return matches
|
---|
759 | def enum(self):
|
---|
760 | return []
|
---|
761 | def matches(self,subexp):
|
---|
762 | if subexp == self.type:
|
---|
763 | return True
|
---|
764 | if not subexp.startswith(self.type):
|
---|
765 | return False
|
---|
766 | m = re.search(r"@(?P<a>\w+)=(?P<v>[^\'\[\]]+)", subexp)
|
---|
767 | matches = False
|
---|
768 | try:
|
---|
769 | if m is not None:
|
---|
770 | dict = m.groupdict()
|
---|
771 | attr = dict['a']
|
---|
772 | val = dict['v']
|
---|
773 | matches = (str(getattr(self.obj, attr)) == val)
|
---|
774 | except:
|
---|
775 | pass
|
---|
776 | return matches
|
---|
777 | def apply(self, cmd):
|
---|
778 | exec(cmd, {'obj':self.obj,'node':self,'ctx':self.getCtx()}, {})
|
---|
779 | def getCtx(self):
|
---|
780 | if hasattr(self,'ctx'):
|
---|
781 | return self.ctx
|
---|
782 | return self.parent.getCtx()
|
---|
783 |
|
---|
784 | class XPathNodeHolder(XPathNode):
|
---|
785 | def __init__(self, parent, obj, attr, heldClass, xpathname):
|
---|
786 | XPathNode.__init__(self, parent, obj, 'hld '+xpathname)
|
---|
787 | self.attr = attr
|
---|
788 | self.heldClass = heldClass
|
---|
789 | self.xpathname = xpathname
|
---|
790 | def enum(self):
|
---|
791 | children = []
|
---|
792 | for n in self.getCtx()['global'].getArray(self.obj, self.attr):
|
---|
793 | node = self.heldClass(self, n)
|
---|
794 | children.append(node)
|
---|
795 | return children
|
---|
796 | def matches(self,subexp):
|
---|
797 | return subexp == self.xpathname
|
---|
798 |
|
---|
799 | class XPathNodeValue(XPathNode):
|
---|
800 | def __init__(self, parent, obj, xpathname):
|
---|
801 | XPathNode.__init__(self, parent, obj, 'val '+xpathname)
|
---|
802 | self.xpathname = xpathname
|
---|
803 | def matches(self,subexp):
|
---|
804 | return subexp == self.xpathname
|
---|
805 |
|
---|
806 | class XPathNodeHolderVM(XPathNodeHolder):
|
---|
807 | def __init__(self, parent, vbox):
|
---|
808 | XPathNodeHolder.__init__(self, parent, vbox, 'machines', XPathNodeVM, 'vms')
|
---|
809 |
|
---|
810 | class XPathNodeVM(XPathNode):
|
---|
811 | def __init__(self, parent, obj):
|
---|
812 | XPathNode.__init__(self, parent, obj, 'vm')
|
---|
813 | #def matches(self,subexp):
|
---|
814 | # return subexp=='vm'
|
---|
815 | def enum(self):
|
---|
816 | return [XPathNodeHolderNIC(self, self.obj),
|
---|
817 | XPathNodeValue(self, self.obj.BIOSSettings, 'bios'),
|
---|
818 | XPathNodeValue(self, self.obj.USBController, 'usb')]
|
---|
819 |
|
---|
820 | class XPathNodeHolderNIC(XPathNodeHolder):
|
---|
821 | def __init__(self, parent, mach):
|
---|
822 | XPathNodeHolder.__init__(self, parent, mach, 'nics', XPathNodeVM, 'nics')
|
---|
823 | self.maxNic = self.getCtx()['vb'].systemProperties.networkAdapterCount
|
---|
824 | def enum(self):
|
---|
825 | children = []
|
---|
826 | for i in range(0, self.maxNic):
|
---|
827 | node = XPathNodeNIC(self, self.obj.getNetworkAdapter(i))
|
---|
828 | children.append(node)
|
---|
829 | return children
|
---|
830 |
|
---|
831 | class XPathNodeNIC(XPathNode):
|
---|
832 | def __init__(self, parent, obj):
|
---|
833 | XPathNode.__init__(self, parent, obj, 'nic')
|
---|
834 | def matches(self,subexp):
|
---|
835 | return subexp=='nic'
|
---|
836 |
|
---|
837 | class XPathNodeRoot(XPathNode):
|
---|
838 | def __init__(self, ctx):
|
---|
839 | XPathNode.__init__(self, None, None, 'root')
|
---|
840 | self.ctx = ctx
|
---|
841 | def enum(self):
|
---|
842 | return [XPathNodeHolderVM(self, self.ctx['vb'])]
|
---|
843 | def matches(self,subexp):
|
---|
844 | return True
|
---|
845 |
|
---|
846 | def eval_xpath(ctx,scope):
|
---|
847 | pathnames = scope.split("/")[2:]
|
---|
848 | nodes = [XPathNodeRoot(ctx)]
|
---|
849 | for p in pathnames:
|
---|
850 | seen = []
|
---|
851 | while len(nodes) > 0:
|
---|
852 | n = nodes.pop()
|
---|
853 | seen.append(n)
|
---|
854 | for s in seen:
|
---|
855 | matches = s.lookup(p)
|
---|
856 | for m in matches:
|
---|
857 | nodes.append(m)
|
---|
858 | if len(nodes) == 0:
|
---|
859 | break
|
---|
860 | return nodes
|
---|
861 |
|
---|
862 | def argsToMach(ctx,args):
|
---|
863 | if len(args) < 2:
|
---|
864 | print "usage: %s [vmname|uuid]" %(args[0])
|
---|
865 | return None
|
---|
866 | id = args[1]
|
---|
867 | m = machById(ctx, id)
|
---|
868 | if m == None:
|
---|
869 | print "Machine '%s' is unknown, use list command to find available machines" %(id)
|
---|
870 | return m
|
---|
871 |
|
---|
872 | def helpSingleCmd(cmd,h,sp):
|
---|
873 | if sp != 0:
|
---|
874 | spec = " [ext from "+sp+"]"
|
---|
875 | else:
|
---|
876 | spec = ""
|
---|
877 | print " %s: %s%s" %(colored(cmd,'blue'),h,spec)
|
---|
878 |
|
---|
879 | def helpCmd(ctx, args):
|
---|
880 | if len(args) == 1:
|
---|
881 | print "Help page:"
|
---|
882 | names = commands.keys()
|
---|
883 | names.sort()
|
---|
884 | for i in names:
|
---|
885 | helpSingleCmd(i, commands[i][0], commands[i][2])
|
---|
886 | else:
|
---|
887 | cmd = args[1]
|
---|
888 | c = commands.get(cmd)
|
---|
889 | if c == None:
|
---|
890 | print "Command '%s' not known" %(cmd)
|
---|
891 | else:
|
---|
892 | helpSingleCmd(cmd, c[0], c[2])
|
---|
893 | return 0
|
---|
894 |
|
---|
895 | def asEnumElem(ctx,enum,elem):
|
---|
896 | all = ctx['const'].all_values(enum)
|
---|
897 | for e in all.keys():
|
---|
898 | if str(elem) == str(all[e]):
|
---|
899 | return colored(e, 'green')
|
---|
900 | return colored("<unknown>", 'green')
|
---|
901 |
|
---|
902 | def enumFromString(ctx,enum,str):
|
---|
903 | all = ctx['const'].all_values(enum)
|
---|
904 | return all.get(str, None)
|
---|
905 |
|
---|
906 | def listCmd(ctx, args):
|
---|
907 | for m in getMachines(ctx, True):
|
---|
908 | try:
|
---|
909 | if m.teleporterEnabled:
|
---|
910 | tele = "[T] "
|
---|
911 | else:
|
---|
912 | tele = " "
|
---|
913 | 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))
|
---|
914 | except Exception, e:
|
---|
915 | printErr(ctx,e)
|
---|
916 | if g_verbose:
|
---|
917 | traceback.print_exc()
|
---|
918 | return 0
|
---|
919 |
|
---|
920 | def infoCmd(ctx,args):
|
---|
921 | if (len(args) < 2):
|
---|
922 | print "usage: info [vmname|uuid]"
|
---|
923 | return 0
|
---|
924 | mach = argsToMach(ctx,args)
|
---|
925 | if mach == None:
|
---|
926 | return 0
|
---|
927 | os = ctx['vb'].getGuestOSType(mach.OSTypeId)
|
---|
928 | print " One can use setvar <mach> <var> <value> to change variable, using name in []."
|
---|
929 | print " Name [name]: %s" %(colVm(ctx,mach.name))
|
---|
930 | print " Description [description]: %s" %(mach.description)
|
---|
931 | print " ID [n/a]: %s" %(mach.id)
|
---|
932 | print " OS Type [via OSTypeId]: %s" %(os.description)
|
---|
933 | print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
|
---|
934 | print
|
---|
935 | print " CPUs [CPUCount]: %d" %(mach.CPUCount)
|
---|
936 | print " RAM [memorySize]: %dM" %(mach.memorySize)
|
---|
937 | print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
|
---|
938 | print " Monitors [monitorCount]: %d" %(mach.monitorCount)
|
---|
939 | print " Chipset [chipsetType]: %s (%s)" %(asEnumElem(ctx,"ChipsetType", mach.chipsetType), mach.chipsetType)
|
---|
940 | print
|
---|
941 | print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
|
---|
942 | print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
|
---|
943 | print
|
---|
944 | if mach.teleporterEnabled:
|
---|
945 | print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
|
---|
946 | print
|
---|
947 | bios = mach.BIOSSettings
|
---|
948 | print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
|
---|
949 | print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
|
---|
950 | hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
|
---|
951 | print " Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
|
---|
952 | hwVirtVPID = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID)
|
---|
953 | print " VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
|
---|
954 | hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging)
|
---|
955 | print " Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
|
---|
956 |
|
---|
957 | print " Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
|
---|
958 | print " Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
|
---|
959 |
|
---|
960 | print " Use universal time [RTCUseUTC]: %s" %(asState(mach.RTCUseUTC))
|
---|
961 | print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
|
---|
962 | if mach.audioAdapter.enabled:
|
---|
963 | print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
|
---|
964 | if mach.USBController.enabled:
|
---|
965 | print " USB [via USBController]: high speed %s" %(asState(mach.USBController.enabledEhci))
|
---|
966 | print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
|
---|
967 |
|
---|
968 | print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
|
---|
969 | print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
|
---|
970 | print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
|
---|
971 | # OSE has no VRDE
|
---|
972 | try:
|
---|
973 | print " VRDE server [VRDEServer.enabled]: %s" %(asState(mach.VRDEServer.enabled))
|
---|
974 | except:
|
---|
975 | pass
|
---|
976 | print
|
---|
977 | print colCat(ctx," I/O subsystem info:")
|
---|
978 | print " Cache enabled [ioCacheEnabled]: %s" %(asState(mach.ioCacheEnabled))
|
---|
979 | print " Cache size [ioCacheSize]: %dM" %(mach.ioCacheSize)
|
---|
980 |
|
---|
981 | controllers = ctx['global'].getArray(mach, 'storageControllers')
|
---|
982 | if controllers:
|
---|
983 | print
|
---|
984 | print colCat(ctx," Controllers:")
|
---|
985 | for controller in controllers:
|
---|
986 | print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
|
---|
987 |
|
---|
988 | attaches = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
989 | if attaches:
|
---|
990 | print
|
---|
991 | print colCat(ctx," Media:")
|
---|
992 | for a in attaches:
|
---|
993 | print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
|
---|
994 | m = a.medium
|
---|
995 | if a.type == ctx['global'].constants.DeviceType_HardDisk:
|
---|
996 | print " HDD:"
|
---|
997 | print " Id: %s" %(m.id)
|
---|
998 | print " Location: %s" %(colPath(ctx,m.location))
|
---|
999 | print " Name: %s" %(m.name)
|
---|
1000 | print " Format: %s" %(m.format)
|
---|
1001 |
|
---|
1002 | if a.type == ctx['global'].constants.DeviceType_DVD:
|
---|
1003 | print " DVD:"
|
---|
1004 | if m:
|
---|
1005 | print " Id: %s" %(m.id)
|
---|
1006 | print " Name: %s" %(m.name)
|
---|
1007 | if m.hostDrive:
|
---|
1008 | print " Host DVD %s" %(colPath(ctx,m.location))
|
---|
1009 | if a.passthrough:
|
---|
1010 | print " [passthrough mode]"
|
---|
1011 | else:
|
---|
1012 | print " Virtual image at %s" %(colPath(ctx,m.location))
|
---|
1013 | print " Size: %s" %(m.size)
|
---|
1014 |
|
---|
1015 | if a.type == ctx['global'].constants.DeviceType_Floppy:
|
---|
1016 | print " Floppy:"
|
---|
1017 | if m:
|
---|
1018 | print " Id: %s" %(m.id)
|
---|
1019 | print " Name: %s" %(m.name)
|
---|
1020 | if m.hostDrive:
|
---|
1021 | print " Host floppy %s" %(colPath(ctx,m.location))
|
---|
1022 | else:
|
---|
1023 | print " Virtual image at %s" %(colPath(ctx,m.location))
|
---|
1024 | print " Size: %s" %(m.size)
|
---|
1025 |
|
---|
1026 | print
|
---|
1027 | print colCat(ctx," Shared folders:")
|
---|
1028 | for sf in ctx['global'].getArray(mach, 'sharedFolders'):
|
---|
1029 | printSf(ctx,sf)
|
---|
1030 |
|
---|
1031 | return 0
|
---|
1032 |
|
---|
1033 | def startCmd(ctx, args):
|
---|
1034 | if len(args) < 2:
|
---|
1035 | print "usage: start name <frontend>"
|
---|
1036 | return 0
|
---|
1037 | mach = argsToMach(ctx,args)
|
---|
1038 | if mach == None:
|
---|
1039 | return 0
|
---|
1040 | if len(args) > 2:
|
---|
1041 | type = args[2]
|
---|
1042 | else:
|
---|
1043 | type = "gui"
|
---|
1044 | startVm(ctx, mach, type)
|
---|
1045 | return 0
|
---|
1046 |
|
---|
1047 | def createVmCmd(ctx, args):
|
---|
1048 | if (len(args) < 3 or len(args) > 4):
|
---|
1049 | print "usage: createvm name ostype <basefolder>"
|
---|
1050 | return 0
|
---|
1051 | name = args[1]
|
---|
1052 | oskind = args[2]
|
---|
1053 | if len(args) == 4:
|
---|
1054 | base = args[3]
|
---|
1055 | else:
|
---|
1056 | base = ''
|
---|
1057 | try:
|
---|
1058 | ctx['vb'].getGuestOSType(oskind)
|
---|
1059 | except Exception, e:
|
---|
1060 | print 'Unknown OS type:',oskind
|
---|
1061 | return 0
|
---|
1062 | createVm(ctx, name, oskind, base)
|
---|
1063 | return 0
|
---|
1064 |
|
---|
1065 | def ginfoCmd(ctx,args):
|
---|
1066 | if (len(args) < 2):
|
---|
1067 | print "usage: ginfo [vmname|uuid]"
|
---|
1068 | return 0
|
---|
1069 | mach = argsToMach(ctx,args)
|
---|
1070 | if mach == None:
|
---|
1071 | return 0
|
---|
1072 | cmdExistingVm(ctx, mach, 'ginfo', '')
|
---|
1073 | return 0
|
---|
1074 |
|
---|
1075 | def execInGuest(ctx,console,args,env,user,passwd,tmo,inputPipe=None,outputPipe=None):
|
---|
1076 | if len(args) < 1:
|
---|
1077 | print "exec in guest needs at least program name"
|
---|
1078 | return
|
---|
1079 | guest = console.guest
|
---|
1080 | # shall contain program name as argv[0]
|
---|
1081 | gargs = args
|
---|
1082 | print "executing %s with args %s as %s" %(args[0], gargs, user)
|
---|
1083 | flags = 0
|
---|
1084 | if inputPipe is not None:
|
---|
1085 | flags = 1 # set WaitForProcessStartOnly
|
---|
1086 | print args[0]
|
---|
1087 | (progress, pid) = guest.executeProcess(args[0], flags, gargs, env, user, passwd, tmo)
|
---|
1088 | print "executed with pid %d" %(pid)
|
---|
1089 | if pid != 0:
|
---|
1090 | try:
|
---|
1091 | while True:
|
---|
1092 | if inputPipe is not None:
|
---|
1093 | indata = inputPipe(ctx)
|
---|
1094 | if indata is not None:
|
---|
1095 | write = len(indata)
|
---|
1096 | off = 0
|
---|
1097 | while write > 0:
|
---|
1098 | w = guest.setProcessInput(pid, 0, 10*1000, indata[off:])
|
---|
1099 | off = off + w
|
---|
1100 | write = write - w
|
---|
1101 | else:
|
---|
1102 | # EOF
|
---|
1103 | try:
|
---|
1104 | guest.setProcessInput(pid, 1, 10*1000, " ")
|
---|
1105 | except:
|
---|
1106 | pass
|
---|
1107 | data = guest.getProcessOutput(pid, 0, 10000, 4096)
|
---|
1108 | if data and len(data) > 0:
|
---|
1109 | sys.stdout.write(data)
|
---|
1110 | continue
|
---|
1111 | progress.waitForCompletion(100)
|
---|
1112 | ctx['global'].waitForEvents(0)
|
---|
1113 | data = guest.getProcessOutput(pid, 0, 0, 4096)
|
---|
1114 | if data and len(data) > 0:
|
---|
1115 | if outputPipe is not None:
|
---|
1116 | outputPipe(ctx,data)
|
---|
1117 | else:
|
---|
1118 | sys.stdout.write(data)
|
---|
1119 | continue
|
---|
1120 | if progress.completed:
|
---|
1121 | break
|
---|
1122 |
|
---|
1123 | except KeyboardInterrupt:
|
---|
1124 | print "Interrupted."
|
---|
1125 | ctx['interrupt'] = True
|
---|
1126 | if progress.cancelable:
|
---|
1127 | progress.cancel()
|
---|
1128 | (reason, code, flags) = guest.getProcessStatus(pid)
|
---|
1129 | print "Exit code: %d" %(code)
|
---|
1130 | return 0
|
---|
1131 | else:
|
---|
1132 | reportError(ctx, progress)
|
---|
1133 |
|
---|
1134 | def copyToGuest(ctx,console,args,user,passwd):
|
---|
1135 | src = args[0]
|
---|
1136 | dst = args[1]
|
---|
1137 | flags = 0
|
---|
1138 | print "Copying host %s to guest %s" %(src,dst)
|
---|
1139 | progress = console.guest.copyToGuest(src, dst, user, passwd, flags)
|
---|
1140 | progressBar(ctx, progress)
|
---|
1141 |
|
---|
1142 | def nh_raw_input(prompt=""):
|
---|
1143 | stream = sys.stdout
|
---|
1144 | prompt = str(prompt)
|
---|
1145 | if prompt:
|
---|
1146 | stream.write(prompt)
|
---|
1147 | line = sys.stdin.readline()
|
---|
1148 | if not line:
|
---|
1149 | raise EOFError
|
---|
1150 | if line[-1] == '\n':
|
---|
1151 | line = line[:-1]
|
---|
1152 | return line
|
---|
1153 |
|
---|
1154 |
|
---|
1155 | def getCred(ctx):
|
---|
1156 | import getpass
|
---|
1157 | user = getpass.getuser()
|
---|
1158 | user_inp = nh_raw_input("User (%s): " %(user))
|
---|
1159 | if len (user_inp) > 0:
|
---|
1160 | user = user_inp
|
---|
1161 | passwd = getpass.getpass()
|
---|
1162 |
|
---|
1163 | return (user,passwd)
|
---|
1164 |
|
---|
1165 | def gexecCmd(ctx,args):
|
---|
1166 | if (len(args) < 2):
|
---|
1167 | print "usage: gexec [vmname|uuid] command args"
|
---|
1168 | return 0
|
---|
1169 | mach = argsToMach(ctx,args)
|
---|
1170 | if mach == None:
|
---|
1171 | return 0
|
---|
1172 | gargs = args[2:]
|
---|
1173 | env = [] # ["DISPLAY=:0"]
|
---|
1174 | (user,passwd) = getCred(ctx)
|
---|
1175 | gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env,user,passwd,10000))
|
---|
1176 | cmdExistingVm(ctx, mach, 'guestlambda', gargs)
|
---|
1177 | return 0
|
---|
1178 |
|
---|
1179 | def gcopyCmd(ctx,args):
|
---|
1180 | if (len(args) < 2):
|
---|
1181 | print "usage: gcopy [vmname|uuid] host_path guest_path"
|
---|
1182 | return 0
|
---|
1183 | mach = argsToMach(ctx,args)
|
---|
1184 | if mach == None:
|
---|
1185 | return 0
|
---|
1186 | gargs = args[2:]
|
---|
1187 | (user,passwd) = getCred(ctx)
|
---|
1188 | gargs.insert(0, lambda ctx,mach,console,args: copyToGuest(ctx,console,args,user,passwd))
|
---|
1189 | cmdExistingVm(ctx, mach, 'guestlambda', gargs)
|
---|
1190 | return 0
|
---|
1191 |
|
---|
1192 | def readCmdPipe(ctx,hcmd):
|
---|
1193 | try:
|
---|
1194 | return ctx['process'].communicate()[0]
|
---|
1195 | except:
|
---|
1196 | return None
|
---|
1197 |
|
---|
1198 | def gpipeCmd(ctx,args):
|
---|
1199 | if (len(args) < 4):
|
---|
1200 | print "usage: gpipe [vmname|uuid] hostProgram guestProgram, such as gpipe linux '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'"
|
---|
1201 | return 0
|
---|
1202 | mach = argsToMach(ctx,args)
|
---|
1203 | if mach == None:
|
---|
1204 | return 0
|
---|
1205 | hcmd = args[2]
|
---|
1206 | gcmd = args[3]
|
---|
1207 | (user,passwd) = getCred(ctx)
|
---|
1208 | import subprocess
|
---|
1209 | ctx['process'] = subprocess.Popen(split_no_quotes(hcmd), stdout=subprocess.PIPE)
|
---|
1210 | gargs = split_no_quotes(gcmd)
|
---|
1211 | env = []
|
---|
1212 | gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env,user,passwd, 10000,lambda ctx:readCmdPipe(ctx, hcmd)))
|
---|
1213 | cmdExistingVm(ctx, mach, 'guestlambda', gargs)
|
---|
1214 | try:
|
---|
1215 | ctx['process'].terminate()
|
---|
1216 | except:
|
---|
1217 | pass
|
---|
1218 | ctx['process'] = None
|
---|
1219 | return 0
|
---|
1220 |
|
---|
1221 |
|
---|
1222 | def removeVmCmd(ctx, args):
|
---|
1223 | mach = argsToMach(ctx,args)
|
---|
1224 | if mach == None:
|
---|
1225 | return 0
|
---|
1226 | removeVm(ctx, mach)
|
---|
1227 | return 0
|
---|
1228 |
|
---|
1229 | def pauseCmd(ctx, args):
|
---|
1230 | mach = argsToMach(ctx,args)
|
---|
1231 | if mach == None:
|
---|
1232 | return 0
|
---|
1233 | cmdExistingVm(ctx, mach, 'pause', '')
|
---|
1234 | return 0
|
---|
1235 |
|
---|
1236 | def powerdownCmd(ctx, args):
|
---|
1237 | mach = argsToMach(ctx,args)
|
---|
1238 | if mach == None:
|
---|
1239 | return 0
|
---|
1240 | cmdExistingVm(ctx, mach, 'powerdown', '')
|
---|
1241 | return 0
|
---|
1242 |
|
---|
1243 | def powerbuttonCmd(ctx, args):
|
---|
1244 | mach = argsToMach(ctx,args)
|
---|
1245 | if mach == None:
|
---|
1246 | return 0
|
---|
1247 | cmdExistingVm(ctx, mach, 'powerbutton', '')
|
---|
1248 | return 0
|
---|
1249 |
|
---|
1250 | def resumeCmd(ctx, args):
|
---|
1251 | mach = argsToMach(ctx,args)
|
---|
1252 | if mach == None:
|
---|
1253 | return 0
|
---|
1254 | cmdExistingVm(ctx, mach, 'resume', '')
|
---|
1255 | return 0
|
---|
1256 |
|
---|
1257 | def saveCmd(ctx, args):
|
---|
1258 | mach = argsToMach(ctx,args)
|
---|
1259 | if mach == None:
|
---|
1260 | return 0
|
---|
1261 | cmdExistingVm(ctx, mach, 'save', '')
|
---|
1262 | return 0
|
---|
1263 |
|
---|
1264 | def statsCmd(ctx, args):
|
---|
1265 | mach = argsToMach(ctx,args)
|
---|
1266 | if mach == None:
|
---|
1267 | return 0
|
---|
1268 | cmdExistingVm(ctx, mach, 'stats', '')
|
---|
1269 | return 0
|
---|
1270 |
|
---|
1271 | def guestCmd(ctx, args):
|
---|
1272 | if (len(args) < 3):
|
---|
1273 | print "usage: guest name commands"
|
---|
1274 | return 0
|
---|
1275 | mach = argsToMach(ctx,args)
|
---|
1276 | if mach == None:
|
---|
1277 | return 0
|
---|
1278 | if mach.state != ctx['const'].MachineState_Running:
|
---|
1279 | cmdClosedVm(ctx, mach, lambda ctx, mach, a: guestExec (ctx, mach, None, ' '.join(args[2:])))
|
---|
1280 | else:
|
---|
1281 | cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
|
---|
1282 | return 0
|
---|
1283 |
|
---|
1284 | def screenshotCmd(ctx, args):
|
---|
1285 | if (len(args) < 2):
|
---|
1286 | print "usage: screenshot vm <file> <width> <height> <monitor>"
|
---|
1287 | return 0
|
---|
1288 | mach = argsToMach(ctx,args)
|
---|
1289 | if mach == None:
|
---|
1290 | return 0
|
---|
1291 | cmdExistingVm(ctx, mach, 'screenshot', args[2:])
|
---|
1292 | return 0
|
---|
1293 |
|
---|
1294 | def teleportCmd(ctx, args):
|
---|
1295 | if (len(args) < 3):
|
---|
1296 | print "usage: teleport name host:port <password>"
|
---|
1297 | return 0
|
---|
1298 | mach = argsToMach(ctx,args)
|
---|
1299 | if mach == None:
|
---|
1300 | return 0
|
---|
1301 | cmdExistingVm(ctx, mach, 'teleport', args[2:])
|
---|
1302 | return 0
|
---|
1303 |
|
---|
1304 | def portalsettings(ctx,mach,args):
|
---|
1305 | enabled = args[0]
|
---|
1306 | mach.teleporterEnabled = enabled
|
---|
1307 | if enabled:
|
---|
1308 | port = args[1]
|
---|
1309 | passwd = args[2]
|
---|
1310 | mach.teleporterPort = port
|
---|
1311 | mach.teleporterPassword = passwd
|
---|
1312 |
|
---|
1313 | def openportalCmd(ctx, args):
|
---|
1314 | if (len(args) < 3):
|
---|
1315 | print "usage: openportal name port <password>"
|
---|
1316 | return 0
|
---|
1317 | mach = argsToMach(ctx,args)
|
---|
1318 | if mach == None:
|
---|
1319 | return 0
|
---|
1320 | port = int(args[2])
|
---|
1321 | if (len(args) > 3):
|
---|
1322 | passwd = args[3]
|
---|
1323 | else:
|
---|
1324 | passwd = ""
|
---|
1325 | if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
|
---|
1326 | cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
|
---|
1327 | startVm(ctx, mach, "gui")
|
---|
1328 | return 0
|
---|
1329 |
|
---|
1330 | def closeportalCmd(ctx, args):
|
---|
1331 | if (len(args) < 2):
|
---|
1332 | print "usage: closeportal name"
|
---|
1333 | return 0
|
---|
1334 | mach = argsToMach(ctx,args)
|
---|
1335 | if mach == None:
|
---|
1336 | return 0
|
---|
1337 | if mach.teleporterEnabled:
|
---|
1338 | cmdClosedVm(ctx, mach, portalsettings, [False])
|
---|
1339 | return 0
|
---|
1340 |
|
---|
1341 | def gueststatsCmd(ctx, args):
|
---|
1342 | if (len(args) < 2):
|
---|
1343 | print "usage: gueststats name <check interval>"
|
---|
1344 | return 0
|
---|
1345 | mach = argsToMach(ctx,args)
|
---|
1346 | if mach == None:
|
---|
1347 | return 0
|
---|
1348 | cmdExistingVm(ctx, mach, 'gueststats', args[2:])
|
---|
1349 | return 0
|
---|
1350 |
|
---|
1351 | def plugcpu(ctx,mach,args):
|
---|
1352 | plug = args[0]
|
---|
1353 | cpu = args[1]
|
---|
1354 | if plug:
|
---|
1355 | print "Adding CPU %d..." %(cpu)
|
---|
1356 | mach.hotPlugCPU(cpu)
|
---|
1357 | else:
|
---|
1358 | print "Removing CPU %d..." %(cpu)
|
---|
1359 | mach.hotUnplugCPU(cpu)
|
---|
1360 |
|
---|
1361 | def plugcpuCmd(ctx, args):
|
---|
1362 | if (len(args) < 2):
|
---|
1363 | print "usage: plugcpu name cpuid"
|
---|
1364 | return 0
|
---|
1365 | mach = argsToMach(ctx,args)
|
---|
1366 | if mach == None:
|
---|
1367 | return 0
|
---|
1368 | if str(mach.sessionState) != str(ctx['const'].SessionState_Locked):
|
---|
1369 | if mach.CPUHotPlugEnabled:
|
---|
1370 | cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
|
---|
1371 | else:
|
---|
1372 | cmdExistingVm(ctx, mach, 'plugcpu', args[2])
|
---|
1373 | return 0
|
---|
1374 |
|
---|
1375 | def unplugcpuCmd(ctx, args):
|
---|
1376 | if (len(args) < 2):
|
---|
1377 | print "usage: unplugcpu name cpuid"
|
---|
1378 | return 0
|
---|
1379 | mach = argsToMach(ctx,args)
|
---|
1380 | if mach == None:
|
---|
1381 | return 0
|
---|
1382 | if str(mach.sessionState) != str(ctx['const'].SessionState_Locked):
|
---|
1383 | if mach.CPUHotPlugEnabled:
|
---|
1384 | cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
|
---|
1385 | else:
|
---|
1386 | cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
|
---|
1387 | return 0
|
---|
1388 |
|
---|
1389 | def setvar(ctx,mach,args):
|
---|
1390 | expr = 'mach.'+args[0]+' = '+args[1]
|
---|
1391 | print "Executing",expr
|
---|
1392 | exec expr
|
---|
1393 |
|
---|
1394 | def setvarCmd(ctx, args):
|
---|
1395 | if (len(args) < 4):
|
---|
1396 | print "usage: setvar [vmname|uuid] expr value"
|
---|
1397 | return 0
|
---|
1398 | mach = argsToMach(ctx,args)
|
---|
1399 | if mach == None:
|
---|
1400 | return 0
|
---|
1401 | cmdClosedVm(ctx, mach, setvar, args[2:])
|
---|
1402 | return 0
|
---|
1403 |
|
---|
1404 | def setvmextra(ctx,mach,args):
|
---|
1405 | key = args[0]
|
---|
1406 | value = args[1]
|
---|
1407 | print "%s: setting %s to %s" %(mach.name, key, value)
|
---|
1408 | mach.setExtraData(key, value)
|
---|
1409 |
|
---|
1410 | def setExtraDataCmd(ctx, args):
|
---|
1411 | if (len(args) < 3):
|
---|
1412 | print "usage: setextra [vmname|uuid|global] key <value>"
|
---|
1413 | return 0
|
---|
1414 | key = args[2]
|
---|
1415 | if len(args) == 4:
|
---|
1416 | value = args[3]
|
---|
1417 | else:
|
---|
1418 | value = None
|
---|
1419 | if args[1] == 'global':
|
---|
1420 | ctx['vb'].setExtraData(key, value)
|
---|
1421 | return 0
|
---|
1422 |
|
---|
1423 | mach = argsToMach(ctx,args)
|
---|
1424 | if mach == None:
|
---|
1425 | return 0
|
---|
1426 | cmdClosedVm(ctx, mach, setvmextra, [key, value])
|
---|
1427 | return 0
|
---|
1428 |
|
---|
1429 | def printExtraKey(obj, key, value):
|
---|
1430 | print "%s: '%s' = '%s'" %(obj, key, value)
|
---|
1431 |
|
---|
1432 | def getExtraDataCmd(ctx, args):
|
---|
1433 | if (len(args) < 2):
|
---|
1434 | print "usage: getextra [vmname|uuid|global] <key>"
|
---|
1435 | return 0
|
---|
1436 | if len(args) == 3:
|
---|
1437 | key = args[2]
|
---|
1438 | else:
|
---|
1439 | key = None
|
---|
1440 |
|
---|
1441 | if args[1] == 'global':
|
---|
1442 | obj = ctx['vb']
|
---|
1443 | else:
|
---|
1444 | obj = argsToMach(ctx,args)
|
---|
1445 | if obj == None:
|
---|
1446 | return 0
|
---|
1447 |
|
---|
1448 | if key == None:
|
---|
1449 | keys = obj.getExtraDataKeys()
|
---|
1450 | else:
|
---|
1451 | keys = [ key ]
|
---|
1452 | for k in keys:
|
---|
1453 | printExtraKey(args[1], k, obj.getExtraData(k))
|
---|
1454 |
|
---|
1455 | return 0
|
---|
1456 |
|
---|
1457 | def quitCmd(ctx, args):
|
---|
1458 | return 1
|
---|
1459 |
|
---|
1460 | def aliasCmd(ctx, args):
|
---|
1461 | if (len(args) == 3):
|
---|
1462 | aliases[args[1]] = args[2]
|
---|
1463 | return 0
|
---|
1464 |
|
---|
1465 | for (k,v) in aliases.items():
|
---|
1466 | print "'%s' is an alias for '%s'" %(k,v)
|
---|
1467 | return 0
|
---|
1468 |
|
---|
1469 | def verboseCmd(ctx, args):
|
---|
1470 | global g_verbose
|
---|
1471 | if (len(args) > 1):
|
---|
1472 | g_verbose = (args[1]=='on')
|
---|
1473 | else:
|
---|
1474 | g_verbose = not g_verbose
|
---|
1475 | return 0
|
---|
1476 |
|
---|
1477 | def colorsCmd(ctx, args):
|
---|
1478 | global g_hascolors
|
---|
1479 | if (len(args) > 1):
|
---|
1480 | g_hascolors = (args[1]=='on')
|
---|
1481 | else:
|
---|
1482 | g_hascolors = not g_hascolors
|
---|
1483 | return 0
|
---|
1484 |
|
---|
1485 | def hostCmd(ctx, args):
|
---|
1486 | vb = ctx['vb']
|
---|
1487 | print "VirtualBox version %s" %(colored(vb.version, 'blue'))
|
---|
1488 | props = vb.systemProperties
|
---|
1489 | print "Machines: %s" %(colPath(ctx,props.defaultMachineFolder))
|
---|
1490 | print "HDDs: %s" %(colPath(ctx,props.defaultHardDiskFolder))
|
---|
1491 |
|
---|
1492 | #print "Global shared folders:"
|
---|
1493 | #for ud in ctx['global'].getArray(vb, 'sharedFolders'):
|
---|
1494 | # printSf(ctx,sf)
|
---|
1495 | host = vb.host
|
---|
1496 | cnt = host.processorCount
|
---|
1497 | print colCat(ctx,"Processors:")
|
---|
1498 | print " available/online: %d/%d " %(cnt,host.processorOnlineCount)
|
---|
1499 | for i in range(0,cnt):
|
---|
1500 | print " processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
|
---|
1501 |
|
---|
1502 | print colCat(ctx, "RAM:")
|
---|
1503 | print " %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
|
---|
1504 | print colCat(ctx,"OS:");
|
---|
1505 | print " %s (%s)" %(host.operatingSystem, host.OSVersion)
|
---|
1506 | if host.Acceleration3DAvailable:
|
---|
1507 | print colCat(ctx,"3D acceleration available")
|
---|
1508 | else:
|
---|
1509 | print colCat(ctx,"3D acceleration NOT available")
|
---|
1510 |
|
---|
1511 | print colCat(ctx,"Network interfaces:")
|
---|
1512 | for ni in ctx['global'].getArray(host, 'networkInterfaces'):
|
---|
1513 | print " %s (%s)" %(ni.name, ni.IPAddress)
|
---|
1514 |
|
---|
1515 | print colCat(ctx,"DVD drives:")
|
---|
1516 | for dd in ctx['global'].getArray(host, 'DVDDrives'):
|
---|
1517 | print " %s - %s" %(dd.name, dd.description)
|
---|
1518 |
|
---|
1519 | print colCat(ctx,"Floppy drives:")
|
---|
1520 | for dd in ctx['global'].getArray(host, 'floppyDrives'):
|
---|
1521 | print " %s - %s" %(dd.name, dd.description)
|
---|
1522 |
|
---|
1523 | print colCat(ctx,"USB devices:")
|
---|
1524 | for ud in ctx['global'].getArray(host, 'USBDevices'):
|
---|
1525 | printHostUsbDev(ctx,ud)
|
---|
1526 |
|
---|
1527 | if ctx['perf']:
|
---|
1528 | for metric in ctx['perf'].query(["*"], [host]):
|
---|
1529 | print metric['name'], metric['values_as_string']
|
---|
1530 |
|
---|
1531 | return 0
|
---|
1532 |
|
---|
1533 | def monitorGuestCmd(ctx, args):
|
---|
1534 | if (len(args) < 2):
|
---|
1535 | print "usage: monitorGuest name (duration)"
|
---|
1536 | return 0
|
---|
1537 | mach = argsToMach(ctx,args)
|
---|
1538 | if mach == None:
|
---|
1539 | return 0
|
---|
1540 | dur = 5
|
---|
1541 | if len(args) > 2:
|
---|
1542 | dur = float(args[2])
|
---|
1543 | active = False
|
---|
1544 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: monitorSource(ctx, console.eventSource, active, dur)])
|
---|
1545 | return 0
|
---|
1546 |
|
---|
1547 | def monitorGuestKbdCmd(ctx, args):
|
---|
1548 | if (len(args) < 2):
|
---|
1549 | print "usage: monitorGuestKbd name (duration)"
|
---|
1550 | return 0
|
---|
1551 | mach = argsToMach(ctx,args)
|
---|
1552 | if mach == None:
|
---|
1553 | return 0
|
---|
1554 | dur = 5
|
---|
1555 | if len(args) > 2:
|
---|
1556 | dur = float(args[2])
|
---|
1557 | active = False
|
---|
1558 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: monitorSource(ctx, console.keyboard.eventSource, active, dur)])
|
---|
1559 | return 0
|
---|
1560 |
|
---|
1561 | def monitorGuestMouseCmd(ctx, args):
|
---|
1562 | if (len(args) < 2):
|
---|
1563 | print "usage: monitorGuestMouse name (duration)"
|
---|
1564 | return 0
|
---|
1565 | mach = argsToMach(ctx,args)
|
---|
1566 | if mach == None:
|
---|
1567 | return 0
|
---|
1568 | dur = 5
|
---|
1569 | if len(args) > 2:
|
---|
1570 | dur = float(args[2])
|
---|
1571 | active = False
|
---|
1572 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: monitorSource(ctx, console.mouse.eventSource, active, dur)])
|
---|
1573 | return 0
|
---|
1574 |
|
---|
1575 | def monitorVBoxCmd(ctx, args):
|
---|
1576 | if (len(args) > 2):
|
---|
1577 | print "usage: monitorVBox (duration)"
|
---|
1578 | return 0
|
---|
1579 | dur = 5
|
---|
1580 | if len(args) > 1:
|
---|
1581 | dur = float(args[1])
|
---|
1582 | vbox = ctx['vb']
|
---|
1583 | active = False
|
---|
1584 | monitorSource(ctx, vbox.eventSource, active, dur)
|
---|
1585 | return 0
|
---|
1586 |
|
---|
1587 | def getAdapterType(ctx, type):
|
---|
1588 | if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
|
---|
1589 | type == ctx['global'].constants.NetworkAdapterType_Am79C973):
|
---|
1590 | return "pcnet"
|
---|
1591 | elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
|
---|
1592 | type == ctx['global'].constants.NetworkAdapterType_I82545EM or
|
---|
1593 | type == ctx['global'].constants.NetworkAdapterType_I82543GC):
|
---|
1594 | return "e1000"
|
---|
1595 | elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
|
---|
1596 | return "virtio"
|
---|
1597 | elif (type == ctx['global'].constants.NetworkAdapterType_Null):
|
---|
1598 | return None
|
---|
1599 | else:
|
---|
1600 | raise Exception("Unknown adapter type: "+type)
|
---|
1601 |
|
---|
1602 |
|
---|
1603 | def portForwardCmd(ctx, args):
|
---|
1604 | if (len(args) != 5):
|
---|
1605 | print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
|
---|
1606 | return 0
|
---|
1607 | mach = argsToMach(ctx,args)
|
---|
1608 | if mach == None:
|
---|
1609 | return 0
|
---|
1610 | adapterNum = int(args[2])
|
---|
1611 | hostPort = int(args[3])
|
---|
1612 | guestPort = int(args[4])
|
---|
1613 | proto = "TCP"
|
---|
1614 | session = ctx['global'].openMachineSession(mach)
|
---|
1615 | mach = session.machine
|
---|
1616 |
|
---|
1617 | adapter = mach.getNetworkAdapter(adapterNum)
|
---|
1618 | adapterType = getAdapterType(ctx, adapter.adapterType)
|
---|
1619 |
|
---|
1620 | profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
|
---|
1621 | config = "VBoxInternal/Devices/" + adapterType + "/"
|
---|
1622 | config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
|
---|
1623 |
|
---|
1624 | mach.setExtraData(config + "/Protocol", proto)
|
---|
1625 | mach.setExtraData(config + "/HostPort", str(hostPort))
|
---|
1626 | mach.setExtraData(config + "/GuestPort", str(guestPort))
|
---|
1627 |
|
---|
1628 | mach.saveSettings()
|
---|
1629 | session.unlockMachine()
|
---|
1630 |
|
---|
1631 | return 0
|
---|
1632 |
|
---|
1633 |
|
---|
1634 | def showLogCmd(ctx, args):
|
---|
1635 | if (len(args) < 2):
|
---|
1636 | print "usage: showLog vm <num>"
|
---|
1637 | return 0
|
---|
1638 | mach = argsToMach(ctx,args)
|
---|
1639 | if mach == None:
|
---|
1640 | return 0
|
---|
1641 |
|
---|
1642 | log = 0
|
---|
1643 | if (len(args) > 2):
|
---|
1644 | log = args[2]
|
---|
1645 |
|
---|
1646 | uOffset = 0
|
---|
1647 | while True:
|
---|
1648 | data = mach.readLog(log, uOffset, 4096)
|
---|
1649 | if (len(data) == 0):
|
---|
1650 | break
|
---|
1651 | # print adds either NL or space to chunks not ending with a NL
|
---|
1652 | sys.stdout.write(str(data))
|
---|
1653 | uOffset += len(data)
|
---|
1654 |
|
---|
1655 | return 0
|
---|
1656 |
|
---|
1657 | def findLogCmd(ctx, args):
|
---|
1658 | if (len(args) < 3):
|
---|
1659 | print "usage: findLog vm pattern <num>"
|
---|
1660 | return 0
|
---|
1661 | mach = argsToMach(ctx,args)
|
---|
1662 | if mach == None:
|
---|
1663 | return 0
|
---|
1664 |
|
---|
1665 | log = 0
|
---|
1666 | if (len(args) > 3):
|
---|
1667 | log = args[3]
|
---|
1668 |
|
---|
1669 | pattern = args[2]
|
---|
1670 | uOffset = 0
|
---|
1671 | while True:
|
---|
1672 | # to reduce line splits on buffer boundary
|
---|
1673 | data = mach.readLog(log, uOffset, 512*1024)
|
---|
1674 | if (len(data) == 0):
|
---|
1675 | break
|
---|
1676 | d = str(data).split("\n")
|
---|
1677 | for s in d:
|
---|
1678 | m = re.findall(pattern, s)
|
---|
1679 | if len(m) > 0:
|
---|
1680 | for mt in m:
|
---|
1681 | s = s.replace(mt, colored(mt,'red'))
|
---|
1682 | print s
|
---|
1683 | uOffset += len(data)
|
---|
1684 |
|
---|
1685 | return 0
|
---|
1686 |
|
---|
1687 |
|
---|
1688 | def findAssertCmd(ctx, args):
|
---|
1689 | if (len(args) < 2):
|
---|
1690 | print "usage: findAssert vm <num>"
|
---|
1691 | return 0
|
---|
1692 | mach = argsToMach(ctx,args)
|
---|
1693 | if mach == None:
|
---|
1694 | return 0
|
---|
1695 |
|
---|
1696 | log = 0
|
---|
1697 | if (len(args) > 2):
|
---|
1698 | log = args[2]
|
---|
1699 |
|
---|
1700 | uOffset = 0
|
---|
1701 | ere = re.compile(r'(Expression:|\!\!\!\!\!\!)')
|
---|
1702 | active = False
|
---|
1703 | context = 0
|
---|
1704 | while True:
|
---|
1705 | # to reduce line splits on buffer boundary
|
---|
1706 | data = mach.readLog(log, uOffset, 512*1024)
|
---|
1707 | if (len(data) == 0):
|
---|
1708 | break
|
---|
1709 | d = str(data).split("\n")
|
---|
1710 | for s in d:
|
---|
1711 | if active:
|
---|
1712 | print s
|
---|
1713 | if context == 0:
|
---|
1714 | active = False
|
---|
1715 | else:
|
---|
1716 | context = context - 1
|
---|
1717 | continue
|
---|
1718 | m = ere.findall(s)
|
---|
1719 | if len(m) > 0:
|
---|
1720 | active = True
|
---|
1721 | context = 50
|
---|
1722 | print s
|
---|
1723 | uOffset += len(data)
|
---|
1724 |
|
---|
1725 | return 0
|
---|
1726 |
|
---|
1727 | def evalCmd(ctx, args):
|
---|
1728 | expr = ' '.join(args[1:])
|
---|
1729 | try:
|
---|
1730 | exec expr
|
---|
1731 | except Exception, e:
|
---|
1732 | printErr(ctx,e)
|
---|
1733 | if g_verbose:
|
---|
1734 | traceback.print_exc()
|
---|
1735 | return 0
|
---|
1736 |
|
---|
1737 | def reloadExtCmd(ctx, args):
|
---|
1738 | # maybe will want more args smartness
|
---|
1739 | checkUserExtensions(ctx, commands, getHomeFolder(ctx))
|
---|
1740 | autoCompletion(commands, ctx)
|
---|
1741 | return 0
|
---|
1742 |
|
---|
1743 | def runScriptCmd(ctx, args):
|
---|
1744 | if (len(args) != 2):
|
---|
1745 | print "usage: runScript <script>"
|
---|
1746 | return 0
|
---|
1747 | try:
|
---|
1748 | lf = open(args[1], 'r')
|
---|
1749 | except IOError,e:
|
---|
1750 | print "cannot open:",args[1], ":",e
|
---|
1751 | return 0
|
---|
1752 |
|
---|
1753 | try:
|
---|
1754 | lines = lf.readlines()
|
---|
1755 | ctx['scriptLine'] = 0
|
---|
1756 | ctx['interrupt'] = False
|
---|
1757 | while ctx['scriptLine'] < len(lines):
|
---|
1758 | line = lines[ctx['scriptLine']]
|
---|
1759 | ctx['scriptLine'] = ctx['scriptLine'] + 1
|
---|
1760 | done = runCommand(ctx, line)
|
---|
1761 | if done != 0 or ctx['interrupt']:
|
---|
1762 | break
|
---|
1763 |
|
---|
1764 | except Exception,e:
|
---|
1765 | printErr(ctx,e)
|
---|
1766 | if g_verbose:
|
---|
1767 | traceback.print_exc()
|
---|
1768 | lf.close()
|
---|
1769 | return 0
|
---|
1770 |
|
---|
1771 | def sleepCmd(ctx, args):
|
---|
1772 | if (len(args) != 2):
|
---|
1773 | print "usage: sleep <secs>"
|
---|
1774 | return 0
|
---|
1775 |
|
---|
1776 | try:
|
---|
1777 | time.sleep(float(args[1]))
|
---|
1778 | except:
|
---|
1779 | # to allow sleep interrupt
|
---|
1780 | pass
|
---|
1781 | return 0
|
---|
1782 |
|
---|
1783 |
|
---|
1784 | def shellCmd(ctx, args):
|
---|
1785 | if (len(args) < 2):
|
---|
1786 | print "usage: shell <commands>"
|
---|
1787 | return 0
|
---|
1788 | cmd = ' '.join(args[1:])
|
---|
1789 |
|
---|
1790 | try:
|
---|
1791 | os.system(cmd)
|
---|
1792 | except KeyboardInterrupt:
|
---|
1793 | # to allow shell command interruption
|
---|
1794 | pass
|
---|
1795 | return 0
|
---|
1796 |
|
---|
1797 |
|
---|
1798 | def connectCmd(ctx, args):
|
---|
1799 | if (len(args) > 4):
|
---|
1800 | print "usage: connect url <username> <passwd>"
|
---|
1801 | return 0
|
---|
1802 |
|
---|
1803 | if ctx['vb'] is not None:
|
---|
1804 | print "Already connected, disconnect first..."
|
---|
1805 | return 0
|
---|
1806 |
|
---|
1807 | if (len(args) > 1):
|
---|
1808 | url = args[1]
|
---|
1809 | else:
|
---|
1810 | url = None
|
---|
1811 |
|
---|
1812 | if (len(args) > 2):
|
---|
1813 | user = args[2]
|
---|
1814 | else:
|
---|
1815 | user = ""
|
---|
1816 |
|
---|
1817 | if (len(args) > 3):
|
---|
1818 | passwd = args[3]
|
---|
1819 | else:
|
---|
1820 | passwd = ""
|
---|
1821 |
|
---|
1822 | ctx['wsinfo'] = [url, user, passwd]
|
---|
1823 | vbox = ctx['global'].platform.connect(url, user, passwd)
|
---|
1824 | ctx['vb'] = vbox
|
---|
1825 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1826 | ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
|
---|
1827 | return 0
|
---|
1828 |
|
---|
1829 | def disconnectCmd(ctx, args):
|
---|
1830 | if (len(args) != 1):
|
---|
1831 | print "usage: disconnect"
|
---|
1832 | return 0
|
---|
1833 |
|
---|
1834 | if ctx['vb'] is None:
|
---|
1835 | print "Not connected yet."
|
---|
1836 | return 0
|
---|
1837 |
|
---|
1838 | try:
|
---|
1839 | ctx['global'].platform.disconnect()
|
---|
1840 | except:
|
---|
1841 | ctx['vb'] = None
|
---|
1842 | raise
|
---|
1843 |
|
---|
1844 | ctx['vb'] = None
|
---|
1845 | return 0
|
---|
1846 |
|
---|
1847 | def reconnectCmd(ctx, args):
|
---|
1848 | if ctx['wsinfo'] is None:
|
---|
1849 | print "Never connected..."
|
---|
1850 | return 0
|
---|
1851 |
|
---|
1852 | try:
|
---|
1853 | ctx['global'].platform.disconnect()
|
---|
1854 | except:
|
---|
1855 | pass
|
---|
1856 |
|
---|
1857 | [url,user,passwd] = ctx['wsinfo']
|
---|
1858 | ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
|
---|
1859 | print "Running VirtualBox version %s" %(ctx['vb'].version)
|
---|
1860 | return 0
|
---|
1861 |
|
---|
1862 | def exportVMCmd(ctx, args):
|
---|
1863 | import sys
|
---|
1864 |
|
---|
1865 | if len(args) < 3:
|
---|
1866 | print "usage: exportVm <machine> <path> <format> <license>"
|
---|
1867 | return 0
|
---|
1868 | mach = argsToMach(ctx,args)
|
---|
1869 | if mach is None:
|
---|
1870 | return 0
|
---|
1871 | path = args[2]
|
---|
1872 | if (len(args) > 3):
|
---|
1873 | format = args[3]
|
---|
1874 | else:
|
---|
1875 | format = "ovf-1.0"
|
---|
1876 | if (len(args) > 4):
|
---|
1877 | license = args[4]
|
---|
1878 | else:
|
---|
1879 | license = "GPL"
|
---|
1880 |
|
---|
1881 | app = ctx['vb'].createAppliance()
|
---|
1882 | desc = mach.export(app)
|
---|
1883 | desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
|
---|
1884 | p = app.write(format, path)
|
---|
1885 | if (progressBar(ctx, p) and int(p.resultCode) == 0):
|
---|
1886 | print "Exported to %s in format %s" %(path, format)
|
---|
1887 | else:
|
---|
1888 | reportError(ctx,p)
|
---|
1889 | return 0
|
---|
1890 |
|
---|
1891 | # PC XT scancodes
|
---|
1892 | scancodes = {
|
---|
1893 | 'a': 0x1e,
|
---|
1894 | 'b': 0x30,
|
---|
1895 | 'c': 0x2e,
|
---|
1896 | 'd': 0x20,
|
---|
1897 | 'e': 0x12,
|
---|
1898 | 'f': 0x21,
|
---|
1899 | 'g': 0x22,
|
---|
1900 | 'h': 0x23,
|
---|
1901 | 'i': 0x17,
|
---|
1902 | 'j': 0x24,
|
---|
1903 | 'k': 0x25,
|
---|
1904 | 'l': 0x26,
|
---|
1905 | 'm': 0x32,
|
---|
1906 | 'n': 0x31,
|
---|
1907 | 'o': 0x18,
|
---|
1908 | 'p': 0x19,
|
---|
1909 | 'q': 0x10,
|
---|
1910 | 'r': 0x13,
|
---|
1911 | 's': 0x1f,
|
---|
1912 | 't': 0x14,
|
---|
1913 | 'u': 0x16,
|
---|
1914 | 'v': 0x2f,
|
---|
1915 | 'w': 0x11,
|
---|
1916 | 'x': 0x2d,
|
---|
1917 | 'y': 0x15,
|
---|
1918 | 'z': 0x2c,
|
---|
1919 | '0': 0x0b,
|
---|
1920 | '1': 0x02,
|
---|
1921 | '2': 0x03,
|
---|
1922 | '3': 0x04,
|
---|
1923 | '4': 0x05,
|
---|
1924 | '5': 0x06,
|
---|
1925 | '6': 0x07,
|
---|
1926 | '7': 0x08,
|
---|
1927 | '8': 0x09,
|
---|
1928 | '9': 0x0a,
|
---|
1929 | ' ': 0x39,
|
---|
1930 | '-': 0xc,
|
---|
1931 | '=': 0xd,
|
---|
1932 | '[': 0x1a,
|
---|
1933 | ']': 0x1b,
|
---|
1934 | ';': 0x27,
|
---|
1935 | '\'': 0x28,
|
---|
1936 | ',': 0x33,
|
---|
1937 | '.': 0x34,
|
---|
1938 | '/': 0x35,
|
---|
1939 | '\t': 0xf,
|
---|
1940 | '\n': 0x1c,
|
---|
1941 | '`': 0x29
|
---|
1942 | };
|
---|
1943 |
|
---|
1944 | extScancodes = {
|
---|
1945 | 'ESC' : [0x01],
|
---|
1946 | 'BKSP': [0xe],
|
---|
1947 | 'SPACE': [0x39],
|
---|
1948 | 'TAB': [0x0f],
|
---|
1949 | 'CAPS': [0x3a],
|
---|
1950 | 'ENTER': [0x1c],
|
---|
1951 | 'LSHIFT': [0x2a],
|
---|
1952 | 'RSHIFT': [0x36],
|
---|
1953 | 'INS': [0xe0, 0x52],
|
---|
1954 | 'DEL': [0xe0, 0x53],
|
---|
1955 | 'END': [0xe0, 0x4f],
|
---|
1956 | 'HOME': [0xe0, 0x47],
|
---|
1957 | 'PGUP': [0xe0, 0x49],
|
---|
1958 | 'PGDOWN': [0xe0, 0x51],
|
---|
1959 | 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
|
---|
1960 | 'RGUI': [0xe0, 0x5c],
|
---|
1961 | 'LCTR': [0x1d],
|
---|
1962 | 'RCTR': [0xe0, 0x1d],
|
---|
1963 | 'LALT': [0x38],
|
---|
1964 | 'RALT': [0xe0, 0x38],
|
---|
1965 | 'APPS': [0xe0, 0x5d],
|
---|
1966 | 'F1': [0x3b],
|
---|
1967 | 'F2': [0x3c],
|
---|
1968 | 'F3': [0x3d],
|
---|
1969 | 'F4': [0x3e],
|
---|
1970 | 'F5': [0x3f],
|
---|
1971 | 'F6': [0x40],
|
---|
1972 | 'F7': [0x41],
|
---|
1973 | 'F8': [0x42],
|
---|
1974 | 'F9': [0x43],
|
---|
1975 | 'F10': [0x44 ],
|
---|
1976 | 'F11': [0x57],
|
---|
1977 | 'F12': [0x58],
|
---|
1978 | 'UP': [0xe0, 0x48],
|
---|
1979 | 'LEFT': [0xe0, 0x4b],
|
---|
1980 | 'DOWN': [0xe0, 0x50],
|
---|
1981 | 'RIGHT': [0xe0, 0x4d],
|
---|
1982 | };
|
---|
1983 |
|
---|
1984 | def keyDown(ch):
|
---|
1985 | code = scancodes.get(ch, 0x0)
|
---|
1986 | if code != 0:
|
---|
1987 | return [code]
|
---|
1988 | extCode = extScancodes.get(ch, [])
|
---|
1989 | if len(extCode) == 0:
|
---|
1990 | print "bad ext",ch
|
---|
1991 | return extCode
|
---|
1992 |
|
---|
1993 | def keyUp(ch):
|
---|
1994 | codes = keyDown(ch)[:] # make a copy
|
---|
1995 | if len(codes) > 0:
|
---|
1996 | codes[len(codes)-1] += 0x80
|
---|
1997 | return codes
|
---|
1998 |
|
---|
1999 | def typeInGuest(console, text, delay):
|
---|
2000 | import time
|
---|
2001 | pressed = []
|
---|
2002 | group = False
|
---|
2003 | modGroupEnd = True
|
---|
2004 | i = 0
|
---|
2005 | kbd = console.keyboard
|
---|
2006 | while i < len(text):
|
---|
2007 | ch = text[i]
|
---|
2008 | i = i+1
|
---|
2009 | if ch == '{':
|
---|
2010 | # start group, all keys to be pressed at the same time
|
---|
2011 | group = True
|
---|
2012 | continue
|
---|
2013 | if ch == '}':
|
---|
2014 | # end group, release all keys
|
---|
2015 | for c in pressed:
|
---|
2016 | kbd.putScancodes(keyUp(c))
|
---|
2017 | pressed = []
|
---|
2018 | group = False
|
---|
2019 | continue
|
---|
2020 | if ch == 'W':
|
---|
2021 | # just wait a bit
|
---|
2022 | time.sleep(0.3)
|
---|
2023 | continue
|
---|
2024 | if ch == '^' or ch == '|' or ch == '$' or ch == '_':
|
---|
2025 | if ch == '^':
|
---|
2026 | ch = 'LCTR'
|
---|
2027 | if ch == '|':
|
---|
2028 | ch = 'LSHIFT'
|
---|
2029 | if ch == '_':
|
---|
2030 | ch = 'LALT'
|
---|
2031 | if ch == '$':
|
---|
2032 | ch = 'LGUI'
|
---|
2033 | if not group:
|
---|
2034 | modGroupEnd = False
|
---|
2035 | else:
|
---|
2036 | if ch == '\\':
|
---|
2037 | if i < len(text):
|
---|
2038 | ch = text[i]
|
---|
2039 | i = i+1
|
---|
2040 | if ch == 'n':
|
---|
2041 | ch = '\n'
|
---|
2042 | elif ch == '&':
|
---|
2043 | combo = ""
|
---|
2044 | while i < len(text):
|
---|
2045 | ch = text[i]
|
---|
2046 | i = i+1
|
---|
2047 | if ch == ';':
|
---|
2048 | break
|
---|
2049 | combo += ch
|
---|
2050 | ch = combo
|
---|
2051 | modGroupEnd = True
|
---|
2052 | kbd.putScancodes(keyDown(ch))
|
---|
2053 | pressed.insert(0, ch)
|
---|
2054 | if not group and modGroupEnd:
|
---|
2055 | for c in pressed:
|
---|
2056 | kbd.putScancodes(keyUp(c))
|
---|
2057 | pressed = []
|
---|
2058 | modGroupEnd = True
|
---|
2059 | time.sleep(delay)
|
---|
2060 |
|
---|
2061 | def typeGuestCmd(ctx, args):
|
---|
2062 | import sys
|
---|
2063 |
|
---|
2064 | if len(args) < 3:
|
---|
2065 | print "usage: typeGuest <machine> <text> <charDelay>"
|
---|
2066 | return 0
|
---|
2067 | mach = argsToMach(ctx,args)
|
---|
2068 | if mach is None:
|
---|
2069 | return 0
|
---|
2070 |
|
---|
2071 | text = args[2]
|
---|
2072 |
|
---|
2073 | if len(args) > 3:
|
---|
2074 | delay = float(args[3])
|
---|
2075 | else:
|
---|
2076 | delay = 0.1
|
---|
2077 |
|
---|
2078 | gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
|
---|
2079 | cmdExistingVm(ctx, mach, 'guestlambda', gargs)
|
---|
2080 |
|
---|
2081 | return 0
|
---|
2082 |
|
---|
2083 | def optId(verbose,id):
|
---|
2084 | if verbose:
|
---|
2085 | return ": "+id
|
---|
2086 | else:
|
---|
2087 | return ""
|
---|
2088 |
|
---|
2089 | def asSize(val,inBytes):
|
---|
2090 | if inBytes:
|
---|
2091 | return int(val)/(1024*1024)
|
---|
2092 | else:
|
---|
2093 | return int(val)
|
---|
2094 |
|
---|
2095 | def listMediaCmd(ctx,args):
|
---|
2096 | if len(args) > 1:
|
---|
2097 | verbose = int(args[1])
|
---|
2098 | else:
|
---|
2099 | verbose = False
|
---|
2100 | hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
|
---|
2101 | print colCat(ctx,"Hard disks:")
|
---|
2102 | for hdd in hdds:
|
---|
2103 | if hdd.state != ctx['global'].constants.MediumState_Created:
|
---|
2104 | hdd.refreshState()
|
---|
2105 | print " %s (%s)%s %s [logical %s]" %(colPath(ctx,hdd.location), hdd.format, optId(verbose,hdd.id),colSizeM(ctx,asSize(hdd.size, True)), colSizeM(ctx,asSize(hdd.logicalSize, True)))
|
---|
2106 |
|
---|
2107 | dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
|
---|
2108 | print colCat(ctx,"CD/DVD disks:")
|
---|
2109 | for dvd in dvds:
|
---|
2110 | if dvd.state != ctx['global'].constants.MediumState_Created:
|
---|
2111 | dvd.refreshState()
|
---|
2112 | print " %s (%s)%s %s" %(colPath(ctx,dvd.location), dvd.format,optId(verbose,dvd.id),colSizeM(ctx,asSize(dvd.size, True)))
|
---|
2113 |
|
---|
2114 | floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
|
---|
2115 | print colCat(ctx,"Floppy disks:")
|
---|
2116 | for floppy in floppys:
|
---|
2117 | if floppy.state != ctx['global'].constants.MediumState_Created:
|
---|
2118 | floppy.refreshState()
|
---|
2119 | print " %s (%s)%s %s" %(colPath(ctx,floppy.location), floppy.format,optId(verbose,floppy.id), colSizeM(ctx,asSize(floppy.size, True)))
|
---|
2120 |
|
---|
2121 | return 0
|
---|
2122 |
|
---|
2123 | def listUsbCmd(ctx,args):
|
---|
2124 | if (len(args) > 1):
|
---|
2125 | print "usage: listUsb"
|
---|
2126 | return 0
|
---|
2127 |
|
---|
2128 | host = ctx['vb'].host
|
---|
2129 | for ud in ctx['global'].getArray(host, 'USBDevices'):
|
---|
2130 | printHostUsbDev(ctx,ud)
|
---|
2131 |
|
---|
2132 | return 0
|
---|
2133 |
|
---|
2134 | def findDevOfType(ctx,mach,type):
|
---|
2135 | atts = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
2136 | for a in atts:
|
---|
2137 | if a.type == type:
|
---|
2138 | return [a.controller, a.port, a.device]
|
---|
2139 | return [None, 0, 0]
|
---|
2140 |
|
---|
2141 | def createHddCmd(ctx,args):
|
---|
2142 | if (len(args) < 3):
|
---|
2143 | print "usage: createHdd sizeM location type"
|
---|
2144 | return 0
|
---|
2145 |
|
---|
2146 | size = int(args[1])
|
---|
2147 | loc = args[2]
|
---|
2148 | if len(args) > 3:
|
---|
2149 | format = args[3]
|
---|
2150 | else:
|
---|
2151 | format = "vdi"
|
---|
2152 |
|
---|
2153 | hdd = ctx['vb'].createHardDisk(format, loc)
|
---|
2154 | progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
|
---|
2155 | if progressBar(ctx,progress) and hdd.id:
|
---|
2156 | print "created HDD at %s as %s" %(colPath(ctx,hdd.location), hdd.id)
|
---|
2157 | else:
|
---|
2158 | print "cannot create disk (file %s exist?)" %(loc)
|
---|
2159 | reportError(ctx,progress)
|
---|
2160 | return 0
|
---|
2161 |
|
---|
2162 | return 0
|
---|
2163 |
|
---|
2164 | def registerHddCmd(ctx,args):
|
---|
2165 | if (len(args) < 2):
|
---|
2166 | print "usage: registerHdd location"
|
---|
2167 | return 0
|
---|
2168 |
|
---|
2169 | vb = ctx['vb']
|
---|
2170 | loc = args[1]
|
---|
2171 | setImageId = False
|
---|
2172 | imageId = ""
|
---|
2173 | setParentId = False
|
---|
2174 | parentId = ""
|
---|
2175 | hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
|
---|
2176 | print "registered HDD as %s" %(hdd.id)
|
---|
2177 | return 0
|
---|
2178 |
|
---|
2179 | def controldevice(ctx,mach,args):
|
---|
2180 | [ctr,port,slot,type,id] = args
|
---|
2181 | mach.attachDevice(ctr, port, slot,type,id)
|
---|
2182 |
|
---|
2183 | def attachHddCmd(ctx,args):
|
---|
2184 | if (len(args) < 3):
|
---|
2185 | print "usage: attachHdd vm hdd controller port:slot"
|
---|
2186 | return 0
|
---|
2187 |
|
---|
2188 | mach = argsToMach(ctx,args)
|
---|
2189 | if mach is None:
|
---|
2190 | return 0
|
---|
2191 | vb = ctx['vb']
|
---|
2192 | loc = args[2]
|
---|
2193 | try:
|
---|
2194 | hdd = vb.findMedium(loc, ctx['global'].constants.DeviceType_HardDisk)
|
---|
2195 | except:
|
---|
2196 | print "no HDD with path %s registered" %(loc)
|
---|
2197 | return 0
|
---|
2198 | if len(args) > 3:
|
---|
2199 | ctr = args[3]
|
---|
2200 | (port,slot) = args[4].split(":")
|
---|
2201 | else:
|
---|
2202 | [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
|
---|
2203 |
|
---|
2204 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
|
---|
2205 | return 0
|
---|
2206 |
|
---|
2207 | def detachVmDevice(ctx,mach,args):
|
---|
2208 | atts = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
2209 | hid = args[0]
|
---|
2210 | for a in atts:
|
---|
2211 | if a.medium:
|
---|
2212 | if hid == "ALL" or a.medium.id == hid:
|
---|
2213 | mach.detachDevice(a.controller, a.port, a.device)
|
---|
2214 |
|
---|
2215 | def detachMedium(ctx,mid,medium):
|
---|
2216 | cmdClosedVm(ctx, machById(ctx, mid), detachVmDevice, [medium])
|
---|
2217 |
|
---|
2218 | def detachHddCmd(ctx,args):
|
---|
2219 | if (len(args) < 3):
|
---|
2220 | print "usage: detachHdd vm hdd"
|
---|
2221 | return 0
|
---|
2222 |
|
---|
2223 | mach = argsToMach(ctx,args)
|
---|
2224 | if mach is None:
|
---|
2225 | return 0
|
---|
2226 | vb = ctx['vb']
|
---|
2227 | loc = args[2]
|
---|
2228 | try:
|
---|
2229 | hdd = vb.findMedium(loc, ctx['global'].constants.DeviceType_HardDisk)
|
---|
2230 | except:
|
---|
2231 | print "no HDD with path %s registered" %(loc)
|
---|
2232 | return 0
|
---|
2233 |
|
---|
2234 | detachMedium(ctx, mach.id, hdd)
|
---|
2235 | return 0
|
---|
2236 |
|
---|
2237 | def unregisterHddCmd(ctx,args):
|
---|
2238 | if (len(args) < 2):
|
---|
2239 | print "usage: unregisterHdd path <vmunreg>"
|
---|
2240 | return 0
|
---|
2241 |
|
---|
2242 | vb = ctx['vb']
|
---|
2243 | loc = args[1]
|
---|
2244 | if (len(args) > 2):
|
---|
2245 | vmunreg = int(args[2])
|
---|
2246 | else:
|
---|
2247 | vmunreg = 0
|
---|
2248 | try:
|
---|
2249 | hdd = vb.findMedium(loc, ctx['global'].constants.DeviceType_HardDisk)
|
---|
2250 | except:
|
---|
2251 | print "no HDD with path %s registered" %(loc)
|
---|
2252 | return 0
|
---|
2253 |
|
---|
2254 | if vmunreg != 0:
|
---|
2255 | machs = ctx['global'].getArray(hdd, 'machineIds')
|
---|
2256 | try:
|
---|
2257 | for m in machs:
|
---|
2258 | print "Trying to detach from %s" %(m)
|
---|
2259 | detachMedium(ctx, m, hdd)
|
---|
2260 | except Exception, e:
|
---|
2261 | print 'failed: ',e
|
---|
2262 | return 0
|
---|
2263 | hdd.close()
|
---|
2264 | return 0
|
---|
2265 |
|
---|
2266 | def removeHddCmd(ctx,args):
|
---|
2267 | if (len(args) != 2):
|
---|
2268 | print "usage: removeHdd path"
|
---|
2269 | return 0
|
---|
2270 |
|
---|
2271 | vb = ctx['vb']
|
---|
2272 | loc = args[1]
|
---|
2273 | try:
|
---|
2274 | hdd = vb.findMedium(loc, ctx['global'].constants.DeviceType_HardDisk)
|
---|
2275 | except:
|
---|
2276 | print "no HDD with path %s registered" %(loc)
|
---|
2277 | return 0
|
---|
2278 |
|
---|
2279 | progress = hdd.deleteStorage()
|
---|
2280 | progressBar(ctx,progress)
|
---|
2281 |
|
---|
2282 | return 0
|
---|
2283 |
|
---|
2284 | def registerIsoCmd(ctx,args):
|
---|
2285 | if (len(args) < 2):
|
---|
2286 | print "usage: registerIso location"
|
---|
2287 | return 0
|
---|
2288 | vb = ctx['vb']
|
---|
2289 | loc = args[1]
|
---|
2290 | id = ""
|
---|
2291 | iso = vb.openDVDImage(loc, id)
|
---|
2292 | print "registered ISO as %s" %(iso.id)
|
---|
2293 | return 0
|
---|
2294 |
|
---|
2295 | def unregisterIsoCmd(ctx,args):
|
---|
2296 | if (len(args) != 2):
|
---|
2297 | print "usage: unregisterIso path"
|
---|
2298 | return 0
|
---|
2299 |
|
---|
2300 | vb = ctx['vb']
|
---|
2301 | loc = args[1]
|
---|
2302 | try:
|
---|
2303 | dvd = vb.findMedium(loc, )
|
---|
2304 | except:
|
---|
2305 | print "no DVD with path %s registered" %(loc)
|
---|
2306 | return 0
|
---|
2307 |
|
---|
2308 | progress = dvd.close()
|
---|
2309 | print "Unregistered ISO at %s" %(colPath(ctx,dvd.location))
|
---|
2310 |
|
---|
2311 | return 0
|
---|
2312 |
|
---|
2313 | def removeIsoCmd(ctx,args):
|
---|
2314 | if (len(args) != 2):
|
---|
2315 | print "usage: removeIso path"
|
---|
2316 | return 0
|
---|
2317 |
|
---|
2318 | vb = ctx['vb']
|
---|
2319 | loc = args[1]
|
---|
2320 | try:
|
---|
2321 | dvd = vb.findMedium(loc, ctx['global'].constants.DeviceType_DVD)
|
---|
2322 | except:
|
---|
2323 | print "no DVD with path %s registered" %(loc)
|
---|
2324 | return 0
|
---|
2325 |
|
---|
2326 | progress = dvd.deleteStorage()
|
---|
2327 | if progressBar(ctx,progress):
|
---|
2328 | print "Removed ISO at %s" %(colPath(ctx,dvd.location))
|
---|
2329 | else:
|
---|
2330 | reportError(ctx,progress)
|
---|
2331 | return 0
|
---|
2332 |
|
---|
2333 | def attachIsoCmd(ctx,args):
|
---|
2334 | if (len(args) < 3):
|
---|
2335 | print "usage: attachIso vm iso controller port:slot"
|
---|
2336 | return 0
|
---|
2337 |
|
---|
2338 | mach = argsToMach(ctx,args)
|
---|
2339 | if mach is None:
|
---|
2340 | return 0
|
---|
2341 | vb = ctx['vb']
|
---|
2342 | loc = args[2]
|
---|
2343 | try:
|
---|
2344 | dvd = vb.findMedium(loc, ctx['global'].constants.DeviceType_DVD)
|
---|
2345 | except:
|
---|
2346 | print "no DVD with path %s registered" %(loc)
|
---|
2347 | return 0
|
---|
2348 | if len(args) > 3:
|
---|
2349 | ctr = args[3]
|
---|
2350 | (port,slot) = args[4].split(":")
|
---|
2351 | else:
|
---|
2352 | [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
|
---|
2353 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd))
|
---|
2354 | return 0
|
---|
2355 |
|
---|
2356 | def detachIsoCmd(ctx,args):
|
---|
2357 | if (len(args) < 3):
|
---|
2358 | print "usage: detachIso vm iso"
|
---|
2359 | return 0
|
---|
2360 |
|
---|
2361 | mach = argsToMach(ctx,args)
|
---|
2362 | if mach is None:
|
---|
2363 | return 0
|
---|
2364 | vb = ctx['vb']
|
---|
2365 | loc = args[2]
|
---|
2366 | try:
|
---|
2367 | dvd = vb.findMedium(loc, ctx['global'].constants.DeviceType_DVD)
|
---|
2368 | except:
|
---|
2369 | print "no DVD with path %s registered" %(loc)
|
---|
2370 | return 0
|
---|
2371 |
|
---|
2372 | detachMedium(ctx, mach.id, dvd)
|
---|
2373 | return 0
|
---|
2374 |
|
---|
2375 | def mountIsoCmd(ctx,args):
|
---|
2376 | if (len(args) < 3):
|
---|
2377 | print "usage: mountIso vm iso controller port:slot"
|
---|
2378 | return 0
|
---|
2379 |
|
---|
2380 | mach = argsToMach(ctx,args)
|
---|
2381 | if mach is None:
|
---|
2382 | return 0
|
---|
2383 | vb = ctx['vb']
|
---|
2384 | loc = args[2]
|
---|
2385 | try:
|
---|
2386 | dvd = vb.findMedium(loc, ctx['global'].constants.DeviceType_DVD)
|
---|
2387 | except:
|
---|
2388 | print "no DVD with path %s registered" %(loc)
|
---|
2389 | return 0
|
---|
2390 |
|
---|
2391 | if len(args) > 3:
|
---|
2392 | ctr = args[3]
|
---|
2393 | (port,slot) = args[4].split(":")
|
---|
2394 | else:
|
---|
2395 | # autodetect controller and location, just find first controller with media == DVD
|
---|
2396 | [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
|
---|
2397 |
|
---|
2398 | cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd, True])
|
---|
2399 |
|
---|
2400 | return 0
|
---|
2401 |
|
---|
2402 | def unmountIsoCmd(ctx,args):
|
---|
2403 | if (len(args) < 2):
|
---|
2404 | print "usage: unmountIso vm controller port:slot"
|
---|
2405 | return 0
|
---|
2406 |
|
---|
2407 | mach = argsToMach(ctx,args)
|
---|
2408 | if mach is None:
|
---|
2409 | return 0
|
---|
2410 | vb = ctx['vb']
|
---|
2411 |
|
---|
2412 | if len(args) > 3:
|
---|
2413 | ctr = args[2]
|
---|
2414 | (port,slot) = args[3].split(":")
|
---|
2415 | else:
|
---|
2416 | # autodetect controller and location, just find first controller with media == DVD
|
---|
2417 | [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
|
---|
2418 |
|
---|
2419 | cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, None, True])
|
---|
2420 |
|
---|
2421 | return 0
|
---|
2422 |
|
---|
2423 | def attachCtr(ctx,mach,args):
|
---|
2424 | [name, bus, type] = args
|
---|
2425 | ctr = mach.addStorageController(name, bus)
|
---|
2426 | if type != None:
|
---|
2427 | ctr.controllerType = type
|
---|
2428 |
|
---|
2429 | def attachCtrCmd(ctx,args):
|
---|
2430 | if (len(args) < 4):
|
---|
2431 | print "usage: attachCtr vm cname bus <type>"
|
---|
2432 | return 0
|
---|
2433 |
|
---|
2434 | if len(args) > 4:
|
---|
2435 | type = enumFromString(ctx,'StorageControllerType', args[4])
|
---|
2436 | if type == None:
|
---|
2437 | print "Controller type %s unknown" %(args[4])
|
---|
2438 | return 0
|
---|
2439 | else:
|
---|
2440 | type = None
|
---|
2441 |
|
---|
2442 | mach = argsToMach(ctx,args)
|
---|
2443 | if mach is None:
|
---|
2444 | return 0
|
---|
2445 | bus = enumFromString(ctx,'StorageBus', args[3])
|
---|
2446 | if bus is None:
|
---|
2447 | print "Bus type %s unknown" %(args[3])
|
---|
2448 | return 0
|
---|
2449 | name = args[2]
|
---|
2450 | cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
|
---|
2451 | return 0
|
---|
2452 |
|
---|
2453 | def detachCtrCmd(ctx,args):
|
---|
2454 | if (len(args) < 3):
|
---|
2455 | print "usage: detachCtr vm name"
|
---|
2456 | return 0
|
---|
2457 |
|
---|
2458 | mach = argsToMach(ctx,args)
|
---|
2459 | if mach is None:
|
---|
2460 | return 0
|
---|
2461 | ctr = args[2]
|
---|
2462 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
|
---|
2463 | return 0
|
---|
2464 |
|
---|
2465 | def usbctr(ctx,mach,console,args):
|
---|
2466 | if (args[0]):
|
---|
2467 | console.attachUSBDevice(args[1])
|
---|
2468 | else:
|
---|
2469 | console.detachUSBDevice(args[1])
|
---|
2470 |
|
---|
2471 | def attachUsbCmd(ctx,args):
|
---|
2472 | if (len(args) < 3):
|
---|
2473 | print "usage: attachUsb vm deviceuid"
|
---|
2474 | return 0
|
---|
2475 |
|
---|
2476 | mach = argsToMach(ctx,args)
|
---|
2477 | if mach is None:
|
---|
2478 | return 0
|
---|
2479 | dev = args[2]
|
---|
2480 | cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
|
---|
2481 | return 0
|
---|
2482 |
|
---|
2483 | def detachUsbCmd(ctx,args):
|
---|
2484 | if (len(args) < 3):
|
---|
2485 | print "usage: detachUsb vm deviceuid"
|
---|
2486 | return 0
|
---|
2487 |
|
---|
2488 | mach = argsToMach(ctx,args)
|
---|
2489 | if mach is None:
|
---|
2490 | return 0
|
---|
2491 | dev = args[2]
|
---|
2492 | cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
|
---|
2493 | return 0
|
---|
2494 |
|
---|
2495 |
|
---|
2496 | def guiCmd(ctx,args):
|
---|
2497 | if (len(args) > 1):
|
---|
2498 | print "usage: gui"
|
---|
2499 | return 0
|
---|
2500 |
|
---|
2501 | binDir = ctx['global'].getBinDir()
|
---|
2502 |
|
---|
2503 | vbox = os.path.join(binDir, 'VirtualBox')
|
---|
2504 | try:
|
---|
2505 | os.system(vbox)
|
---|
2506 | except KeyboardInterrupt:
|
---|
2507 | # to allow interruption
|
---|
2508 | pass
|
---|
2509 | return 0
|
---|
2510 |
|
---|
2511 | def shareFolderCmd(ctx,args):
|
---|
2512 | if (len(args) < 4):
|
---|
2513 | print "usage: shareFolder vm path name <writable> <persistent>"
|
---|
2514 | return 0
|
---|
2515 |
|
---|
2516 | mach = argsToMach(ctx,args)
|
---|
2517 | if mach is None:
|
---|
2518 | return 0
|
---|
2519 | path = args[2]
|
---|
2520 | name = args[3]
|
---|
2521 | writable = False
|
---|
2522 | persistent = False
|
---|
2523 | if len(args) > 4:
|
---|
2524 | for a in args[4:]:
|
---|
2525 | if a == 'writable':
|
---|
2526 | writable = True
|
---|
2527 | if a == 'persistent':
|
---|
2528 | persistent = True
|
---|
2529 | if persistent:
|
---|
2530 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.createSharedFolder(name, path, writable), [])
|
---|
2531 | else:
|
---|
2532 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.createSharedFolder(name, path, writable)])
|
---|
2533 | return 0
|
---|
2534 |
|
---|
2535 | def unshareFolderCmd(ctx,args):
|
---|
2536 | if (len(args) < 3):
|
---|
2537 | print "usage: unshareFolder vm name"
|
---|
2538 | return 0
|
---|
2539 |
|
---|
2540 | mach = argsToMach(ctx,args)
|
---|
2541 | if mach is None:
|
---|
2542 | return 0
|
---|
2543 | name = args[2]
|
---|
2544 | found = False
|
---|
2545 | for sf in ctx['global'].getArray(mach, 'sharedFolders'):
|
---|
2546 | if sf.name == name:
|
---|
2547 | cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeSharedFolder(name), [])
|
---|
2548 | found = True
|
---|
2549 | break
|
---|
2550 | if not found:
|
---|
2551 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.removeSharedFolder(name)])
|
---|
2552 | return 0
|
---|
2553 |
|
---|
2554 |
|
---|
2555 | def snapshotCmd(ctx,args):
|
---|
2556 | if (len(args) < 2 or args[1] == 'help'):
|
---|
2557 | print "Take snapshot: snapshot vm take name <description>"
|
---|
2558 | print "Restore snapshot: snapshot vm restore name"
|
---|
2559 | print "Merge snapshot: snapshot vm merge name"
|
---|
2560 | return 0
|
---|
2561 |
|
---|
2562 | mach = argsToMach(ctx,args)
|
---|
2563 | if mach is None:
|
---|
2564 | return 0
|
---|
2565 | cmd = args[2]
|
---|
2566 | if cmd == 'take':
|
---|
2567 | if (len(args) < 4):
|
---|
2568 | print "usage: snapshot vm take name <description>"
|
---|
2569 | return 0
|
---|
2570 | name = args[3]
|
---|
2571 | if (len(args) > 4):
|
---|
2572 | desc = args[4]
|
---|
2573 | else:
|
---|
2574 | desc = ""
|
---|
2575 | cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.takeSnapshot(name,desc)))
|
---|
2576 | return 0
|
---|
2577 |
|
---|
2578 | if cmd == 'restore':
|
---|
2579 | if (len(args) < 4):
|
---|
2580 | print "usage: snapshot vm restore name"
|
---|
2581 | return 0
|
---|
2582 | name = args[3]
|
---|
2583 | snap = mach.findSnapshot(name)
|
---|
2584 | cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
|
---|
2585 | return 0
|
---|
2586 |
|
---|
2587 | if cmd == 'restorecurrent':
|
---|
2588 | if (len(args) < 4):
|
---|
2589 | print "usage: snapshot vm restorecurrent"
|
---|
2590 | return 0
|
---|
2591 | snap = mach.currentSnapshot()
|
---|
2592 | cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
|
---|
2593 | return 0
|
---|
2594 |
|
---|
2595 | if cmd == 'delete':
|
---|
2596 | if (len(args) < 4):
|
---|
2597 | print "usage: snapshot vm delete name"
|
---|
2598 | return 0
|
---|
2599 | name = args[3]
|
---|
2600 | snap = mach.findSnapshot(name)
|
---|
2601 | cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.deleteSnapshot(snap.id)))
|
---|
2602 | return 0
|
---|
2603 |
|
---|
2604 | print "Command '%s' is unknown" %(cmd)
|
---|
2605 | return 0
|
---|
2606 |
|
---|
2607 | def natAlias(ctx, mach, nicnum, nat, args=[]):
|
---|
2608 | """This command shows/alters NAT's alias settings.
|
---|
2609 | usage: nat <vm> <nicnum> alias [default|[log] [proxyonly] [sameports]]
|
---|
2610 | default - set settings to default values
|
---|
2611 | log - switch on alias logging
|
---|
2612 | proxyonly - switch proxyonly mode on
|
---|
2613 | sameports - enforces NAT using the same ports
|
---|
2614 | """
|
---|
2615 | alias = {
|
---|
2616 | 'log': 0x1,
|
---|
2617 | 'proxyonly': 0x2,
|
---|
2618 | 'sameports': 0x4
|
---|
2619 | }
|
---|
2620 | if len(args) == 1:
|
---|
2621 | first = 0
|
---|
2622 | msg = ''
|
---|
2623 | for aliasmode, aliaskey in alias.iteritems():
|
---|
2624 | if first == 0:
|
---|
2625 | first = 1
|
---|
2626 | else:
|
---|
2627 | msg += ', '
|
---|
2628 | if int(nat.aliasMode) & aliaskey:
|
---|
2629 | msg += '{0}: {1}'.format(aliasmode, 'on')
|
---|
2630 | else:
|
---|
2631 | msg += '{0}: {1}'.format(aliasmode, 'off')
|
---|
2632 | msg += ')'
|
---|
2633 | return (0, [msg])
|
---|
2634 | else:
|
---|
2635 | nat.aliasMode = 0
|
---|
2636 | if 'default' not in args:
|
---|
2637 | for a in range(1, len(args)):
|
---|
2638 | if not alias.has_key(args[a]):
|
---|
2639 | print 'Invalid alias mode: ' + args[a]
|
---|
2640 | print natAlias.__doc__
|
---|
2641 | return (1, None)
|
---|
2642 | nat.aliasMode = int(nat.aliasMode) | alias[args[a]];
|
---|
2643 | return (0, None)
|
---|
2644 |
|
---|
2645 | def natSettings(ctx, mach, nicnum, nat, args):
|
---|
2646 | """This command shows/alters NAT settings.
|
---|
2647 | usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
|
---|
2648 | mtu - set mtu <= 16000
|
---|
2649 | socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
|
---|
2650 | tcpsndwnd/tcprcvwnd - sets size of initial tcp sending/receiving window
|
---|
2651 | """
|
---|
2652 | if len(args) == 1:
|
---|
2653 | (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings();
|
---|
2654 | if mtu == 0: mtu = 1500
|
---|
2655 | if socksndbuf == 0: socksndbuf = 64
|
---|
2656 | if sockrcvbuf == 0: sockrcvbuf = 64
|
---|
2657 | if tcpsndwnd == 0: tcpsndwnd = 64
|
---|
2658 | if tcprcvwnd == 0: tcprcvwnd = 64
|
---|
2659 | msg = 'mtu:{0} socket(snd:{1}, rcv:{2}) tcpwnd(snd:{3}, rcv:{4})'.format(mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd);
|
---|
2660 | return (0, [msg])
|
---|
2661 | else:
|
---|
2662 | if args[1] < 16000:
|
---|
2663 | print 'invalid mtu value ({0} no in range [65 - 16000])'.format(args[1])
|
---|
2664 | return (1, None)
|
---|
2665 | for i in range(2, len(args)):
|
---|
2666 | if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024:
|
---|
2667 | print 'invalid {0} parameter ({1} not in range [8-1024])'.format(i, args[i])
|
---|
2668 | return (1, None)
|
---|
2669 | a = [args[1]]
|
---|
2670 | if len(args) < 6:
|
---|
2671 | for i in range(2, len(args)): a.append(args[i])
|
---|
2672 | for i in range(len(args), 6): a.append(0)
|
---|
2673 | else:
|
---|
2674 | for i in range(2, len(args)): a.append(args[i])
|
---|
2675 | #print a
|
---|
2676 | nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))
|
---|
2677 | return (0, None)
|
---|
2678 |
|
---|
2679 | def natDns(ctx, mach, nicnum, nat, args):
|
---|
2680 | """This command shows/alters DNS's NAT settings
|
---|
2681 | usage: nat <vm> <nicnum> dns [passdomain] [proxy] [usehostresolver]
|
---|
2682 | passdomain - enforces builtin DHCP server to pass domain
|
---|
2683 | proxy - switch on builtin NAT DNS proxying mechanism
|
---|
2684 | usehostresolver - proxies all DNS requests to Host Resolver interface
|
---|
2685 | """
|
---|
2686 | yesno = {0: 'off', 1: 'on'}
|
---|
2687 | if len(args) == 1:
|
---|
2688 | msg = 'passdomain:{0}, proxy:{1}, usehostresolver:{2}'.format(yesno[int(nat.dnsPassDomain)], yesno[int(nat.dnsProxy)], yesno[int(nat.dnsUseHostResolver)])
|
---|
2689 | return (0, [msg])
|
---|
2690 | else:
|
---|
2691 | nat.dnsPassDomain = 'passdomain' in args
|
---|
2692 | nat.dnsProxy = 'proxy' in args
|
---|
2693 | nat.dnsUseHostResolver = 'usehostresolver' in args
|
---|
2694 | return (0, None)
|
---|
2695 |
|
---|
2696 | def natTftp(ctx, mach, nicnum, nat, args):
|
---|
2697 | """This command shows/alters TFTP settings
|
---|
2698 | usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
|
---|
2699 | prefix - alters prefix TFTP settings
|
---|
2700 | bootfile - alters bootfile TFTP settings
|
---|
2701 | server - sets booting server
|
---|
2702 | """
|
---|
2703 | if len(args) == 1:
|
---|
2704 | server = nat.tftpNextServer
|
---|
2705 | if server is None:
|
---|
2706 | server = nat.network
|
---|
2707 | if server is None:
|
---|
2708 | server = '10.0.{0}/24'.format(int(nicnum) + 2)
|
---|
2709 | (server,mask) = server.split('/')
|
---|
2710 | while server.count('.') != 3:
|
---|
2711 | server += '.0'
|
---|
2712 | (a,b,c,d) = server.split('.')
|
---|
2713 | server = '{0}.{1}.{2}.4'.format(a,b,c)
|
---|
2714 | prefix = nat.tftpPrefix
|
---|
2715 | if prefix is None:
|
---|
2716 | prefix = '{0}/TFTP/'.format(ctx['vb'].homeFolder)
|
---|
2717 | bootfile = nat.tftpBootFile
|
---|
2718 | if bootfile is None:
|
---|
2719 | bootfile = '{0}.pxe'.format(mach.name)
|
---|
2720 | msg = 'server:{0}, prefix:{1}, bootfile:{2}'.format(server, prefix, bootfile)
|
---|
2721 | return (0, [msg])
|
---|
2722 | else:
|
---|
2723 |
|
---|
2724 | cmd = args[1]
|
---|
2725 | if len(args) != 3:
|
---|
2726 | print 'invalid args:', args
|
---|
2727 | print natTftp.__doc__
|
---|
2728 | return (1, None)
|
---|
2729 | if cmd == 'prefix': nat.tftpPrefix = args[2]
|
---|
2730 | elif cmd == 'bootfile': nat.tftpBootFile = args[2]
|
---|
2731 | elif cmd == 'server': nat.tftpNextServer = args[2]
|
---|
2732 | else:
|
---|
2733 | print "invalid cmd:", cmd
|
---|
2734 | return (1, None)
|
---|
2735 | return (0, None)
|
---|
2736 |
|
---|
2737 | def natPortForwarding(ctx, mach, nicnum, nat, args):
|
---|
2738 | """This command shows/manages port-forwarding settings
|
---|
2739 | usage:
|
---|
2740 | nat <vm> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
|
---|
2741 | |[no_name tcp|udp <hostip> <hostport> <guestip> <guestport>]
|
---|
2742 | |[ex tcp|udp <pf-name> <hostip> <hostport> <guestip> <guestport>]
|
---|
2743 | |[delete <pf-name>]
|
---|
2744 | """
|
---|
2745 | if len(args) == 1:
|
---|
2746 | # note: keys/values are swapped in defining part of the function
|
---|
2747 | proto = {0: 'udp', 1: 'tcp'}
|
---|
2748 | msg = []
|
---|
2749 | pfs = ctx['global'].getArray(nat, 'redirects')
|
---|
2750 | for pf in pfs:
|
---|
2751 | (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(',')
|
---|
2752 | msg.append('{0}: {1} {2}:{3} => {4}:{5}'.format(pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
|
---|
2753 | return (0, msg) # msg is array
|
---|
2754 | else:
|
---|
2755 | proto = {'udp': 0, 'tcp': 1}
|
---|
2756 | pfcmd = {
|
---|
2757 | 'simple': {
|
---|
2758 | 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 5,
|
---|
2759 | 'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4]))
|
---|
2760 | },
|
---|
2761 | 'no_name': {
|
---|
2762 | 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 7,
|
---|
2763 | 'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6]))
|
---|
2764 | },
|
---|
2765 | 'ex': {
|
---|
2766 | 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 8,
|
---|
2767 | 'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7]))
|
---|
2768 | },
|
---|
2769 | 'delete': {
|
---|
2770 | 'validate': lambda: len(args) == 3,
|
---|
2771 | 'func': lambda: nat.removeRedirect(args[2])
|
---|
2772 | }
|
---|
2773 | }
|
---|
2774 |
|
---|
2775 | if not pfcmd[args[1]]['validate']():
|
---|
2776 | print 'invalid port-forwarding or args of sub command ', args[1]
|
---|
2777 | print natPortForwarding.__doc__
|
---|
2778 | return (1, None)
|
---|
2779 |
|
---|
2780 | a = pfcmd[args[1]]['func']()
|
---|
2781 | return (0, None)
|
---|
2782 |
|
---|
2783 | def natNetwork(ctx, mach, nicnum, nat, args):
|
---|
2784 | """This command shows/alters NAT network settings
|
---|
2785 | usage: nat <vm> <nicnum> network [<network>]
|
---|
2786 | """
|
---|
2787 | if len(args) == 1:
|
---|
2788 | if nat.network is not None and len(str(nat.network)) != 0:
|
---|
2789 | msg = '\'%s\'' % (nat.network)
|
---|
2790 | else:
|
---|
2791 | msg = '10.0.{0}.0/24'.format(int(nicnum) + 2)
|
---|
2792 | return (0, [msg])
|
---|
2793 | else:
|
---|
2794 | (addr, mask) = args[1].split('/')
|
---|
2795 | if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
|
---|
2796 | print 'Invalid arguments'
|
---|
2797 | return (1, None)
|
---|
2798 | nat.network = args[1]
|
---|
2799 | return (0, None)
|
---|
2800 |
|
---|
2801 | def natCmd(ctx, args):
|
---|
2802 | """This command is entry point to NAT settins management
|
---|
2803 | usage: nat <vm> <nicnum> <cmd> <cmd-args>
|
---|
2804 | cmd - [alias|settings|tftp|dns|pf|network]
|
---|
2805 | for more information about commands:
|
---|
2806 | nat help <cmd>
|
---|
2807 | """
|
---|
2808 |
|
---|
2809 | natcommands = {
|
---|
2810 | 'alias' : natAlias,
|
---|
2811 | 'settings' : natSettings,
|
---|
2812 | 'tftp': natTftp,
|
---|
2813 | 'dns': natDns,
|
---|
2814 | 'pf': natPortForwarding,
|
---|
2815 | 'network': natNetwork
|
---|
2816 | }
|
---|
2817 |
|
---|
2818 | if len(args) < 2 or args[1] == 'help':
|
---|
2819 | if len(args) > 2:
|
---|
2820 | print natcommands[args[2]].__doc__
|
---|
2821 | else:
|
---|
2822 | print natCmd.__doc__
|
---|
2823 | return 0
|
---|
2824 | if len(args) == 1 or len(args) < 4 or args[3] not in natcommands:
|
---|
2825 | print natCmd.__doc__
|
---|
2826 | return 0
|
---|
2827 | mach = ctx['argsToMach'](args)
|
---|
2828 | if mach == None:
|
---|
2829 | print "please specify vm"
|
---|
2830 | return 0
|
---|
2831 | if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
|
---|
2832 | print 'please specify adapter num {0} isn\'t in range [0-{1}]'.format(args[2], ctx['vb'].systemProperties.networkAdapterCount)
|
---|
2833 | return 0
|
---|
2834 | nicnum = int(args[2])
|
---|
2835 | cmdargs = []
|
---|
2836 | for i in range(3, len(args)):
|
---|
2837 | cmdargs.append(args[i])
|
---|
2838 |
|
---|
2839 | # @todo vvl if nicnum is missed but command is entered
|
---|
2840 | # use NAT func for every adapter on machine.
|
---|
2841 | func = args[3]
|
---|
2842 | rosession = 1
|
---|
2843 | session = None
|
---|
2844 | if len(cmdargs) > 1:
|
---|
2845 | rosession = 0
|
---|
2846 | session = ctx['global'].openMachineSession(mach, False);
|
---|
2847 | mach = session.machine;
|
---|
2848 |
|
---|
2849 | adapter = mach.getNetworkAdapter(nicnum)
|
---|
2850 | natEngine = adapter.natDriver
|
---|
2851 | (rc, report) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
|
---|
2852 | if rosession == 0:
|
---|
2853 | if rc == 0:
|
---|
2854 | mach.saveSettings()
|
---|
2855 | session.unlockMachine()
|
---|
2856 | elif report is not None:
|
---|
2857 | for r in report:
|
---|
2858 | msg ='{0} nic{1} {2}: {3}'.format(mach.name, nicnum, func, r)
|
---|
2859 | print msg
|
---|
2860 | return 0
|
---|
2861 |
|
---|
2862 | def nicSwitchOnOff(adapter, attr, args):
|
---|
2863 | if len(args) == 1:
|
---|
2864 | yesno = {0: 'off', 1: 'on'}
|
---|
2865 | r = yesno[int(adapter.__getattr__(attr))]
|
---|
2866 | return (0, r)
|
---|
2867 | else:
|
---|
2868 | yesno = {'off' : 0, 'on' : 1}
|
---|
2869 | if args[1] not in yesno:
|
---|
2870 | print '%s isn\'t acceptable, please choose %s' % (args[1], yesno.keys())
|
---|
2871 | return (1, None)
|
---|
2872 | adapter.__setattr__(attr, yesno[args[1]])
|
---|
2873 | return (0, None)
|
---|
2874 |
|
---|
2875 | def nicTraceSubCmd(ctx, vm, nicnum, adapter, args):
|
---|
2876 | '''
|
---|
2877 | usage: nic <vm> <nicnum> trace [on|off [file]]
|
---|
2878 | '''
|
---|
2879 | (rc, r) = nicSwitchOnOff(adapter, 'traceEnabled', args)
|
---|
2880 | if len(args) == 1 and rc == 0:
|
---|
2881 | r = '%s file:%s' % (r, adapter.traceFile)
|
---|
2882 | return (0, r)
|
---|
2883 | elif len(args) == 3 and rc == 0:
|
---|
2884 | adapter.traceFile = args[2]
|
---|
2885 | return (0, None)
|
---|
2886 |
|
---|
2887 | def nicLineSpeedSubCmd(ctx, vm, nicnum, adapter, args):
|
---|
2888 | if len(args) == 1:
|
---|
2889 | r = '%d kbps'%(adapter.lineSpeed)
|
---|
2890 | return (0, r)
|
---|
2891 | else:
|
---|
2892 | if not args[1].isdigit():
|
---|
2893 | print '%s isn\'t a number'.format(args[1])
|
---|
2894 | print (1, None)
|
---|
2895 | adapter.lineSpeed = int(args[1])
|
---|
2896 | return (0, None)
|
---|
2897 |
|
---|
2898 | def nicCableSubCmd(ctx, vm, nicnum, adapter, args):
|
---|
2899 | '''
|
---|
2900 | usage: nic <vm> <nicnum> cable [on|off]
|
---|
2901 | '''
|
---|
2902 | return nicSwitchOnOff(adapter, 'cableConnected', args)
|
---|
2903 |
|
---|
2904 | def nicEnableSubCmd(ctx, vm, nicnum, adapter, args):
|
---|
2905 | '''
|
---|
2906 | usage: nic <vm> <nicnum> enable [on|off]
|
---|
2907 | '''
|
---|
2908 | return nicSwitchOnOff(adapter, 'enabled', args)
|
---|
2909 |
|
---|
2910 | def nicTypeSubCmd(ctx, vm, nicnum, adapter, args):
|
---|
2911 | '''
|
---|
2912 | usage: nic <vm> <nicnum> type [Am79c970A|Am79c970A|I82540EM|I82545EM|I82543GC|Virtio]
|
---|
2913 | '''
|
---|
2914 | if len(args) == 1:
|
---|
2915 | nictypes = ctx['const'].all_values('NetworkAdapterType')
|
---|
2916 | for n in nictypes.keys():
|
---|
2917 | if str(adapter.adapterType) == str(nictypes[n]):
|
---|
2918 | return (0, str(n))
|
---|
2919 | return (1, None)
|
---|
2920 | else:
|
---|
2921 | nictypes = ctx['const'].all_values('NetworkAdapterType')
|
---|
2922 | if args[1] not in nictypes.keys():
|
---|
2923 | print '%s not in acceptable values (%s)' % (args[1], nictypes.keys())
|
---|
2924 | return (1, None)
|
---|
2925 | adapter.adapterType = nictypes[args[1]]
|
---|
2926 | return (0, None)
|
---|
2927 |
|
---|
2928 | def nicAttachmentSubCmd(ctx, vm, nicnum, adapter, args):
|
---|
2929 | '''
|
---|
2930 | usage: nic <vm> <nicnum> attachment [Null|NAT|Bridged <interface>|Internal <name>|HostOnly <interface>]
|
---|
2931 | '''
|
---|
2932 | if len(args) == 1:
|
---|
2933 | nicAttachmentType = {
|
---|
2934 | ctx['global'].constants.NetworkAttachmentType_Null: ('Null', ''),
|
---|
2935 | ctx['global'].constants.NetworkAttachmentType_NAT: ('NAT', ''),
|
---|
2936 | ctx['global'].constants.NetworkAttachmentType_Bridged: ('Bridged', adapter.hostInterface),
|
---|
2937 | ctx['global'].constants.NetworkAttachmentType_Internal: ('Internal', adapter.internalNetwork),
|
---|
2938 | ctx['global'].constants.NetworkAttachmentType_HostOnly: ('HostOnly', adapter.hostInterface),
|
---|
2939 | #ctx['global'].constants.NetworkAttachmentType_VDE: ('VDE', adapter.VDENetwork)
|
---|
2940 | }
|
---|
2941 | import types
|
---|
2942 | if type(adapter.attachmentType) != types.IntType:
|
---|
2943 | t = str(adapter.attachmentType)
|
---|
2944 | else:
|
---|
2945 | t = adapter.attachmentType
|
---|
2946 | (r, p) = nicAttachmentType[t]
|
---|
2947 | return (0, 'attachment:{0}, name:{1}'.format(r, p))
|
---|
2948 | else:
|
---|
2949 | nicAttachmentType = {
|
---|
2950 | 'Null': {
|
---|
2951 | 'v': lambda: len(args) == 2,
|
---|
2952 | 'p': lambda: 'do nothing',
|
---|
2953 | 'f': lambda: adapter.detach()},
|
---|
2954 | 'NAT': {
|
---|
2955 | 'v': lambda: len(args) == 2,
|
---|
2956 | 'p': lambda: 'do nothing',
|
---|
2957 | 'f': lambda: adapter.attachToNAT()},
|
---|
2958 | 'Bridged': {
|
---|
2959 | 'v': lambda: len(args) == 3,
|
---|
2960 | 'p': lambda: adapter.__setattr__('hostInterface', args[2]),
|
---|
2961 | 'f': lambda: adapter.attachToBridgedInterface()},
|
---|
2962 | 'Internal': {
|
---|
2963 | 'v': lambda: len(args) == 3,
|
---|
2964 | 'p': lambda: adapter.__setattr__('internalNetwork', args[2]),
|
---|
2965 | 'f': lambda: adapter.attachToInternalNetwork()},
|
---|
2966 | 'HostOnly': {
|
---|
2967 | 'v': lambda: len(args) == 2,
|
---|
2968 | 'p': lambda: adapter.__setattr__('hostInterface', args[2]),
|
---|
2969 | 'f': lambda: adapter.attachToHostOnlyInterface()},
|
---|
2970 | 'VDE': {
|
---|
2971 | 'v': lambda: len(args) == 3,
|
---|
2972 | 'p': lambda: adapter.__setattr__('VDENetwork', args[2]),
|
---|
2973 | 'f': lambda: adapter.attachToVDE()}
|
---|
2974 | }
|
---|
2975 | if args[1] not in nicAttachmentType.keys():
|
---|
2976 | print '{0} not in acceptable values ({1})'.format(args[1], nicAttachmentType.keys())
|
---|
2977 | return (1, None)
|
---|
2978 | if not nicAttachmentType[args[1]]['v']():
|
---|
2979 | print nicAttachmentType.__doc__
|
---|
2980 | return (1, None)
|
---|
2981 | nicAttachmentType[args[1]]['p']()
|
---|
2982 | nicAttachmentType[args[1]]['f']()
|
---|
2983 | return (0, None)
|
---|
2984 |
|
---|
2985 | def nicCmd(ctx, args):
|
---|
2986 | '''
|
---|
2987 | This command to manage network adapters
|
---|
2988 | usage: nic <vm> <nicnum> <cmd> <cmd-args>
|
---|
2989 | where cmd : attachment, trace, linespeed, cable, enable, type
|
---|
2990 | '''
|
---|
2991 | # 'command name':{'runtime': is_callable_at_runtime, 'op': function_name}
|
---|
2992 | niccomand = {
|
---|
2993 | 'attachment': nicAttachmentSubCmd,
|
---|
2994 | 'trace': nicTraceSubCmd,
|
---|
2995 | 'linespeed': nicLineSpeedSubCmd,
|
---|
2996 | 'cable': nicCableSubCmd,
|
---|
2997 | 'enable': nicEnableSubCmd,
|
---|
2998 | 'type': nicTypeSubCmd
|
---|
2999 | }
|
---|
3000 | if len(args) < 2 \
|
---|
3001 | or args[1] == 'help' \
|
---|
3002 | or (len(args) > 2 and args[3] not in niccomand):
|
---|
3003 | if len(args) == 3 \
|
---|
3004 | and args[2] in niccomand:
|
---|
3005 | print niccomand[args[2]].__doc__
|
---|
3006 | else:
|
---|
3007 | print nicCmd.__doc__
|
---|
3008 | return 0
|
---|
3009 |
|
---|
3010 | vm = ctx['argsToMach'](args)
|
---|
3011 | if vm is None:
|
---|
3012 | print 'please specify vm'
|
---|
3013 | return 0
|
---|
3014 |
|
---|
3015 | if len(args) < 3 \
|
---|
3016 | or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
|
---|
3017 | print 'please specify adapter num %d isn\'t in range [0-%d]'%(args[2], ctx['vb'].systemProperties.networkAdapterCount)
|
---|
3018 | return 0
|
---|
3019 | nicnum = int(args[2])
|
---|
3020 | cmdargs = args[3:]
|
---|
3021 | func = args[3]
|
---|
3022 | session = None
|
---|
3023 | session = ctx['global'].openMachineSession(vm)
|
---|
3024 | vm = session.machine
|
---|
3025 | adapter = vm.getNetworkAdapter(nicnum)
|
---|
3026 | (rc, report) = niccomand[func](ctx, vm, nicnum, adapter, cmdargs)
|
---|
3027 | if rc == 0:
|
---|
3028 | vm.saveSettings()
|
---|
3029 | if report is not None:
|
---|
3030 | print '%s nic %d %s: %s' % (vm.name, nicnum, args[3], report)
|
---|
3031 | session.unlockMachine()
|
---|
3032 | return 0
|
---|
3033 |
|
---|
3034 |
|
---|
3035 | def promptCmd(ctx, args):
|
---|
3036 | if len(args) < 2:
|
---|
3037 | print "Current prompt: '%s'" %(ctx['prompt'])
|
---|
3038 | return 0
|
---|
3039 |
|
---|
3040 | ctx['prompt'] = args[1]
|
---|
3041 | return 0
|
---|
3042 |
|
---|
3043 | def foreachCmd(ctx, args):
|
---|
3044 | if len(args) < 3:
|
---|
3045 | print "usage: foreach scope command, where scope is XPath-like expression //vms/vm[@CPUCount='2']"
|
---|
3046 | return 0
|
---|
3047 |
|
---|
3048 | scope = args[1]
|
---|
3049 | cmd = args[2]
|
---|
3050 | elems = eval_xpath(ctx,scope)
|
---|
3051 | try:
|
---|
3052 | for e in elems:
|
---|
3053 | e.apply(cmd)
|
---|
3054 | except:
|
---|
3055 | print "Error executing"
|
---|
3056 | traceback.print_exc()
|
---|
3057 | return 0
|
---|
3058 |
|
---|
3059 | def foreachvmCmd(ctx, args):
|
---|
3060 | if len(args) < 2:
|
---|
3061 | print "foreachvm command <args>"
|
---|
3062 | return 0
|
---|
3063 | cmdargs = args[1:]
|
---|
3064 | cmdargs.insert(1, '')
|
---|
3065 | for m in getMachines(ctx):
|
---|
3066 | cmdargs[1] = m.id
|
---|
3067 | runCommandArgs(ctx, cmdargs)
|
---|
3068 | return 0
|
---|
3069 |
|
---|
3070 | def recordDemoCmd(ctx, args):
|
---|
3071 | if (len(args) < 3):
|
---|
3072 | print "usage: recordDemo vm filename (duration)"
|
---|
3073 | return 0
|
---|
3074 | mach = argsToMach(ctx,args)
|
---|
3075 | if mach == None:
|
---|
3076 | return 0
|
---|
3077 | filename = args[2]
|
---|
3078 | dur = 10000
|
---|
3079 | if len(args) > 3:
|
---|
3080 | dur = float(args[3])
|
---|
3081 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: recordDemo(ctx, console, filename, dur)])
|
---|
3082 | return 0
|
---|
3083 |
|
---|
3084 | def playbackDemoCmd(ctx, args):
|
---|
3085 | if (len(args) < 3):
|
---|
3086 | print "usage: playbackDemo vm filename (duration)"
|
---|
3087 | return 0
|
---|
3088 | mach = argsToMach(ctx,args)
|
---|
3089 | if mach == None:
|
---|
3090 | return 0
|
---|
3091 | filename = args[2]
|
---|
3092 | dur = 10000
|
---|
3093 | if len(args) > 3:
|
---|
3094 | dur = float(args[3])
|
---|
3095 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: playbackDemo(ctx, console, filename, dur)])
|
---|
3096 | return 0
|
---|
3097 |
|
---|
3098 |
|
---|
3099 | def pciAddr(ctx,addr):
|
---|
3100 | str = "%d:%d.%d" %(addr >> 8, (addr & 0xff) >> 3, addr & 7)
|
---|
3101 | return colPci(ctx, str)
|
---|
3102 |
|
---|
3103 | def lspci(ctx, console):
|
---|
3104 | assigned = ctx['global'].getArray(console.machine, 'pciDeviceAssignments')
|
---|
3105 | for a in assigned:
|
---|
3106 | if a.isPhysicalDevice:
|
---|
3107 | print "%s: assigned host device %s" %(colDev(ctx, a.name), pciAddr(ctx, a.hostAddress))
|
---|
3108 |
|
---|
3109 | atts = ctx['global'].getArray(console, 'attachedPciDevices')
|
---|
3110 | for a in atts:
|
---|
3111 | if a.isPhysicalDevice:
|
---|
3112 | print "%s: physical, guest %s, host %s" %(colDev(a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress))
|
---|
3113 | else:
|
---|
3114 | print "%s: virtual, guest %s" %(colDev(ctx, a.name), pciAddr(ctx, a.guestAddress))
|
---|
3115 | return
|
---|
3116 |
|
---|
3117 | def parsePci(str):
|
---|
3118 | pcire = re.compile(r'(?P<b>\d+):(?P<d>\d+)\.(?P<f>\d)')
|
---|
3119 | m = pcire.search(str)
|
---|
3120 | if m is None:
|
---|
3121 | return -1
|
---|
3122 | dict = m.groupdict()
|
---|
3123 | return ((int(dict['b'])) << 8) | ((int(dict['d'])) << 3) | int(dict['f'])
|
---|
3124 |
|
---|
3125 | def lspciCmd(ctx, args):
|
---|
3126 | if (len(args) < 2):
|
---|
3127 | print "usage: lspci vm"
|
---|
3128 | return 0
|
---|
3129 | mach = argsToMach(ctx,args)
|
---|
3130 | if mach == None:
|
---|
3131 | return 0
|
---|
3132 | cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: lspci(ctx, console)])
|
---|
3133 | return 0
|
---|
3134 |
|
---|
3135 | def attachpciCmd(ctx, args):
|
---|
3136 | if (len(args) < 3):
|
---|
3137 | print "usage: attachpci vm hostpci <guestpci>"
|
---|
3138 | return 0
|
---|
3139 | mach = argsToMach(ctx,args)
|
---|
3140 | if mach == None:
|
---|
3141 | return 0
|
---|
3142 | hostaddr = parsePci(args[2])
|
---|
3143 | if hostaddr == -1:
|
---|
3144 | print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" %(args[2])
|
---|
3145 | return 0
|
---|
3146 |
|
---|
3147 | if (len(args) > 3):
|
---|
3148 | guestaddr = parsePci(args[3])
|
---|
3149 | if guestaddr == -1:
|
---|
3150 | print "invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" %(args[3])
|
---|
3151 | return 0
|
---|
3152 | else:
|
---|
3153 | guestaddr = hostaddr
|
---|
3154 | cmdClosedVm(ctx, mach, lambda ctx,mach,a: mach.attachHostPciDevice(hostaddr, guestaddr, True))
|
---|
3155 | return 0
|
---|
3156 |
|
---|
3157 | def detachpciCmd(ctx, args):
|
---|
3158 | if (len(args) < 3):
|
---|
3159 | print "usage: detachpci vm hostpci"
|
---|
3160 | return 0
|
---|
3161 | mach = argsToMach(ctx,args)
|
---|
3162 | if mach == None:
|
---|
3163 | return 0
|
---|
3164 | hostaddr = parsePci(args[2])
|
---|
3165 | if hostaddr == -1:
|
---|
3166 | print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" %(args[2])
|
---|
3167 | return 0
|
---|
3168 |
|
---|
3169 | cmdClosedVm(ctx, mach, lambda ctx,mach,a: mach.detachHostPciDevice(hostaddr))
|
---|
3170 | return 0
|
---|
3171 |
|
---|
3172 | def gotoCmd(ctx, args):
|
---|
3173 | if (len(args) < 2):
|
---|
3174 | print "usage: goto line"
|
---|
3175 | return 0
|
---|
3176 |
|
---|
3177 | line = int(args[1])
|
---|
3178 |
|
---|
3179 | ctx['scriptLine'] = line
|
---|
3180 |
|
---|
3181 | return 0
|
---|
3182 |
|
---|
3183 | aliases = {'s':'start',
|
---|
3184 | 'i':'info',
|
---|
3185 | 'l':'list',
|
---|
3186 | 'h':'help',
|
---|
3187 | 'a':'alias',
|
---|
3188 | 'q':'quit', 'exit':'quit',
|
---|
3189 | 'tg': 'typeGuest',
|
---|
3190 | 'v':'verbose'}
|
---|
3191 |
|
---|
3192 | commands = {'help':['Prints help information', helpCmd, 0],
|
---|
3193 | 'start':['Start virtual machine by name or uuid: start Linux headless', startCmd, 0],
|
---|
3194 | 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
|
---|
3195 | 'removeVm':['Remove virtual machine', removeVmCmd, 0],
|
---|
3196 | 'pause':['Pause virtual machine', pauseCmd, 0],
|
---|
3197 | 'resume':['Resume virtual machine', resumeCmd, 0],
|
---|
3198 | 'save':['Save execution state of virtual machine', saveCmd, 0],
|
---|
3199 | 'stats':['Stats for virtual machine', statsCmd, 0],
|
---|
3200 | 'powerdown':['Power down virtual machine', powerdownCmd, 0],
|
---|
3201 | 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
|
---|
3202 | 'list':['Shows known virtual machines', listCmd, 0],
|
---|
3203 | 'info':['Shows info on machine', infoCmd, 0],
|
---|
3204 | 'ginfo':['Shows info on guest', ginfoCmd, 0],
|
---|
3205 | 'gexec':['Executes program in the guest', gexecCmd, 0],
|
---|
3206 | 'gcopy':['Copy file to the guest', gcopyCmd, 0],
|
---|
3207 | 'gpipe':['Pipe between host and guest', gpipeCmd, 0],
|
---|
3208 | 'alias':['Control aliases', aliasCmd, 0],
|
---|
3209 | 'verbose':['Toggle verbosity', verboseCmd, 0],
|
---|
3210 | 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
|
---|
3211 | 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
|
---|
3212 | 'quit':['Exits', quitCmd, 0],
|
---|
3213 | 'host':['Show host information', hostCmd, 0],
|
---|
3214 | 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
|
---|
3215 | 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
|
---|
3216 | 'monitorGuestKbd':['Monitor guest keyboardfor some time: monitorGuestKbd Win32 10', monitorGuestKbdCmd, 0],
|
---|
3217 | 'monitorGuestMouse':['Monitor guest keyboardfor some time: monitorGuestMouse Win32 10', monitorGuestMouseCmd, 0],
|
---|
3218 | 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
|
---|
3219 | 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
|
---|
3220 | 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
|
---|
3221 | 'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
|
---|
3222 | 'findAssert':['Find assert in log file of the VM, : findAssert Win32', findAssertCmd, 0],
|
---|
3223 | 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
|
---|
3224 | 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
|
---|
3225 | 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
|
---|
3226 | 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
|
---|
3227 | 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
|
---|
3228 | 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768 0', screenshotCmd, 0],
|
---|
3229 | 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
|
---|
3230 | 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
|
---|
3231 | 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
|
---|
3232 | 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
|
---|
3233 | 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
|
---|
3234 | 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
|
---|
3235 | 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
|
---|
3236 | 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
|
---|
3237 | 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
|
---|
3238 | 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
|
---|
3239 | 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
|
---|
3240 | 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
|
---|
3241 | 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
|
---|
3242 | 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
|
---|
3243 | 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
|
---|
3244 | 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
|
---|
3245 | 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
|
---|
3246 | 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
|
---|
3247 | 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
|
---|
3248 | 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
|
---|
3249 | 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
|
---|
3250 | 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
|
---|
3251 | 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
|
---|
3252 | 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
|
---|
3253 | 'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
|
---|
3254 | 'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
|
---|
3255 | 'listMedia': ['List media known to this VBox instance', listMediaCmd, 0],
|
---|
3256 | 'listUsb': ['List known USB devices', listUsbCmd, 0],
|
---|
3257 | 'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
|
---|
3258 | 'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
|
---|
3259 | 'gui': ['Start GUI frontend', guiCmd, 0],
|
---|
3260 | 'colors':['Toggle colors', colorsCmd, 0],
|
---|
3261 | 'snapshot':['VM snapshot manipulation, snapshot help for more info', snapshotCmd, 0],
|
---|
3262 | 'nat':['NAT (network address translation engine) manipulation, nat help for more info', natCmd, 0],
|
---|
3263 | 'nic' : ['Network adapter management', nicCmd, 0],
|
---|
3264 | 'prompt' : ['Control shell prompt', promptCmd, 0],
|
---|
3265 | 'foreachvm' : ['Perform command for each VM', foreachvmCmd, 0],
|
---|
3266 | 'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print obj.name"', foreachCmd, 0],
|
---|
3267 | 'recordDemo':['Record demo: recordDemo Win32 file.dmo 10', recordDemoCmd, 0],
|
---|
3268 | 'playbackDemo':['Playback demo: playbackDemo Win32 file.dmo 10', playbackDemoCmd, 0],
|
---|
3269 | 'lspci': ['List PCI devices attached to the VM: lspci Win32', lspciCmd, 0],
|
---|
3270 | 'attachpci': ['Attach host PCI device to the VM: attachpci Win32 01:00.0', attachpciCmd, 0],
|
---|
3271 | 'detachpci': ['Detach host PCI device from the VM: detachpci Win32 01:00.0', detachpciCmd, 0],
|
---|
3272 | 'goto': ['Go to line in script (script-only)', gotoCmd, 0]
|
---|
3273 | }
|
---|
3274 |
|
---|
3275 | def runCommandArgs(ctx, args):
|
---|
3276 | c = args[0]
|
---|
3277 | if aliases.get(c, None) != None:
|
---|
3278 | c = aliases[c]
|
---|
3279 | ci = commands.get(c,None)
|
---|
3280 | if ci == None:
|
---|
3281 | print "Unknown command: '%s', type 'help' for list of known commands" %(c)
|
---|
3282 | return 0
|
---|
3283 | if ctx['remote'] and ctx['vb'] is None:
|
---|
3284 | if c not in ['connect', 'reconnect', 'help', 'quit']:
|
---|
3285 | print "First connect to remote server with %s command." %(colored('connect', 'blue'))
|
---|
3286 | return 0
|
---|
3287 | return ci[1](ctx, args)
|
---|
3288 |
|
---|
3289 |
|
---|
3290 | def runCommand(ctx, cmd):
|
---|
3291 | if len(cmd) == 0: return 0
|
---|
3292 | args = split_no_quotes(cmd)
|
---|
3293 | if len(args) == 0: return 0
|
---|
3294 | return runCommandArgs(ctx, args)
|
---|
3295 |
|
---|
3296 | #
|
---|
3297 | # To write your own custom commands to vboxshell, create
|
---|
3298 | # file ~/.VirtualBox/shellext.py with content like
|
---|
3299 | #
|
---|
3300 | # def runTestCmd(ctx, args):
|
---|
3301 | # print "Testy test", ctx['vb']
|
---|
3302 | # return 0
|
---|
3303 | #
|
---|
3304 | # commands = {
|
---|
3305 | # 'test': ['Test help', runTestCmd]
|
---|
3306 | # }
|
---|
3307 | # and issue reloadExt shell command.
|
---|
3308 | # This file also will be read automatically on startup or 'reloadExt'.
|
---|
3309 | #
|
---|
3310 | # Also one can put shell extensions into ~/.VirtualBox/shexts and
|
---|
3311 | # they will also be picked up, so this way one can exchange
|
---|
3312 | # shell extensions easily.
|
---|
3313 | def addExtsFromFile(ctx, cmds, file):
|
---|
3314 | if not os.path.isfile(file):
|
---|
3315 | return
|
---|
3316 | d = {}
|
---|
3317 | try:
|
---|
3318 | execfile(file, d, d)
|
---|
3319 | for (k,v) in d['commands'].items():
|
---|
3320 | if g_verbose:
|
---|
3321 | print "customize: adding \"%s\" - %s" %(k, v[0])
|
---|
3322 | cmds[k] = [v[0], v[1], file]
|
---|
3323 | except:
|
---|
3324 | print "Error loading user extensions from %s" %(file)
|
---|
3325 | traceback.print_exc()
|
---|
3326 |
|
---|
3327 |
|
---|
3328 | def checkUserExtensions(ctx, cmds, folder):
|
---|
3329 | folder = str(folder)
|
---|
3330 | name = os.path.join(folder, "shellext.py")
|
---|
3331 | addExtsFromFile(ctx, cmds, name)
|
---|
3332 | # also check 'exts' directory for all files
|
---|
3333 | shextdir = os.path.join(folder, "shexts")
|
---|
3334 | if not os.path.isdir(shextdir):
|
---|
3335 | return
|
---|
3336 | exts = os.listdir(shextdir)
|
---|
3337 | for e in exts:
|
---|
3338 | # not editor temporary files, please.
|
---|
3339 | if e.endswith('.py'):
|
---|
3340 | addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
|
---|
3341 |
|
---|
3342 | def getHomeFolder(ctx):
|
---|
3343 | if ctx['remote'] or ctx['vb'] is None:
|
---|
3344 | if 'VBOX_USER_HOME' in os.environ:
|
---|
3345 | return os.path.join(os.environ['VBOX_USER_HOME'])
|
---|
3346 | return os.path.join(os.path.expanduser("~"), ".VirtualBox")
|
---|
3347 | else:
|
---|
3348 | return ctx['vb'].homeFolder
|
---|
3349 |
|
---|
3350 | def interpret(ctx):
|
---|
3351 | if ctx['remote']:
|
---|
3352 | commands['connect'] = ["Connect to remote VBox instance: connect http://server:18083 user password", connectCmd, 0]
|
---|
3353 | commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
|
---|
3354 | commands['reconnect'] = ["Reconnect to remote VBox instance", reconnectCmd, 0]
|
---|
3355 | ctx['wsinfo'] = ["http://localhost:18083", "", ""]
|
---|
3356 |
|
---|
3357 | vbox = ctx['vb']
|
---|
3358 | if vbox is not None:
|
---|
3359 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
3360 | ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
|
---|
3361 | else:
|
---|
3362 | ctx['perf'] = None
|
---|
3363 |
|
---|
3364 | home = getHomeFolder(ctx)
|
---|
3365 | checkUserExtensions(ctx, commands, home)
|
---|
3366 | if platform.system() in ['Windows', 'Microsoft']:
|
---|
3367 | global g_hascolors
|
---|
3368 | g_hascolors = False
|
---|
3369 | hist_file=os.path.join(home, ".vboxshellhistory")
|
---|
3370 | autoCompletion(commands, ctx)
|
---|
3371 |
|
---|
3372 | if g_hasreadline and os.path.exists(hist_file):
|
---|
3373 | readline.read_history_file(hist_file)
|
---|
3374 |
|
---|
3375 | # to allow to print actual host information, we collect info for
|
---|
3376 | # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
|
---|
3377 | if ctx['perf']:
|
---|
3378 | try:
|
---|
3379 | ctx['perf'].setup(['*'], [vbox.host], 10, 15)
|
---|
3380 | except:
|
---|
3381 | pass
|
---|
3382 | cmds = []
|
---|
3383 |
|
---|
3384 | if g_cmd is not None:
|
---|
3385 | cmds = g_cmd.split(';')
|
---|
3386 | it = cmds.__iter__()
|
---|
3387 |
|
---|
3388 | while True:
|
---|
3389 | try:
|
---|
3390 | if g_batchmode:
|
---|
3391 | cmd = 'runScript %s'%(g_scripfile)
|
---|
3392 | elif g_cmd is not None:
|
---|
3393 | cmd = it.next()
|
---|
3394 | else:
|
---|
3395 | cmd = raw_input(ctx['prompt'])
|
---|
3396 | done = runCommand(ctx, cmd)
|
---|
3397 | if done != 0: break
|
---|
3398 | if g_batchmode:
|
---|
3399 | break
|
---|
3400 | except KeyboardInterrupt:
|
---|
3401 | print '====== You can type quit or q to leave'
|
---|
3402 | except StopIteration:
|
---|
3403 | break
|
---|
3404 | except EOFError:
|
---|
3405 | break
|
---|
3406 | except Exception,e:
|
---|
3407 | printErr(ctx,e)
|
---|
3408 | if g_verbose:
|
---|
3409 | traceback.print_exc()
|
---|
3410 | ctx['global'].waitForEvents(0)
|
---|
3411 | try:
|
---|
3412 | # There is no need to disable metric collection. This is just an example.
|
---|
3413 | if ct['perf']:
|
---|
3414 | ctx['perf'].disable(['*'], [vbox.host])
|
---|
3415 | except:
|
---|
3416 | pass
|
---|
3417 | if g_hasreadline:
|
---|
3418 | readline.write_history_file(hist_file)
|
---|
3419 |
|
---|
3420 | def runCommandCb(ctx, cmd, args):
|
---|
3421 | args.insert(0, cmd)
|
---|
3422 | return runCommandArgs(ctx, args)
|
---|
3423 |
|
---|
3424 | def runGuestCommandCb(ctx, id, guestLambda, args):
|
---|
3425 | mach = machById(ctx,id)
|
---|
3426 | if mach == None:
|
---|
3427 | return 0
|
---|
3428 | args.insert(0, guestLambda)
|
---|
3429 | cmdExistingVm(ctx, mach, 'guestlambda', args)
|
---|
3430 | return 0
|
---|
3431 |
|
---|
3432 | def main(argv):
|
---|
3433 | style = None
|
---|
3434 | params = None
|
---|
3435 | autopath = False
|
---|
3436 | script_file = None
|
---|
3437 | parse = OptionParser()
|
---|
3438 | parse.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help = "switch on verbose")
|
---|
3439 | parse.add_option("-a", "--autopath", dest="autopath", action="store_true", default=False, help = "switch on autopath")
|
---|
3440 | parse.add_option("-w", "--webservice", dest="style", action="store_const", const="WEBSERVICE", help = "connect to webservice")
|
---|
3441 | parse.add_option("-b", "--batch", dest="batch_file", help = "script file to execute")
|
---|
3442 | parse.add_option("-c", dest="command_line", help = "command sequence to execute")
|
---|
3443 | parse.add_option("-o", dest="opt_line", help = "option line")
|
---|
3444 | global g_verbose, g_scripfile, g_batchmode, g_hascolors, g_hasreadline, g_cmd
|
---|
3445 | (options, args) = parse.parse_args()
|
---|
3446 | g_verbose = options.verbose
|
---|
3447 | style = options.style
|
---|
3448 | if options.batch_file is not None:
|
---|
3449 | g_batchmode = True
|
---|
3450 | g_hascolors = False
|
---|
3451 | g_hasreadline = False
|
---|
3452 | g_scripfile = options.batch_file
|
---|
3453 | if options.command_line is not None:
|
---|
3454 | g_hascolors = False
|
---|
3455 | g_hasreadline = False
|
---|
3456 | g_cmd = options.command_line
|
---|
3457 | if options.opt_line is not None:
|
---|
3458 | params = {}
|
---|
3459 | strparams = options.opt_line
|
---|
3460 | l = strparams.split(',')
|
---|
3461 | for e in l:
|
---|
3462 | (k,v) = e.split('=')
|
---|
3463 | params[k] = v
|
---|
3464 | else:
|
---|
3465 | params = None
|
---|
3466 |
|
---|
3467 | if options.autopath:
|
---|
3468 | cwd = os.getcwd()
|
---|
3469 | vpp = os.environ.get("VBOX_PROGRAM_PATH")
|
---|
3470 | if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
|
---|
3471 | vpp = cwd
|
---|
3472 | print "Autodetected VBOX_PROGRAM_PATH as",vpp
|
---|
3473 | os.environ["VBOX_PROGRAM_PATH"] = vpp
|
---|
3474 | sys.path.append(os.path.join(vpp, "sdk", "installer"))
|
---|
3475 | vsp = os.environ.get("VBOX_SDK_PATH")
|
---|
3476 | if vsp is None and os.path.isfile(os.path.join(cwd, "sdk", "bindings", "VirtualBox.xidl")) :
|
---|
3477 | vsp = os.path.join(cwd, "sdk")
|
---|
3478 | if vsp is None and os.path.isfile(os.path.join(vpp, "sdk", "bindings", "VirtualBox.xidl")) :
|
---|
3479 | vsp = os.path.join(vpp, "sdk")
|
---|
3480 | if vsp is not None :
|
---|
3481 | print "Autodetected VBOX_SDK_PATH as",vsp
|
---|
3482 | os.environ["VBOX_SDK_PATH"] = vsp
|
---|
3483 |
|
---|
3484 | from vboxapi import VirtualBoxManager
|
---|
3485 | g_virtualBoxManager = VirtualBoxManager(style, params)
|
---|
3486 | ctx = {'global':g_virtualBoxManager,
|
---|
3487 | 'mgr':g_virtualBoxManager.mgr,
|
---|
3488 | 'vb':g_virtualBoxManager.vbox,
|
---|
3489 | 'const':g_virtualBoxManager.constants,
|
---|
3490 | 'remote':g_virtualBoxManager.remote,
|
---|
3491 | 'type':g_virtualBoxManager.type,
|
---|
3492 | 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
|
---|
3493 | 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
|
---|
3494 | 'machById': lambda id: machById(ctx,id),
|
---|
3495 | 'argsToMach': lambda args: argsToMach(ctx,args),
|
---|
3496 | 'progressBar': lambda p: progressBar(ctx,p),
|
---|
3497 | 'typeInGuest': typeInGuest,
|
---|
3498 | '_machlist': None,
|
---|
3499 | 'prompt': g_prompt,
|
---|
3500 | 'scriptLine': 0,
|
---|
3501 | 'interrupt': False
|
---|
3502 | }
|
---|
3503 | interpret(ctx)
|
---|
3504 | g_virtualBoxManager.deinit()
|
---|
3505 | del g_virtualBoxManager
|
---|
3506 |
|
---|
3507 | if __name__ == '__main__':
|
---|
3508 | main(sys.argv)
|
---|