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