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