1 | #!/usr/bin/python
|
---|
2 | #
|
---|
3 | # Copyright (C) 2009 Sun Microsystems, Inc.
|
---|
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 | # Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
|
---|
14 | # Clara, CA 95054 USA or visit http://www.sun.com if you need
|
---|
15 | # additional information or have any questions.
|
---|
16 | #
|
---|
17 | #################################################################################
|
---|
18 | # This program is a simple interactive shell for VirtualBox. You can query #
|
---|
19 | # information and issue commands from a simple command line. #
|
---|
20 | # #
|
---|
21 | # It also provides you with examples on how to use VirtualBox's Python API. #
|
---|
22 | # This shell is even somewhat documented and supports TAB-completion and #
|
---|
23 | # history if you have Python readline installed. #
|
---|
24 | # #
|
---|
25 | # Enjoy. #
|
---|
26 | ################################################################################
|
---|
27 |
|
---|
28 | import os,sys
|
---|
29 | import traceback
|
---|
30 | import shlex
|
---|
31 | import time
|
---|
32 |
|
---|
33 | # Simple implementation of IConsoleCallback, one can use it as skeleton
|
---|
34 | # for custom implementations
|
---|
35 | class GuestMonitor:
|
---|
36 | def __init__(self, mach):
|
---|
37 | self.mach = mach
|
---|
38 |
|
---|
39 | def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
|
---|
40 | print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
|
---|
41 | def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
|
---|
42 | print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, needsHostCursor)
|
---|
43 |
|
---|
44 | def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
|
---|
45 | print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
|
---|
46 |
|
---|
47 | def onStateChange(self, state):
|
---|
48 | print "%s: onStateChange state=%d" %(self.mach.name, state)
|
---|
49 |
|
---|
50 | def onAdditionsStateChange(self):
|
---|
51 | print "%s: onAdditionsStateChange" %(self.mach.name)
|
---|
52 |
|
---|
53 | def onNetworkAdapterChange(self, adapter):
|
---|
54 | print "%s: onNetworkAdapterChange" %(self.mach.name)
|
---|
55 |
|
---|
56 | def onSerialPortChange(self, port):
|
---|
57 | print "%s: onSerialPortChange" %(self.mach.name)
|
---|
58 |
|
---|
59 | def onParallelPortChange(self, port):
|
---|
60 | print "%s: onParallelPortChange" %(self.mach.name)
|
---|
61 |
|
---|
62 | def onStorageControllerChange(self):
|
---|
63 | print "%s: onStorageControllerChange" %(self.mach.name)
|
---|
64 |
|
---|
65 | def onMediumChange(self, attachment):
|
---|
66 | print "%s: onMediumChange" %(self.mach.name)
|
---|
67 |
|
---|
68 | def onVRDPServerChange(self):
|
---|
69 | print "%s: onVRDPServerChange" %(self.mach.name)
|
---|
70 |
|
---|
71 | def onUSBControllerChange(self):
|
---|
72 | print "%s: onUSBControllerChange" %(self.mach.name)
|
---|
73 |
|
---|
74 | def onUSBDeviceStateChange(self, device, attached, error):
|
---|
75 | print "%s: onUSBDeviceStateChange" %(self.mach.name)
|
---|
76 |
|
---|
77 | def onSharedFolderChange(self, scope):
|
---|
78 | print "%s: onSharedFolderChange" %(self.mach.name)
|
---|
79 |
|
---|
80 | def onRuntimeError(self, fatal, id, message):
|
---|
81 | print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
|
---|
82 |
|
---|
83 | def onCanShowWindow(self):
|
---|
84 | print "%s: onCanShowWindow" %(self.mach.name)
|
---|
85 | return True
|
---|
86 |
|
---|
87 | def onShowWindow(self, winId):
|
---|
88 | print "%s: onShowWindow: %d" %(self.mach.name, winId)
|
---|
89 |
|
---|
90 | class VBoxMonitor:
|
---|
91 | def __init__(self, params):
|
---|
92 | self.vbox = params[0]
|
---|
93 | self.isMscom = params[1]
|
---|
94 | pass
|
---|
95 |
|
---|
96 | def onMachineStateChange(self, id, state):
|
---|
97 | print "onMachineStateChange: %s %d" %(id, state)
|
---|
98 |
|
---|
99 | def onMachineDataChange(self,id):
|
---|
100 | print "onMachineDataChange: %s" %(id)
|
---|
101 |
|
---|
102 | def onExtraDataCanChange(self, id, key, value):
|
---|
103 | print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
|
---|
104 | # Witty COM bridge thinks if someone wishes to return tuple, hresult
|
---|
105 | # is one of values we want to return
|
---|
106 | if self.isMscom:
|
---|
107 | return "", 0, True
|
---|
108 | else:
|
---|
109 | return True, ""
|
---|
110 |
|
---|
111 | def onExtraDataChange(self, id, key, value):
|
---|
112 | print "onExtraDataChange: %s %s=>%s" %(id, key, value)
|
---|
113 |
|
---|
114 | def onMediaRegistered(self, id, type, registered):
|
---|
115 | print "onMediaRegistered: %s" %(id)
|
---|
116 |
|
---|
117 | def onMachineRegistered(self, id, registred):
|
---|
118 | print "onMachineRegistered: %s" %(id)
|
---|
119 |
|
---|
120 | def onSessionStateChange(self, id, state):
|
---|
121 | print "onSessionStateChange: %s %d" %(id, state)
|
---|
122 |
|
---|
123 | def onSnapshotTaken(self, mach, id):
|
---|
124 | print "onSnapshotTaken: %s %s" %(mach, id)
|
---|
125 |
|
---|
126 | def onSnapshotDiscarded(self, mach, id):
|
---|
127 | print "onSnapshotDiscarded: %s %s" %(mach, id)
|
---|
128 |
|
---|
129 | def onSnapshotChange(self, mach, id):
|
---|
130 | print "onSnapshotChange: %s %s" %(mach, id)
|
---|
131 |
|
---|
132 | def onGuestPropertyChange(self, id, name, newValue, flags):
|
---|
133 | print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
|
---|
134 |
|
---|
135 | g_hasreadline = 1
|
---|
136 | try:
|
---|
137 | import readline
|
---|
138 | import rlcompleter
|
---|
139 | except:
|
---|
140 | g_hasreadline = 0
|
---|
141 |
|
---|
142 |
|
---|
143 | if g_hasreadline:
|
---|
144 | class CompleterNG(rlcompleter.Completer):
|
---|
145 | def __init__(self, dic, ctx):
|
---|
146 | self.ctx = ctx
|
---|
147 | return rlcompleter.Completer.__init__(self,dic)
|
---|
148 |
|
---|
149 | def complete(self, text, state):
|
---|
150 | """
|
---|
151 | taken from:
|
---|
152 | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
|
---|
153 | """
|
---|
154 | if text == "":
|
---|
155 | return ['\t',None][state]
|
---|
156 | else:
|
---|
157 | return rlcompleter.Completer.complete(self,text,state)
|
---|
158 |
|
---|
159 | def global_matches(self, text):
|
---|
160 | """
|
---|
161 | Compute matches when text is a simple name.
|
---|
162 | Return a list of all names currently defined
|
---|
163 | in self.namespace that match.
|
---|
164 | """
|
---|
165 |
|
---|
166 | matches = []
|
---|
167 | n = len(text)
|
---|
168 |
|
---|
169 | for list in [ self.namespace ]:
|
---|
170 | for word in list:
|
---|
171 | if word[:n] == text:
|
---|
172 | matches.append(word)
|
---|
173 |
|
---|
174 |
|
---|
175 | try:
|
---|
176 | for m in getMachines(self.ctx):
|
---|
177 | # although it has autoconversion, we need to cast
|
---|
178 | # explicitly for subscripts to work
|
---|
179 | word = str(m.name)
|
---|
180 | if word[:n] == text:
|
---|
181 | matches.append(word)
|
---|
182 | word = str(m.id)
|
---|
183 | if word[0] == '{':
|
---|
184 | word = word[1:-1]
|
---|
185 | if word[:n] == text:
|
---|
186 | matches.append(word)
|
---|
187 | except Exception,e:
|
---|
188 | traceback.print_exc()
|
---|
189 | print e
|
---|
190 |
|
---|
191 | return matches
|
---|
192 |
|
---|
193 |
|
---|
194 | def autoCompletion(commands, ctx):
|
---|
195 | if not g_hasreadline:
|
---|
196 | return
|
---|
197 |
|
---|
198 | comps = {}
|
---|
199 | for (k,v) in commands.items():
|
---|
200 | comps[k] = None
|
---|
201 | completer = CompleterNG(comps, ctx)
|
---|
202 | readline.set_completer(completer.complete)
|
---|
203 | readline.parse_and_bind("tab: complete")
|
---|
204 |
|
---|
205 | g_verbose = True
|
---|
206 |
|
---|
207 | def split_no_quotes(s):
|
---|
208 | return shlex.split(s)
|
---|
209 |
|
---|
210 | def progressBar(ctx,p,wait=1000):
|
---|
211 | try:
|
---|
212 | while not p.completed:
|
---|
213 | print "%d %%\r" %(p.percent),
|
---|
214 | sys.stdout.flush()
|
---|
215 | p.waitForCompletion(wait)
|
---|
216 | ctx['global'].waitForEvents(0)
|
---|
217 | except KeyboardInterrupt:
|
---|
218 | print "Interrupted."
|
---|
219 |
|
---|
220 |
|
---|
221 | def reportError(ctx,session,rc):
|
---|
222 | if not ctx['remote']:
|
---|
223 | print session.QueryErrorObject(rc)
|
---|
224 |
|
---|
225 |
|
---|
226 | def createVm(ctx,name,kind,base):
|
---|
227 | mgr = ctx['mgr']
|
---|
228 | vb = ctx['vb']
|
---|
229 | mach = vb.createMachine(name, kind, base, "")
|
---|
230 | mach.saveSettings()
|
---|
231 | print "created machine with UUID",mach.id
|
---|
232 | vb.registerMachine(mach)
|
---|
233 | # update cache
|
---|
234 | getMachines(ctx, True)
|
---|
235 |
|
---|
236 | def removeVm(ctx,mach):
|
---|
237 | mgr = ctx['mgr']
|
---|
238 | vb = ctx['vb']
|
---|
239 | id = mach.id
|
---|
240 | print "removing machine ",mach.name,"with UUID",id
|
---|
241 | session = ctx['global'].openMachineSession(id)
|
---|
242 | try:
|
---|
243 | mach = session.machine
|
---|
244 | for d in ctx['global'].getArray(mach, 'mediumAttachments'):
|
---|
245 | mach.detachDevice(d.controller, d.port, d.device)
|
---|
246 | except:
|
---|
247 | traceback.print_exc()
|
---|
248 | mach.saveSettings()
|
---|
249 | ctx['global'].closeMachineSession(session)
|
---|
250 | mach = vb.unregisterMachine(id)
|
---|
251 | if mach:
|
---|
252 | mach.deleteSettings()
|
---|
253 | # update cache
|
---|
254 | getMachines(ctx, True)
|
---|
255 |
|
---|
256 | def startVm(ctx,mach,type):
|
---|
257 | mgr = ctx['mgr']
|
---|
258 | vb = ctx['vb']
|
---|
259 | perf = ctx['perf']
|
---|
260 | session = mgr.getSessionObject(vb)
|
---|
261 | uuid = mach.id
|
---|
262 | progress = vb.openRemoteSession(session, uuid, type, "")
|
---|
263 | progressBar(ctx, progress, 100)
|
---|
264 | completed = progress.completed
|
---|
265 | rc = int(progress.resultCode)
|
---|
266 | print "Completed:", completed, "rc:",hex(rc&0xffffffff)
|
---|
267 | if rc == 0:
|
---|
268 | # we ignore exceptions to allow starting VM even if
|
---|
269 | # perf collector cannot be started
|
---|
270 | if perf:
|
---|
271 | try:
|
---|
272 | perf.setup(['*'], [mach], 10, 15)
|
---|
273 | except Exception,e:
|
---|
274 | print e
|
---|
275 | if g_verbose:
|
---|
276 | traceback.print_exc()
|
---|
277 | pass
|
---|
278 | # if session not opened, close doesn't make sense
|
---|
279 | session.close()
|
---|
280 | else:
|
---|
281 | reportError(ctx,session,rc)
|
---|
282 |
|
---|
283 | def getMachines(ctx, invalidate = False):
|
---|
284 | if ctx['vb'] is not None:
|
---|
285 | if ctx['_machlist'] is None or invalidate:
|
---|
286 | ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
|
---|
287 | return ctx['_machlist']
|
---|
288 | else:
|
---|
289 | return []
|
---|
290 |
|
---|
291 | def asState(var):
|
---|
292 | if var:
|
---|
293 | return 'on'
|
---|
294 | else:
|
---|
295 | return 'off'
|
---|
296 |
|
---|
297 | def perfStats(ctx,mach):
|
---|
298 | if not ctx['perf']:
|
---|
299 | return
|
---|
300 | for metric in ctx['perf'].query(["*"], [mach]):
|
---|
301 | print metric['name'], metric['values_as_string']
|
---|
302 |
|
---|
303 | def guestExec(ctx, machine, console, cmds):
|
---|
304 | exec cmds
|
---|
305 |
|
---|
306 | def monitorGuest(ctx, machine, console, dur):
|
---|
307 | cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
|
---|
308 | console.registerCallback(cb)
|
---|
309 | if dur == -1:
|
---|
310 | # not infinity, but close enough
|
---|
311 | dur = 100000
|
---|
312 | try:
|
---|
313 | end = time.time() + dur
|
---|
314 | while time.time() < end:
|
---|
315 | ctx['global'].waitForEvents(500)
|
---|
316 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
317 | except:
|
---|
318 | pass
|
---|
319 | console.unregisterCallback(cb)
|
---|
320 |
|
---|
321 |
|
---|
322 | def monitorVBox(ctx, dur):
|
---|
323 | vbox = ctx['vb']
|
---|
324 | isMscom = (ctx['global'].type == 'MSCOM')
|
---|
325 | cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
|
---|
326 | vbox.registerCallback(cb)
|
---|
327 | if dur == -1:
|
---|
328 | # not infinity, but close enough
|
---|
329 | dur = 100000
|
---|
330 | try:
|
---|
331 | end = time.time() + dur
|
---|
332 | while time.time() < end:
|
---|
333 | ctx['global'].waitForEvents(500)
|
---|
334 | # We need to catch all exceptions here, otherwise callback will never be unregistered
|
---|
335 | except:
|
---|
336 | pass
|
---|
337 | vbox.unregisterCallback(cb)
|
---|
338 |
|
---|
339 |
|
---|
340 | def takeScreenshot(ctx,console,args):
|
---|
341 | from PIL import Image
|
---|
342 | display = console.display
|
---|
343 | if len(args) > 0:
|
---|
344 | f = args[0]
|
---|
345 | else:
|
---|
346 | f = "/tmp/screenshot.png"
|
---|
347 | if len(args) > 1:
|
---|
348 | w = args[1]
|
---|
349 | else:
|
---|
350 | w = console.display.width
|
---|
351 | if len(args) > 2:
|
---|
352 | h = args[2]
|
---|
353 | else:
|
---|
354 | h = console.display.height
|
---|
355 | print "Saving screenshot (%d x %d) in %s..." %(w,h,f)
|
---|
356 | data = display.takeScreenShotSlow(w,h)
|
---|
357 | size = (w,h)
|
---|
358 | mode = "RGBA"
|
---|
359 | im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
|
---|
360 | im.save(f, "PNG")
|
---|
361 |
|
---|
362 |
|
---|
363 | def teleport(ctx,session,console,args):
|
---|
364 | if args[0].find(":") == -1:
|
---|
365 | print "Use host:port format for teleport target"
|
---|
366 | return
|
---|
367 | (host,port) = args[0].split(":")
|
---|
368 | if len(args) > 1:
|
---|
369 | passwd = args[1]
|
---|
370 | else:
|
---|
371 | passwd = ""
|
---|
372 |
|
---|
373 | port = int(port)
|
---|
374 | print "Teleporting to %s:%d..." %(host,port)
|
---|
375 | progress = console.teleport(host, port, passwd)
|
---|
376 | progressBar(ctx, progress, 100)
|
---|
377 | completed = progress.completed
|
---|
378 | rc = int(progress.resultCode)
|
---|
379 | if rc == 0:
|
---|
380 | print "Success!"
|
---|
381 | else:
|
---|
382 | reportError(ctx,session,rc)
|
---|
383 |
|
---|
384 |
|
---|
385 | def guestStats(ctx,console,args):
|
---|
386 | guest = console.guest
|
---|
387 | # we need to set up guest statistics
|
---|
388 | if len(args) > 0 :
|
---|
389 | update = args[0]
|
---|
390 | else:
|
---|
391 | update = 1
|
---|
392 | if guest.statisticsUpdateInterval != update:
|
---|
393 | guest.statisticsUpdateInterval = update
|
---|
394 | try:
|
---|
395 | time.sleep(float(update)+0.1)
|
---|
396 | except:
|
---|
397 | # to allow sleep interruption
|
---|
398 | pass
|
---|
399 | all_stats = ctx['ifaces'].all_values('GuestStatisticType')
|
---|
400 | cpu = 0
|
---|
401 | for s in all_stats.keys():
|
---|
402 | try:
|
---|
403 | val = guest.getStatistic( cpu, all_stats[s])
|
---|
404 | print "%s: %d" %(s, val)
|
---|
405 | except:
|
---|
406 | # likely not implemented
|
---|
407 | pass
|
---|
408 |
|
---|
409 | def plugCpu(ctx,machine,session,args):
|
---|
410 | cpu = int(args)
|
---|
411 | print "Adding CPU %d..." %(cpu)
|
---|
412 | machine.HotPlugCPU(cpu)
|
---|
413 |
|
---|
414 | def unplugCpu(ctx,machine,session,args):
|
---|
415 | cpu = int(args)
|
---|
416 | print "Removing CPU %d..." %(cpu)
|
---|
417 | machine.HotUnplugCPU(cpu)
|
---|
418 |
|
---|
419 | def cmdExistingVm(ctx,mach,cmd,args):
|
---|
420 | mgr=ctx['mgr']
|
---|
421 | vb=ctx['vb']
|
---|
422 | session = mgr.getSessionObject(vb)
|
---|
423 | uuid = mach.id
|
---|
424 | try:
|
---|
425 | progress = vb.openExistingSession(session, uuid)
|
---|
426 | except Exception,e:
|
---|
427 | print "Session to '%s' not open: %s" %(mach.name,e)
|
---|
428 | if g_verbose:
|
---|
429 | traceback.print_exc()
|
---|
430 | return
|
---|
431 | if str(session.state) != str(ctx['ifaces'].SessionState_Open):
|
---|
432 | print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
|
---|
433 | return
|
---|
434 | # this could be an example how to handle local only (i.e. unavailable
|
---|
435 | # in Webservices) functionality
|
---|
436 | if ctx['remote'] and cmd == 'some_local_only_command':
|
---|
437 | print 'Trying to use local only functionality, ignored'
|
---|
438 | return
|
---|
439 | console=session.console
|
---|
440 | ops={'pause': lambda: console.pause(),
|
---|
441 | 'resume': lambda: console.resume(),
|
---|
442 | 'powerdown': lambda: console.powerDown(),
|
---|
443 | 'powerbutton': lambda: console.powerButton(),
|
---|
444 | 'stats': lambda: perfStats(ctx, mach),
|
---|
445 | 'guest': lambda: guestExec(ctx, mach, console, args),
|
---|
446 | 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
|
---|
447 | 'save': lambda: progressBar(ctx,console.saveState()),
|
---|
448 | 'screenshot': lambda: takeScreenshot(ctx,console,args),
|
---|
449 | 'teleport': lambda: teleport(ctx,session,console,args),
|
---|
450 | 'gueststats': lambda: guestStats(ctx, console, args),
|
---|
451 | 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
|
---|
452 | 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
|
---|
453 | }
|
---|
454 | try:
|
---|
455 | ops[cmd]()
|
---|
456 | except Exception, e:
|
---|
457 | print 'failed: ',e
|
---|
458 | if g_verbose:
|
---|
459 | traceback.print_exc()
|
---|
460 |
|
---|
461 | session.close()
|
---|
462 |
|
---|
463 | def machById(ctx,id):
|
---|
464 | mach = None
|
---|
465 | for m in getMachines(ctx):
|
---|
466 | if m.name == id:
|
---|
467 | mach = m
|
---|
468 | break
|
---|
469 | mid = str(m.id)
|
---|
470 | if mid[0] == '{':
|
---|
471 | mid = mid[1:-1]
|
---|
472 | if mid == id:
|
---|
473 | mach = m
|
---|
474 | break
|
---|
475 | return mach
|
---|
476 |
|
---|
477 | def argsToMach(ctx,args):
|
---|
478 | if len(args) < 2:
|
---|
479 | print "usage: %s [vmname|uuid]" %(args[0])
|
---|
480 | return None
|
---|
481 | id = args[1]
|
---|
482 | m = machById(ctx, id)
|
---|
483 | if m == None:
|
---|
484 | print "Machine '%s' is unknown, use list command to find available machines" %(id)
|
---|
485 | return m
|
---|
486 |
|
---|
487 | def helpSingleCmd(cmd,h,sp):
|
---|
488 | if sp != 0:
|
---|
489 | spec = " [ext from "+sp+"]"
|
---|
490 | else:
|
---|
491 | spec = ""
|
---|
492 | print " %s: %s%s" %(cmd,h,spec)
|
---|
493 |
|
---|
494 | def helpCmd(ctx, args):
|
---|
495 | if len(args) == 1:
|
---|
496 | print "Help page:"
|
---|
497 | names = commands.keys()
|
---|
498 | names.sort()
|
---|
499 | for i in names:
|
---|
500 | helpSingleCmd(i, commands[i][0], commands[i][2])
|
---|
501 | else:
|
---|
502 | cmd = args[1]
|
---|
503 | c = commands.get(cmd)
|
---|
504 | if c == None:
|
---|
505 | print "Command '%s' not known" %(cmd)
|
---|
506 | else:
|
---|
507 | helpSingleCmd(cmd, c[0], c[2])
|
---|
508 | return 0
|
---|
509 |
|
---|
510 | def listCmd(ctx, args):
|
---|
511 | for m in getMachines(ctx, True):
|
---|
512 | if m.teleporterEnabled:
|
---|
513 | tele = "[T] "
|
---|
514 | else:
|
---|
515 | tele = " "
|
---|
516 | print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,m.sessionState)
|
---|
517 | return 0
|
---|
518 |
|
---|
519 | def getControllerType(type):
|
---|
520 | if type == 0:
|
---|
521 | return "Null"
|
---|
522 | elif type == 1:
|
---|
523 | return "LsiLogic"
|
---|
524 | elif type == 2:
|
---|
525 | return "BusLogic"
|
---|
526 | elif type == 3:
|
---|
527 | return "IntelAhci"
|
---|
528 | elif type == 4:
|
---|
529 | return "PIIX3"
|
---|
530 | elif type == 5:
|
---|
531 | return "PIIX4"
|
---|
532 | elif type == 6:
|
---|
533 | return "ICH6"
|
---|
534 | else:
|
---|
535 | return "Unknown"
|
---|
536 |
|
---|
537 | def getFirmwareType(type):
|
---|
538 | if type == 0:
|
---|
539 | return "invalid"
|
---|
540 | elif type == 1:
|
---|
541 | return "bios"
|
---|
542 | elif type == 2:
|
---|
543 | return "efi"
|
---|
544 | elif type == 3:
|
---|
545 | return "efi64"
|
---|
546 | elif type == 4:
|
---|
547 | return "efidual"
|
---|
548 | else:
|
---|
549 | return "Unknown"
|
---|
550 |
|
---|
551 |
|
---|
552 | def infoCmd(ctx,args):
|
---|
553 | if (len(args) < 2):
|
---|
554 | print "usage: info [vmname|uuid]"
|
---|
555 | return 0
|
---|
556 | mach = argsToMach(ctx,args)
|
---|
557 | if mach == None:
|
---|
558 | return 0
|
---|
559 | os = ctx['vb'].getGuestOSType(mach.OSTypeId)
|
---|
560 | print " One can use setvar <mach> <var> <value> to change variable, using name in []."
|
---|
561 | print " Name [name]: %s" %(mach.name)
|
---|
562 | print " ID [n/a]: %s" %(mach.id)
|
---|
563 | print " OS Type [n/a]: %s" %(os.description)
|
---|
564 | print " Firmware [firmwareType]: %s (%s)" %(getFirmwareType(mach.firmwareType),mach.firmwareType)
|
---|
565 | print
|
---|
566 | print " CPUs [CPUCount]: %d" %(mach.CPUCount)
|
---|
567 | print " RAM [memorySize]: %dM" %(mach.memorySize)
|
---|
568 | print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
|
---|
569 | print " Monitors [monitorCount]: %d" %(mach.monitorCount)
|
---|
570 | print
|
---|
571 | print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
|
---|
572 | print " Machine status [n/a]: %d" % (mach.sessionState)
|
---|
573 | print
|
---|
574 | if mach.teleporterEnabled:
|
---|
575 | print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
|
---|
576 | print
|
---|
577 | bios = mach.BIOSSettings
|
---|
578 | print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
|
---|
579 | print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
|
---|
580 | hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
|
---|
581 | print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
|
---|
582 | hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
|
---|
583 | print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
|
---|
584 | hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
|
---|
585 | print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
|
---|
586 |
|
---|
587 | print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
|
---|
588 | print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
|
---|
589 |
|
---|
590 | print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
|
---|
591 | print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
|
---|
592 | print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
|
---|
593 |
|
---|
594 | controllers = ctx['global'].getArray(mach, 'storageControllers')
|
---|
595 | if controllers:
|
---|
596 | print
|
---|
597 | print " Controllers:"
|
---|
598 | for controller in controllers:
|
---|
599 | print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
|
---|
600 |
|
---|
601 | attaches = ctx['global'].getArray(mach, 'mediumAttachments')
|
---|
602 | if attaches:
|
---|
603 | print
|
---|
604 | print " Mediums:"
|
---|
605 | for a in attaches:
|
---|
606 | print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
|
---|
607 | m = a.medium
|
---|
608 | if a.type == ctx['global'].constants.DeviceType_HardDisk:
|
---|
609 | print " HDD:"
|
---|
610 | print " Id: %s" %(m.id)
|
---|
611 | print " Location: %s" %(m.location)
|
---|
612 | print " Name: %s" %(m.name)
|
---|
613 | print " Format: %s" %(m.format)
|
---|
614 |
|
---|
615 | if a.type == ctx['global'].constants.DeviceType_DVD:
|
---|
616 | print " DVD:"
|
---|
617 | if m:
|
---|
618 | print " Id: %s" %(m.id)
|
---|
619 | print " Name: %s" %(m.name)
|
---|
620 | if m.hostDrive:
|
---|
621 | print " Host DVD %s" %(m.location)
|
---|
622 | if a.passthrough:
|
---|
623 | print " [passthrough mode]"
|
---|
624 | else:
|
---|
625 | print " Virtual image at %s" %(m.location)
|
---|
626 | print " Size: %s" %(m.size)
|
---|
627 |
|
---|
628 | if a.type == ctx['global'].constants.DeviceType_Floppy:
|
---|
629 | print " Floppy:"
|
---|
630 | if m:
|
---|
631 | print " Id: %s" %(m.id)
|
---|
632 | print " Name: %s" %(m.name)
|
---|
633 | if m.hostDrive:
|
---|
634 | print " Host floppy %s" %(m.location)
|
---|
635 | else:
|
---|
636 | print " Virtual image at %s" %(m.location)
|
---|
637 | print " Size: %s" %(m.size)
|
---|
638 |
|
---|
639 | return 0
|
---|
640 |
|
---|
641 | def startCmd(ctx, args):
|
---|
642 | mach = argsToMach(ctx,args)
|
---|
643 | if mach == None:
|
---|
644 | return 0
|
---|
645 | if len(args) > 2:
|
---|
646 | type = args[2]
|
---|
647 | else:
|
---|
648 | type = "gui"
|
---|
649 | startVm(ctx, mach, type)
|
---|
650 | return 0
|
---|
651 |
|
---|
652 | def createCmd(ctx, args):
|
---|
653 | if (len(args) < 3 or len(args) > 4):
|
---|
654 | print "usage: create name ostype <basefolder>"
|
---|
655 | return 0
|
---|
656 | name = args[1]
|
---|
657 | oskind = args[2]
|
---|
658 | if len(args) == 4:
|
---|
659 | base = args[3]
|
---|
660 | else:
|
---|
661 | base = ''
|
---|
662 | try:
|
---|
663 | ctx['vb'].getGuestOSType(oskind)
|
---|
664 | except Exception, e:
|
---|
665 | print 'Unknown OS type:',oskind
|
---|
666 | return 0
|
---|
667 | createVm(ctx, name, oskind, base)
|
---|
668 | return 0
|
---|
669 |
|
---|
670 | def removeCmd(ctx, args):
|
---|
671 | mach = argsToMach(ctx,args)
|
---|
672 | if mach == None:
|
---|
673 | return 0
|
---|
674 | removeVm(ctx, mach)
|
---|
675 | return 0
|
---|
676 |
|
---|
677 | def pauseCmd(ctx, args):
|
---|
678 | mach = argsToMach(ctx,args)
|
---|
679 | if mach == None:
|
---|
680 | return 0
|
---|
681 | cmdExistingVm(ctx, mach, 'pause', '')
|
---|
682 | return 0
|
---|
683 |
|
---|
684 | def powerdownCmd(ctx, args):
|
---|
685 | mach = argsToMach(ctx,args)
|
---|
686 | if mach == None:
|
---|
687 | return 0
|
---|
688 | cmdExistingVm(ctx, mach, 'powerdown', '')
|
---|
689 | return 0
|
---|
690 |
|
---|
691 | def powerbuttonCmd(ctx, args):
|
---|
692 | mach = argsToMach(ctx,args)
|
---|
693 | if mach == None:
|
---|
694 | return 0
|
---|
695 | cmdExistingVm(ctx, mach, 'powerbutton', '')
|
---|
696 | return 0
|
---|
697 |
|
---|
698 | def resumeCmd(ctx, args):
|
---|
699 | mach = argsToMach(ctx,args)
|
---|
700 | if mach == None:
|
---|
701 | return 0
|
---|
702 | cmdExistingVm(ctx, mach, 'resume', '')
|
---|
703 | return 0
|
---|
704 |
|
---|
705 | def saveCmd(ctx, args):
|
---|
706 | mach = argsToMach(ctx,args)
|
---|
707 | if mach == None:
|
---|
708 | return 0
|
---|
709 | cmdExistingVm(ctx, mach, 'save', '')
|
---|
710 | return 0
|
---|
711 |
|
---|
712 | def statsCmd(ctx, args):
|
---|
713 | mach = argsToMach(ctx,args)
|
---|
714 | if mach == None:
|
---|
715 | return 0
|
---|
716 | cmdExistingVm(ctx, mach, 'stats', '')
|
---|
717 | return 0
|
---|
718 |
|
---|
719 | def guestCmd(ctx, args):
|
---|
720 | if (len(args) < 3):
|
---|
721 | print "usage: guest name commands"
|
---|
722 | return 0
|
---|
723 | mach = argsToMach(ctx,args)
|
---|
724 | if mach == None:
|
---|
725 | return 0
|
---|
726 | cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
|
---|
727 | return 0
|
---|
728 |
|
---|
729 | def screenshotCmd(ctx, args):
|
---|
730 | if (len(args) < 3):
|
---|
731 | print "usage: screenshot name file <width> <height>"
|
---|
732 | return 0
|
---|
733 | mach = argsToMach(ctx,args)
|
---|
734 | if mach == None:
|
---|
735 | return 0
|
---|
736 | cmdExistingVm(ctx, mach, 'screenshot', args[2:])
|
---|
737 | return 0
|
---|
738 |
|
---|
739 | def teleportCmd(ctx, args):
|
---|
740 | if (len(args) < 3):
|
---|
741 | print "usage: teleport name host:port <password>"
|
---|
742 | return 0
|
---|
743 | mach = argsToMach(ctx,args)
|
---|
744 | if mach == None:
|
---|
745 | return 0
|
---|
746 | cmdExistingVm(ctx, mach, 'teleport', args[2:])
|
---|
747 | return 0
|
---|
748 |
|
---|
749 | def openportalCmd(ctx, args):
|
---|
750 | if (len(args) < 3):
|
---|
751 | print "usage: openportal name port <password>"
|
---|
752 | return 0
|
---|
753 | mach = argsToMach(ctx,args)
|
---|
754 | if mach == None:
|
---|
755 | return 0
|
---|
756 | port = int(args[2])
|
---|
757 | if (len(args) > 3):
|
---|
758 | passwd = args[3]
|
---|
759 | else:
|
---|
760 | passwd = ""
|
---|
761 | if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
|
---|
762 | session = ctx['global'].openMachineSession(mach.id)
|
---|
763 | mach1 = session.machine
|
---|
764 | mach1.teleporterEnabled = True
|
---|
765 | mach1.teleporterPort = port
|
---|
766 | mach1.teleporterPassword = passwd
|
---|
767 | mach1.saveSettings()
|
---|
768 | session.close()
|
---|
769 | startVm(ctx, mach, "gui")
|
---|
770 | return 0
|
---|
771 |
|
---|
772 | def closeportalCmd(ctx, args):
|
---|
773 | if (len(args) < 2):
|
---|
774 | print "usage: closeportal name"
|
---|
775 | return 0
|
---|
776 | mach = argsToMach(ctx,args)
|
---|
777 | if mach == None:
|
---|
778 | return 0
|
---|
779 | if mach.teleporterEnabled:
|
---|
780 | session = ctx['global'].openMachineSession(mach.id)
|
---|
781 | mach1 = session.machine
|
---|
782 | mach1.teleporterEnabled = False
|
---|
783 | mach1.saveSettings()
|
---|
784 | session.close()
|
---|
785 | return 0
|
---|
786 |
|
---|
787 | def gueststatsCmd(ctx, args):
|
---|
788 | if (len(args) < 2):
|
---|
789 | print "usage: gueststats name <check interval>"
|
---|
790 | return 0
|
---|
791 | mach = argsToMach(ctx,args)
|
---|
792 | if mach == None:
|
---|
793 | return 0
|
---|
794 | cmdExistingVm(ctx, mach, 'gueststats', args[2:])
|
---|
795 | return 0
|
---|
796 |
|
---|
797 | def plugcpuCmd(ctx, args):
|
---|
798 | if (len(args) < 2):
|
---|
799 | print "usage: plugcpu name cpuid"
|
---|
800 | return 0
|
---|
801 | mach = argsToMach(ctx,args)
|
---|
802 | if mach == None:
|
---|
803 | return 0
|
---|
804 | cmdExistingVm(ctx, mach, 'plugcpu', args[2])
|
---|
805 | return 0
|
---|
806 |
|
---|
807 | def unplugcpuCmd(ctx, args):
|
---|
808 | if (len(args) < 2):
|
---|
809 | print "usage: unplugcpu name cpuid"
|
---|
810 | return 0
|
---|
811 | mach = argsToMach(ctx,args)
|
---|
812 | if mach == None:
|
---|
813 | return 0
|
---|
814 | cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
|
---|
815 | return 0
|
---|
816 |
|
---|
817 | def setvarCmd(ctx, args):
|
---|
818 | if (len(args) < 4):
|
---|
819 | print "usage: setvar [vmname|uuid] expr value"
|
---|
820 | return 0
|
---|
821 | mach = argsToMach(ctx,args)
|
---|
822 | if mach == None:
|
---|
823 | return 0
|
---|
824 | session = ctx['global'].openMachineSession(mach.id)
|
---|
825 | mach = session.machine
|
---|
826 | expr = 'mach.'+args[2]+' = '+args[3]
|
---|
827 | print "Executing",expr
|
---|
828 | try:
|
---|
829 | exec expr
|
---|
830 | except Exception, e:
|
---|
831 | print 'failed: ',e
|
---|
832 | if g_verbose:
|
---|
833 | traceback.print_exc()
|
---|
834 | mach.saveSettings()
|
---|
835 | session.close()
|
---|
836 | return 0
|
---|
837 |
|
---|
838 |
|
---|
839 | def setExtraDataCmd(ctx, args):
|
---|
840 | if (len(args) < 3):
|
---|
841 | print "usage: setextra [vmname|uuid|global] key <value>"
|
---|
842 | return 0
|
---|
843 | key = args[2]
|
---|
844 | if len(args) == 4:
|
---|
845 | value = args[3]
|
---|
846 | else:
|
---|
847 | value = None
|
---|
848 | if args[1] == 'global':
|
---|
849 | ctx['vb'].setExtraData(key, value)
|
---|
850 | return 0
|
---|
851 |
|
---|
852 | mach = argsToMach(ctx,args)
|
---|
853 | if mach == None:
|
---|
854 | return 0
|
---|
855 | session = ctx['global'].openMachineSession(mach.id)
|
---|
856 | mach = session.machine
|
---|
857 | mach.setExtraData(key, value)
|
---|
858 | mach.saveSettings()
|
---|
859 | session.close()
|
---|
860 | return 0
|
---|
861 |
|
---|
862 | def printExtraKey(obj, key, value):
|
---|
863 | print "%s: '%s' = '%s'" %(obj, key, value)
|
---|
864 |
|
---|
865 | def getExtraDataCmd(ctx, args):
|
---|
866 | if (len(args) < 2):
|
---|
867 | print "usage: getextra [vmname|uuid|global] <key>"
|
---|
868 | return 0
|
---|
869 | if len(args) == 3:
|
---|
870 | key = args[2]
|
---|
871 | else:
|
---|
872 | key = None
|
---|
873 |
|
---|
874 | if args[1] == 'global':
|
---|
875 | obj = ctx['vb']
|
---|
876 | else:
|
---|
877 | obj = argsToMach(ctx,args)
|
---|
878 | if obj == None:
|
---|
879 | return 0
|
---|
880 |
|
---|
881 | if key == None:
|
---|
882 | keys = obj.getExtraDataKeys()
|
---|
883 | else:
|
---|
884 | keys = [ key ]
|
---|
885 | for k in keys:
|
---|
886 | printExtraKey(args[1], k, ctx['vb'].getExtraData(k))
|
---|
887 |
|
---|
888 | return 0
|
---|
889 |
|
---|
890 | def quitCmd(ctx, args):
|
---|
891 | return 1
|
---|
892 |
|
---|
893 | def aliasCmd(ctx, args):
|
---|
894 | if (len(args) == 3):
|
---|
895 | aliases[args[1]] = args[2]
|
---|
896 | return 0
|
---|
897 |
|
---|
898 | for (k,v) in aliases.items():
|
---|
899 | print "'%s' is an alias for '%s'" %(k,v)
|
---|
900 | return 0
|
---|
901 |
|
---|
902 | def verboseCmd(ctx, args):
|
---|
903 | global g_verbose
|
---|
904 | g_verbose = not g_verbose
|
---|
905 | return 0
|
---|
906 |
|
---|
907 | def getUSBStateString(state):
|
---|
908 | if state == 0:
|
---|
909 | return "NotSupported"
|
---|
910 | elif state == 1:
|
---|
911 | return "Unavailable"
|
---|
912 | elif state == 2:
|
---|
913 | return "Busy"
|
---|
914 | elif state == 3:
|
---|
915 | return "Available"
|
---|
916 | elif state == 4:
|
---|
917 | return "Held"
|
---|
918 | elif state == 5:
|
---|
919 | return "Captured"
|
---|
920 | else:
|
---|
921 | return "Unknown"
|
---|
922 |
|
---|
923 | def hostCmd(ctx, args):
|
---|
924 | host = ctx['vb'].host
|
---|
925 | cnt = host.processorCount
|
---|
926 | print "Processor count:",cnt
|
---|
927 | for i in range(0,cnt):
|
---|
928 | print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
|
---|
929 |
|
---|
930 | print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
|
---|
931 | print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
|
---|
932 | if host.Acceleration3DAvailable:
|
---|
933 | print "3D acceleration available"
|
---|
934 | else:
|
---|
935 | print "3D acceleration NOT available"
|
---|
936 |
|
---|
937 | print "Network interfaces:"
|
---|
938 | for ni in ctx['global'].getArray(host, 'networkInterfaces'):
|
---|
939 | print " %s (%s)" %(ni.name, ni.IPAddress)
|
---|
940 |
|
---|
941 | print "DVD drives:"
|
---|
942 | for dd in ctx['global'].getArray(host, 'DVDDrives'):
|
---|
943 | print " %s - %s" %(dd.name, dd.description)
|
---|
944 |
|
---|
945 | print "USB devices:"
|
---|
946 | for ud in ctx['global'].getArray(host, 'USBDevices'):
|
---|
947 | print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
|
---|
948 |
|
---|
949 | if ctx['perf']:
|
---|
950 | for metric in ctx['perf'].query(["*"], [host]):
|
---|
951 | print metric['name'], metric['values_as_string']
|
---|
952 |
|
---|
953 | return 0
|
---|
954 |
|
---|
955 | def monitorGuestCmd(ctx, args):
|
---|
956 | if (len(args) < 2):
|
---|
957 | print "usage: monitorGuest name (duration)"
|
---|
958 | return 0
|
---|
959 | mach = argsToMach(ctx,args)
|
---|
960 | if mach == None:
|
---|
961 | return 0
|
---|
962 | dur = 5
|
---|
963 | if len(args) > 2:
|
---|
964 | dur = float(args[2])
|
---|
965 | cmdExistingVm(ctx, mach, 'monitorGuest', dur)
|
---|
966 | return 0
|
---|
967 |
|
---|
968 | def monitorVBoxCmd(ctx, args):
|
---|
969 | if (len(args) > 2):
|
---|
970 | print "usage: monitorVBox (duration)"
|
---|
971 | return 0
|
---|
972 | dur = 5
|
---|
973 | if len(args) > 1:
|
---|
974 | dur = float(args[1])
|
---|
975 | monitorVBox(ctx, dur)
|
---|
976 | return 0
|
---|
977 |
|
---|
978 | def getAdapterType(ctx, type):
|
---|
979 | if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
|
---|
980 | type == ctx['global'].constants.NetworkAdapterType_Am79C973):
|
---|
981 | return "pcnet"
|
---|
982 | elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
|
---|
983 | type == ctx['global'].constants.NetworkAdapterType_I82545EM or
|
---|
984 | type == ctx['global'].constants.NetworkAdapterType_I82543GC):
|
---|
985 | return "e1000"
|
---|
986 | elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
|
---|
987 | return "virtio"
|
---|
988 | elif (type == ctx['global'].constants.NetworkAdapterType_Null):
|
---|
989 | return None
|
---|
990 | else:
|
---|
991 | raise Exception("Unknown adapter type: "+type)
|
---|
992 |
|
---|
993 |
|
---|
994 | def portForwardCmd(ctx, args):
|
---|
995 | if (len(args) != 5):
|
---|
996 | print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
|
---|
997 | return 0
|
---|
998 | mach = argsToMach(ctx,args)
|
---|
999 | if mach == None:
|
---|
1000 | return 0
|
---|
1001 | adapterNum = int(args[2])
|
---|
1002 | hostPort = int(args[3])
|
---|
1003 | guestPort = int(args[4])
|
---|
1004 | proto = "TCP"
|
---|
1005 | session = ctx['global'].openMachineSession(mach.id)
|
---|
1006 | mach = session.machine
|
---|
1007 |
|
---|
1008 | adapter = mach.getNetworkAdapter(adapterNum)
|
---|
1009 | adapterType = getAdapterType(ctx, adapter.adapterType)
|
---|
1010 |
|
---|
1011 | profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
|
---|
1012 | config = "VBoxInternal/Devices/" + adapterType + "/"
|
---|
1013 | config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
|
---|
1014 |
|
---|
1015 | mach.setExtraData(config + "/Protocol", proto)
|
---|
1016 | mach.setExtraData(config + "/HostPort", str(hostPort))
|
---|
1017 | mach.setExtraData(config + "/GuestPort", str(guestPort))
|
---|
1018 |
|
---|
1019 | mach.saveSettings()
|
---|
1020 | session.close()
|
---|
1021 |
|
---|
1022 | return 0
|
---|
1023 |
|
---|
1024 |
|
---|
1025 | def showLogCmd(ctx, args):
|
---|
1026 | if (len(args) < 2):
|
---|
1027 | print "usage: showLog <vm> <num>"
|
---|
1028 | return 0
|
---|
1029 | mach = argsToMach(ctx,args)
|
---|
1030 | if mach == None:
|
---|
1031 | return 0
|
---|
1032 |
|
---|
1033 | log = "VBox.log"
|
---|
1034 | if (len(args) > 2):
|
---|
1035 | log += "."+args[2]
|
---|
1036 | fileName = os.path.join(mach.logFolder, log)
|
---|
1037 |
|
---|
1038 | try:
|
---|
1039 | lf = open(fileName, 'r')
|
---|
1040 | except IOError,e:
|
---|
1041 | print "cannot open: ",e
|
---|
1042 | return 0
|
---|
1043 |
|
---|
1044 | for line in lf:
|
---|
1045 | print line,
|
---|
1046 | lf.close()
|
---|
1047 |
|
---|
1048 | return 0
|
---|
1049 |
|
---|
1050 | def evalCmd(ctx, args):
|
---|
1051 | expr = ' '.join(args[1:])
|
---|
1052 | try:
|
---|
1053 | exec expr
|
---|
1054 | except Exception, e:
|
---|
1055 | print 'failed: ',e
|
---|
1056 | if g_verbose:
|
---|
1057 | traceback.print_exc()
|
---|
1058 | return 0
|
---|
1059 |
|
---|
1060 | def reloadExtCmd(ctx, args):
|
---|
1061 | # maybe will want more args smartness
|
---|
1062 | checkUserExtensions(ctx, commands, getHomeFolder(ctx))
|
---|
1063 | autoCompletion(commands, ctx)
|
---|
1064 | return 0
|
---|
1065 |
|
---|
1066 |
|
---|
1067 | def runScriptCmd(ctx, args):
|
---|
1068 | if (len(args) != 2):
|
---|
1069 | print "usage: runScript <script>"
|
---|
1070 | return 0
|
---|
1071 | try:
|
---|
1072 | lf = open(args[1], 'r')
|
---|
1073 | except IOError,e:
|
---|
1074 | print "cannot open:",args[1], ":",e
|
---|
1075 | return 0
|
---|
1076 |
|
---|
1077 | try:
|
---|
1078 | for line in lf:
|
---|
1079 | done = runCommand(ctx, line)
|
---|
1080 | if done != 0: break
|
---|
1081 | except Exception,e:
|
---|
1082 | print "error:",e
|
---|
1083 | if g_verbose:
|
---|
1084 | traceback.print_exc()
|
---|
1085 | lf.close()
|
---|
1086 | return 0
|
---|
1087 |
|
---|
1088 | def sleepCmd(ctx, args):
|
---|
1089 | if (len(args) != 2):
|
---|
1090 | print "usage: sleep <secs>"
|
---|
1091 | return 0
|
---|
1092 |
|
---|
1093 | try:
|
---|
1094 | time.sleep(float(args[1]))
|
---|
1095 | except:
|
---|
1096 | # to allow sleep interrupt
|
---|
1097 | pass
|
---|
1098 | return 0
|
---|
1099 |
|
---|
1100 |
|
---|
1101 | def shellCmd(ctx, args):
|
---|
1102 | if (len(args) < 2):
|
---|
1103 | print "usage: shell <commands>"
|
---|
1104 | return 0
|
---|
1105 | cmd = ' '.join(args[1:])
|
---|
1106 | try:
|
---|
1107 | os.system(cmd)
|
---|
1108 | except KeyboardInterrupt:
|
---|
1109 | # to allow shell command interruption
|
---|
1110 | pass
|
---|
1111 | return 0
|
---|
1112 |
|
---|
1113 |
|
---|
1114 | def connectCmd(ctx, args):
|
---|
1115 | if (len(args) > 4):
|
---|
1116 | print "usage: connect [url] [username] [passwd]"
|
---|
1117 | return 0
|
---|
1118 |
|
---|
1119 | if ctx['vb'] is not None:
|
---|
1120 | print "Already connected, disconnect first..."
|
---|
1121 | return 0
|
---|
1122 |
|
---|
1123 | if (len(args) > 1):
|
---|
1124 | url = args[1]
|
---|
1125 | else:
|
---|
1126 | url = None
|
---|
1127 |
|
---|
1128 | if (len(args) > 2):
|
---|
1129 | user = args[2]
|
---|
1130 | else:
|
---|
1131 | user = ""
|
---|
1132 |
|
---|
1133 | if (len(args) > 3):
|
---|
1134 | passwd = args[3]
|
---|
1135 | else:
|
---|
1136 | passwd = ""
|
---|
1137 |
|
---|
1138 | vbox = ctx['global'].platform.connect(url, user, passwd)
|
---|
1139 | ctx['vb'] = vbox
|
---|
1140 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1141 | ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
|
---|
1142 | return 0
|
---|
1143 |
|
---|
1144 | def disconnectCmd(ctx, args):
|
---|
1145 | if (len(args) != 1):
|
---|
1146 | print "usage: disconnect"
|
---|
1147 | return 0
|
---|
1148 |
|
---|
1149 | if ctx['vb'] is None:
|
---|
1150 | print "Not connected yet."
|
---|
1151 | return 0
|
---|
1152 |
|
---|
1153 | try:
|
---|
1154 | ctx['global'].platform.disconnect()
|
---|
1155 | except:
|
---|
1156 | ctx['vb'] = None
|
---|
1157 | raise
|
---|
1158 |
|
---|
1159 | ctx['vb'] = None
|
---|
1160 | return 0
|
---|
1161 |
|
---|
1162 | def exportVMCmd(ctx, args):
|
---|
1163 | import sys
|
---|
1164 |
|
---|
1165 | if len(args) < 3:
|
---|
1166 | print "usage: exportVm <machine> <path> <format> <license>"
|
---|
1167 | return 0
|
---|
1168 | mach = ctx['machById'](args[1])
|
---|
1169 | if mach is None:
|
---|
1170 | return 0
|
---|
1171 | path = args[2]
|
---|
1172 | if (len(args) > 3):
|
---|
1173 | format = args[3]
|
---|
1174 | else:
|
---|
1175 | format = "ovf-1.0"
|
---|
1176 | if (len(args) > 4):
|
---|
1177 | license = args[4]
|
---|
1178 | else:
|
---|
1179 | license = "GPL"
|
---|
1180 |
|
---|
1181 | app = ctx['vb'].createAppliance()
|
---|
1182 | desc = mach.export(app)
|
---|
1183 | desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
|
---|
1184 | p = app.write(format, path)
|
---|
1185 | progressBar(ctx, p)
|
---|
1186 | print "Exported to %s in format %s" %(path, format)
|
---|
1187 | return 0
|
---|
1188 |
|
---|
1189 | aliases = {'s':'start',
|
---|
1190 | 'i':'info',
|
---|
1191 | 'l':'list',
|
---|
1192 | 'h':'help',
|
---|
1193 | 'a':'alias',
|
---|
1194 | 'q':'quit', 'exit':'quit',
|
---|
1195 | 'v':'verbose'}
|
---|
1196 |
|
---|
1197 | commands = {'help':['Prints help information', helpCmd, 0],
|
---|
1198 | 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
|
---|
1199 | 'create':['Create virtual machine', createCmd, 0],
|
---|
1200 | 'remove':['Remove virtual machine', removeCmd, 0],
|
---|
1201 | 'pause':['Pause virtual machine', pauseCmd, 0],
|
---|
1202 | 'resume':['Resume virtual machine', resumeCmd, 0],
|
---|
1203 | 'save':['Save execution state of virtual machine', saveCmd, 0],
|
---|
1204 | 'stats':['Stats for virtual machine', statsCmd, 0],
|
---|
1205 | 'powerdown':['Power down virtual machine', powerdownCmd, 0],
|
---|
1206 | 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
|
---|
1207 | 'list':['Shows known virtual machines', listCmd, 0],
|
---|
1208 | 'info':['Shows info on machine', infoCmd, 0],
|
---|
1209 | 'alias':['Control aliases', aliasCmd, 0],
|
---|
1210 | 'verbose':['Toggle verbosity', verboseCmd, 0],
|
---|
1211 | 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
|
---|
1212 | 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
|
---|
1213 | 'quit':['Exits', quitCmd, 0],
|
---|
1214 | 'host':['Show host information', hostCmd, 0],
|
---|
1215 | 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
|
---|
1216 | 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
|
---|
1217 | 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
|
---|
1218 | 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
|
---|
1219 | 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
|
---|
1220 | 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
|
---|
1221 | 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
|
---|
1222 | 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
|
---|
1223 | 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
|
---|
1224 | 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
|
---|
1225 | 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
|
---|
1226 | 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd>', teleportCmd, 0],
|
---|
1227 | 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
|
---|
1228 | 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
|
---|
1229 | 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
|
---|
1230 | 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
|
---|
1231 | 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
|
---|
1232 | 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
|
---|
1233 | 'unplugcpu':['Remove a CPU from a running VM: plugcpu Win 1', unplugcpuCmd, 0],
|
---|
1234 | }
|
---|
1235 |
|
---|
1236 | def runCommandArgs(ctx, args):
|
---|
1237 | c = args[0]
|
---|
1238 | if aliases.get(c, None) != None:
|
---|
1239 | c = aliases[c]
|
---|
1240 | ci = commands.get(c,None)
|
---|
1241 | if ci == None:
|
---|
1242 | print "Unknown command: '%s', type 'help' for list of known commands" %(c)
|
---|
1243 | return 0
|
---|
1244 | return ci[1](ctx, args)
|
---|
1245 |
|
---|
1246 |
|
---|
1247 | def runCommand(ctx, cmd):
|
---|
1248 | if len(cmd) == 0: return 0
|
---|
1249 | args = split_no_quotes(cmd)
|
---|
1250 | if len(args) == 0: return 0
|
---|
1251 | return runCommandArgs(ctx, args)
|
---|
1252 |
|
---|
1253 | #
|
---|
1254 | # To write your own custom commands to vboxshell, create
|
---|
1255 | # file ~/.VirtualBox/shellext.py with content like
|
---|
1256 | #
|
---|
1257 | # def runTestCmd(ctx, args):
|
---|
1258 | # print "Testy test", ctx['vb']
|
---|
1259 | # return 0
|
---|
1260 | #
|
---|
1261 | # commands = {
|
---|
1262 | # 'test': ['Test help', runTestCmd]
|
---|
1263 | # }
|
---|
1264 | # and issue reloadExt shell command.
|
---|
1265 | # This file also will be read automatically on startup or 'reloadExt'.
|
---|
1266 | #
|
---|
1267 | # Also one can put shell extensions into ~/.VirtualBox/shexts and
|
---|
1268 | # they will also be picked up, so this way one can exchange
|
---|
1269 | # shell extensions easily.
|
---|
1270 | def addExtsFromFile(ctx, cmds, file):
|
---|
1271 | if not os.path.isfile(file):
|
---|
1272 | return
|
---|
1273 | d = {}
|
---|
1274 | try:
|
---|
1275 | execfile(file, d, d)
|
---|
1276 | for (k,v) in d['commands'].items():
|
---|
1277 | if g_verbose:
|
---|
1278 | print "customize: adding \"%s\" - %s" %(k, v[0])
|
---|
1279 | cmds[k] = [v[0], v[1], file]
|
---|
1280 | except:
|
---|
1281 | print "Error loading user extensions from %s" %(file)
|
---|
1282 | traceback.print_exc()
|
---|
1283 |
|
---|
1284 |
|
---|
1285 | def checkUserExtensions(ctx, cmds, folder):
|
---|
1286 | folder = str(folder)
|
---|
1287 | name = os.path.join(folder, "shellext.py")
|
---|
1288 | addExtsFromFile(ctx, cmds, name)
|
---|
1289 | # also check 'exts' directory for all files
|
---|
1290 | shextdir = os.path.join(folder, "shexts")
|
---|
1291 | if not os.path.isdir(shextdir):
|
---|
1292 | return
|
---|
1293 | exts = os.listdir(shextdir)
|
---|
1294 | for e in exts:
|
---|
1295 | addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
|
---|
1296 |
|
---|
1297 | def getHomeFolder(ctx):
|
---|
1298 | if ctx['remote'] or ctx['vb'] is None:
|
---|
1299 | return os.path.join(os.path.expanduser("~"), ".VirtualBox")
|
---|
1300 | else:
|
---|
1301 | return ctx['vb'].homeFolder
|
---|
1302 |
|
---|
1303 | def interpret(ctx):
|
---|
1304 | if ctx['remote']:
|
---|
1305 | commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
|
---|
1306 | commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
|
---|
1307 |
|
---|
1308 | vbox = ctx['vb']
|
---|
1309 |
|
---|
1310 | if vbox is not None:
|
---|
1311 | print "Running VirtualBox version %s" %(vbox.version)
|
---|
1312 | ctx['perf'] = ctx['global'].getPerfCollector(vbox)
|
---|
1313 | else:
|
---|
1314 | ctx['perf'] = None
|
---|
1315 |
|
---|
1316 | home = getHomeFolder(ctx)
|
---|
1317 | checkUserExtensions(ctx, commands, home)
|
---|
1318 |
|
---|
1319 | autoCompletion(commands, ctx)
|
---|
1320 |
|
---|
1321 | # to allow to print actual host information, we collect info for
|
---|
1322 | # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
|
---|
1323 | if ctx['perf']:
|
---|
1324 | try:
|
---|
1325 | ctx['perf'].setup(['*'], [vbox.host], 10, 15)
|
---|
1326 | except:
|
---|
1327 | pass
|
---|
1328 |
|
---|
1329 | while True:
|
---|
1330 | try:
|
---|
1331 | cmd = raw_input("vbox> ")
|
---|
1332 | done = runCommand(ctx, cmd)
|
---|
1333 | if done != 0: break
|
---|
1334 | except KeyboardInterrupt:
|
---|
1335 | print '====== You can type quit or q to leave'
|
---|
1336 | break
|
---|
1337 | except EOFError:
|
---|
1338 | break;
|
---|
1339 | except Exception,e:
|
---|
1340 | print e
|
---|
1341 | if g_verbose:
|
---|
1342 | traceback.print_exc()
|
---|
1343 | ctx['global'].waitForEvents(0)
|
---|
1344 | try:
|
---|
1345 | # There is no need to disable metric collection. This is just an example.
|
---|
1346 | if ct['perf']:
|
---|
1347 | ctx['perf'].disable(['*'], [vbox.host])
|
---|
1348 | except:
|
---|
1349 | pass
|
---|
1350 |
|
---|
1351 | def runCommandCb(ctx, cmd, args):
|
---|
1352 | args.insert(0, cmd)
|
---|
1353 | return runCommandArgs(ctx, args)
|
---|
1354 |
|
---|
1355 | def main(argv):
|
---|
1356 | style = None
|
---|
1357 | autopath = False
|
---|
1358 | argv.pop(0)
|
---|
1359 | while len(argv) > 0:
|
---|
1360 | if argv[0] == "-w":
|
---|
1361 | style = "WEBSERVICE"
|
---|
1362 | if argv[0] == "-a":
|
---|
1363 | autopath = True
|
---|
1364 | argv.pop(0)
|
---|
1365 |
|
---|
1366 | if autopath:
|
---|
1367 | cwd = os.getcwd()
|
---|
1368 | vpp = os.environ.get("VBOX_PROGRAM_PATH")
|
---|
1369 | if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
|
---|
1370 | vpp = cwd
|
---|
1371 | print "Autodetected VBOX_PROGRAM_PATH as",vpp
|
---|
1372 | os.environ["VBOX_PROGRAM_PATH"] = cwd
|
---|
1373 | sys.path.append(os.path.join(vpp, "sdk", "installer"))
|
---|
1374 |
|
---|
1375 | from vboxapi import VirtualBoxManager
|
---|
1376 | g_virtualBoxManager = VirtualBoxManager(style, None)
|
---|
1377 | ctx = {'global':g_virtualBoxManager,
|
---|
1378 | 'mgr':g_virtualBoxManager.mgr,
|
---|
1379 | 'vb':g_virtualBoxManager.vbox,
|
---|
1380 | 'ifaces':g_virtualBoxManager.constants,
|
---|
1381 | 'remote':g_virtualBoxManager.remote,
|
---|
1382 | 'type':g_virtualBoxManager.type,
|
---|
1383 | 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
|
---|
1384 | 'machById': lambda id: machById(ctx,id),
|
---|
1385 | 'argsToMach': lambda args: argsToMach(ctx,args),
|
---|
1386 | 'progressBar': lambda p: progressBar(ctx,p),
|
---|
1387 | '_machlist':None
|
---|
1388 | }
|
---|
1389 | interpret(ctx)
|
---|
1390 | g_virtualBoxManager.deinit()
|
---|
1391 | del g_virtualBoxManager
|
---|
1392 |
|
---|
1393 | if __name__ == '__main__':
|
---|
1394 | main(sys.argv)
|
---|