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