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