VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxShell/vboxshell.py@ 24581

Last change on this file since 24581 was 24581, checked in by vboxsync, 16 years ago

Python shell: teleportation support

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.0 KB
Line 
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.215389.xyz. 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
28import os,sys
29import traceback
30import shlex
31import time
32
33# Simple implementation of IConsoleCallback, one can use it as skeleton
34# for custom implementations
35class 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, needsHostCursor):
42 print "%s: onMouseCapabilityChange: needsHostCursor=%d" %(self.mach.name, 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
90class 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
135g_hasreadline = 1
136try:
137 import readline
138 import rlcompleter
139except:
140 g_hasreadline = 0
141
142
143if 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
194def 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
205g_verbose = True
206
207def split_no_quotes(s):
208 return shlex.split(s)
209
210def 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
221def reportError(ctx,session,rc):
222 if not ctx['remote']:
223 print session.QueryErrorObject(rc)
224
225
226def 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
236def 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, 'hardDiskAttachments'):
245 mach.detachHardDisk(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
256def 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
283def 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
291def asState(var):
292 if var:
293 return 'on'
294 else:
295 return 'off'
296
297def guestStats(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
303def guestExec(ctx, machine, console, cmds):
304 exec cmds
305
306def 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
322def 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
340def 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
363def 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
384def cmdExistingVm(ctx,mach,cmd,args):
385 mgr=ctx['mgr']
386 vb=ctx['vb']
387 session = mgr.getSessionObject(vb)
388 uuid = mach.id
389 try:
390 progress = vb.openExistingSession(session, uuid)
391 except Exception,e:
392 print "Session to '%s' not open: %s" %(mach.name,e)
393 if g_verbose:
394 traceback.print_exc()
395 return
396 if session.state != ctx['ifaces'].SessionState_Open:
397 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
398 return
399 # unfortunately IGuest is suppressed, thus WebServices knows not about it
400 # this is an example how to handle local only functionality
401 if ctx['remote'] and cmd == 'stats2':
402 print 'Trying to use local only functionality, ignored'
403 return
404 console=session.console
405 ops={'pause': lambda: console.pause(),
406 'resume': lambda: console.resume(),
407 'powerdown': lambda: console.powerDown(),
408 'powerbutton': lambda: console.powerButton(),
409 'stats': lambda: guestStats(ctx, mach),
410 'guest': lambda: guestExec(ctx, mach, console, args),
411 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
412 'save': lambda: progressBar(ctx,console.saveState()),
413 'screenshot': lambda: takeScreenshot(ctx,console,args),
414 'teleport': lambda: teleport(ctx,session,console,args)
415 }
416 try:
417 ops[cmd]()
418 except Exception, e:
419 print 'failed: ',e
420 if g_verbose:
421 traceback.print_exc()
422
423 session.close()
424
425def machById(ctx,id):
426 mach = None
427 for m in getMachines(ctx):
428 if m.name == id:
429 mach = m
430 break
431 mid = str(m.id)
432 if mid[0] == '{':
433 mid = mid[1:-1]
434 if mid == id:
435 mach = m
436 break
437 return mach
438
439def argsToMach(ctx,args):
440 if len(args) < 2:
441 print "usage: %s [vmname|uuid]" %(args[0])
442 return None
443 id = args[1]
444 m = machById(ctx, id)
445 if m == None:
446 print "Machine '%s' is unknown, use list command to find available machines" %(id)
447 return m
448
449def helpSingleCmd(cmd,h,sp):
450 if sp != 0:
451 spec = " [ext from "+sp+"]"
452 else:
453 spec = ""
454 print " %s: %s%s" %(cmd,h,spec)
455
456def helpCmd(ctx, args):
457 if len(args) == 1:
458 print "Help page:"
459 names = commands.keys()
460 names.sort()
461 for i in names:
462 helpSingleCmd(i, commands[i][0], commands[i][2])
463 else:
464 cmd = args[1]
465 c = commands.get(cmd)
466 if c == None:
467 print "Command '%s' not known" %(cmd)
468 else:
469 helpSingleCmd(cmd, c[0], c[2])
470 return 0
471
472def listCmd(ctx, args):
473 for m in getMachines(ctx, True):
474 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
475 return 0
476
477def getControllerType(type):
478 if type == 0:
479 return "Null"
480 elif type == 1:
481 return "LsiLogic"
482 elif type == 2:
483 return "BusLogic"
484 elif type == 3:
485 return "IntelAhci"
486 elif type == 4:
487 return "PIIX3"
488 elif type == 5:
489 return "PIIX4"
490 elif type == 6:
491 return "ICH6"
492 else:
493 return "Unknown"
494
495def infoCmd(ctx,args):
496 if (len(args) < 2):
497 print "usage: info [vmname|uuid]"
498 return 0
499 mach = argsToMach(ctx,args)
500 if mach == None:
501 return 0
502 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
503 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
504 print " Name [name]: %s" %(mach.name)
505 print " ID [n/a]: %s" %(mach.id)
506 print " OS Type [n/a]: %s" %(os.description)
507 print " Firmware [firmwareType]: %s" %(mach.firmwareType)
508 print
509 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
510 print " RAM [memorySize]: %dM" %(mach.memorySize)
511 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
512 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
513 print
514 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
515 print " Machine status [n/a]: %d" % (mach.sessionState)
516 print
517 bios = mach.BIOSSettings
518 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
519 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
520 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
521 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
522 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
523 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
524 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
525 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
526
527 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
528 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
529
530 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
531 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
532
533 controllers = ctx['global'].getArray(mach, 'storageControllers')
534 if controllers:
535 print
536 print " Controllers:"
537 for controller in controllers:
538 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
539
540 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
541 if attaches:
542 print
543 print " Mediums:"
544 for a in attaches:
545 print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
546 m = a.medium
547 if a.type == ctx['global'].constants.DeviceType_HardDisk:
548 print " HDD:"
549 print " Id: %s" %(m.id)
550 print " Location: %s" %(m.location)
551 print " Name: %s" %(m.name)
552 print " Format: %s" %(m.format)
553
554 if a.type == ctx['global'].constants.DeviceType_DVD:
555 print " DVD:"
556 if m:
557 print " Id: %s" %(m.id)
558 print " Name: %s" %(m.name)
559 if m.hostDrive:
560 print " Host DVD %s" %(m.location)
561 if a.passthrough:
562 print " [passthrough mode]"
563 else:
564 print " Virtual image at %s" %(m.location)
565 print " Size: %s" %(m.size)
566
567 if a.type == ctx['global'].constants.DeviceType_Floppy:
568 print " Floppy:"
569 if m:
570 print " Id: %s" %(m.id)
571 print " Name: %s" %(m.name)
572 if m.hostDrive:
573 print " Host floppy %s" %(m.location)
574 else:
575 print " Virtual image at %s" %(m.location)
576 print " Size: %s" %(m.size)
577
578 return 0
579
580def startCmd(ctx, args):
581 mach = argsToMach(ctx,args)
582 if mach == None:
583 return 0
584 if len(args) > 2:
585 type = args[2]
586 else:
587 type = "gui"
588 startVm(ctx, mach, type)
589 return 0
590
591def createCmd(ctx, args):
592 if (len(args) < 3 or len(args) > 4):
593 print "usage: create name ostype <basefolder>"
594 return 0
595 name = args[1]
596 oskind = args[2]
597 if len(args) == 4:
598 base = args[3]
599 else:
600 base = ''
601 try:
602 ctx['vb'].getGuestOSType(oskind)
603 except Exception, e:
604 print 'Unknown OS type:',oskind
605 return 0
606 createVm(ctx, name, oskind, base)
607 return 0
608
609def removeCmd(ctx, args):
610 mach = argsToMach(ctx,args)
611 if mach == None:
612 return 0
613 removeVm(ctx, mach)
614 return 0
615
616def pauseCmd(ctx, args):
617 mach = argsToMach(ctx,args)
618 if mach == None:
619 return 0
620 cmdExistingVm(ctx, mach, 'pause', '')
621 return 0
622
623def powerdownCmd(ctx, args):
624 mach = argsToMach(ctx,args)
625 if mach == None:
626 return 0
627 cmdExistingVm(ctx, mach, 'powerdown', '')
628 return 0
629
630def powerbuttonCmd(ctx, args):
631 mach = argsToMach(ctx,args)
632 if mach == None:
633 return 0
634 cmdExistingVm(ctx, mach, 'powerbutton', '')
635 return 0
636
637def resumeCmd(ctx, args):
638 mach = argsToMach(ctx,args)
639 if mach == None:
640 return 0
641 cmdExistingVm(ctx, mach, 'resume', '')
642 return 0
643
644def saveCmd(ctx, args):
645 mach = argsToMach(ctx,args)
646 if mach == None:
647 return 0
648 cmdExistingVm(ctx, mach, 'save', '')
649 return 0
650
651def statsCmd(ctx, args):
652 mach = argsToMach(ctx,args)
653 if mach == None:
654 return 0
655 cmdExistingVm(ctx, mach, 'stats', '')
656 return 0
657
658def guestCmd(ctx, args):
659 if (len(args) < 3):
660 print "usage: guest name commands"
661 return 0
662 mach = argsToMach(ctx,args)
663 if mach == None:
664 return 0
665 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
666 return 0
667
668def screenshotCmd(ctx, args):
669 if (len(args) < 3):
670 print "usage: screenshot name file <width> <height>"
671 return 0
672 mach = argsToMach(ctx,args)
673 if mach == None:
674 return 0
675 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
676 return 0
677
678def teleportCmd(ctx, args):
679 if (len(args) < 3):
680 print "usage: teleport name host:port <password>"
681 return 0
682 mach = argsToMach(ctx,args)
683 if mach == None:
684 return 0
685 cmdExistingVm(ctx, mach, 'teleport', args[2:])
686 return 0
687
688def makeportalCmd(ctx, args):
689 if (len(args) < 3):
690 print "usage: makeportal name port <password>"
691 return 0
692 mach = argsToMach(ctx,args)
693 if mach == None:
694 return 0
695 port = int(args[2])
696 if (len(args) > 3):
697 passwd = args[3]
698 else:
699 passwd = ""
700 if not mach.teleporterEnabled or mach.teleporterPort != port:
701 session = ctx['global'].openMachineSession(mach.id)
702 mach1 = session.machine
703 mach1.teleporterEnabled = True
704 mach1.teleporterPort = port
705 mach1.saveSettings()
706 session.close()
707 startVm(ctx, mach, "gui")
708 return 0
709
710def closeportalCmd(ctx, args):
711 if (len(args) < 2):
712 print "usage: closeportal name"
713 return 0
714 mach = argsToMach(ctx,args)
715 if mach == None:
716 return 0
717 if mach.teleporterEnabled:
718 session = ctx['global'].openMachineSession(mach.id)
719 mach1 = session.machine
720 mach1.teleporterEnabled = False
721 mach1.saveSettings()
722 session.close()
723 return 0
724
725
726def setvarCmd(ctx, args):
727 if (len(args) < 4):
728 print "usage: setvar [vmname|uuid] expr value"
729 return 0
730 mach = argsToMach(ctx,args)
731 if mach == None:
732 return 0
733 session = ctx['global'].openMachineSession(mach.id)
734 mach = session.machine
735 expr = 'mach.'+args[2]+' = '+args[3]
736 print "Executing",expr
737 try:
738 exec expr
739 except Exception, e:
740 print 'failed: ',e
741 if g_verbose:
742 traceback.print_exc()
743 mach.saveSettings()
744 session.close()
745 return 0
746
747def quitCmd(ctx, args):
748 return 1
749
750def aliasCmd(ctx, args):
751 if (len(args) == 3):
752 aliases[args[1]] = args[2]
753 return 0
754
755 for (k,v) in aliases.items():
756 print "'%s' is an alias for '%s'" %(k,v)
757 return 0
758
759def verboseCmd(ctx, args):
760 global g_verbose
761 g_verbose = not g_verbose
762 return 0
763
764def getUSBStateString(state):
765 if state == 0:
766 return "NotSupported"
767 elif state == 1:
768 return "Unavailable"
769 elif state == 2:
770 return "Busy"
771 elif state == 3:
772 return "Available"
773 elif state == 4:
774 return "Held"
775 elif state == 5:
776 return "Captured"
777 else:
778 return "Unknown"
779
780def hostCmd(ctx, args):
781 host = ctx['vb'].host
782 cnt = host.processorCount
783 print "Processor count:",cnt
784 for i in range(0,cnt):
785 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
786
787 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
788 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
789 if host.Acceleration3DAvailable:
790 print "3D acceleration available"
791 else:
792 print "3D acceleration NOT available"
793
794 print "Network interfaces:"
795 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
796 print " %s (%s)" %(ni.name, ni.IPAddress)
797
798 print "DVD drives:"
799 for dd in ctx['global'].getArray(host, 'DVDDrives'):
800 print " %s - %s" %(dd.name, dd.description)
801
802 print "USB devices:"
803 for ud in ctx['global'].getArray(host, 'USBDevices'):
804 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
805
806 if ctx['perf']:
807 for metric in ctx['perf'].query(["*"], [host]):
808 print metric['name'], metric['values_as_string']
809
810 return 0
811
812def monitorGuestCmd(ctx, args):
813 if (len(args) < 2):
814 print "usage: monitorGuest name (duration)"
815 return 0
816 mach = argsToMach(ctx,args)
817 if mach == None:
818 return 0
819 dur = 5
820 if len(args) > 2:
821 dur = float(args[2])
822 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
823 return 0
824
825def monitorVBoxCmd(ctx, args):
826 if (len(args) > 2):
827 print "usage: monitorVBox (duration)"
828 return 0
829 dur = 5
830 if len(args) > 1:
831 dur = float(args[1])
832 monitorVBox(ctx, dur)
833 return 0
834
835def getAdapterType(ctx, type):
836 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
837 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
838 return "pcnet"
839 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
840 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
841 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
842 return "e1000"
843 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
844 return "virtio"
845 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
846 return None
847 else:
848 raise Exception("Unknown adapter type: "+type)
849
850
851def portForwardCmd(ctx, args):
852 if (len(args) != 5):
853 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
854 return 0
855 mach = argsToMach(ctx,args)
856 if mach == None:
857 return 0
858 adapterNum = int(args[2])
859 hostPort = int(args[3])
860 guestPort = int(args[4])
861 proto = "TCP"
862 session = ctx['global'].openMachineSession(mach.id)
863 mach = session.machine
864
865 adapter = mach.getNetworkAdapter(adapterNum)
866 adapterType = getAdapterType(ctx, adapter.adapterType)
867
868 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
869 config = "VBoxInternal/Devices/" + adapterType + "/"
870 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
871
872 mach.setExtraData(config + "/Protocol", proto)
873 mach.setExtraData(config + "/HostPort", str(hostPort))
874 mach.setExtraData(config + "/GuestPort", str(guestPort))
875
876 mach.saveSettings()
877 session.close()
878
879 return 0
880
881
882def showLogCmd(ctx, args):
883 if (len(args) < 2):
884 print "usage: showLog <vm> <num>"
885 return 0
886 mach = argsToMach(ctx,args)
887 if mach == None:
888 return 0
889
890 log = "VBox.log"
891 if (len(args) > 2):
892 log += "."+args[2]
893 fileName = os.path.join(mach.logFolder, log)
894
895 try:
896 lf = open(fileName, 'r')
897 except IOError,e:
898 print "cannot open: ",e
899 return 0
900
901 for line in lf:
902 print line,
903 lf.close()
904
905 return 0
906
907def evalCmd(ctx, args):
908 expr = ' '.join(args[1:])
909 try:
910 exec expr
911 except Exception, e:
912 print 'failed: ',e
913 if g_verbose:
914 traceback.print_exc()
915 return 0
916
917def reloadExtCmd(ctx, args):
918 # maybe will want more args smartness
919 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
920 autoCompletion(commands, ctx)
921 return 0
922
923
924def runScriptCmd(ctx, args):
925 if (len(args) != 2):
926 print "usage: runScript <script>"
927 return 0
928 try:
929 lf = open(args[1], 'r')
930 except IOError,e:
931 print "cannot open:",args[1], ":",e
932 return 0
933
934 try:
935 for line in lf:
936 done = runCommand(ctx, line)
937 if done != 0: break
938 except Exception,e:
939 print "error:",e
940 if g_verbose:
941 traceback.print_exc()
942 lf.close()
943 return 0
944
945def sleepCmd(ctx, args):
946 if (len(args) != 2):
947 print "usage: sleep <secs>"
948 return 0
949
950 try:
951 time.sleep(float(args[1]))
952 except:
953 # to allow sleep interrupt
954 pass
955 return 0
956
957
958def shellCmd(ctx, args):
959 if (len(args) < 2):
960 print "usage: shell <commands>"
961 return 0
962 cmd = ' '.join(args[1:])
963 try:
964 os.system(cmd)
965 except KeyboardInterrupt:
966 # to allow shell command interruption
967 pass
968 return 0
969
970
971def connectCmd(ctx, args):
972 if (len(args) > 4):
973 print "usage: connect [url] [username] [passwd]"
974 return 0
975
976 if ctx['vb'] is not None:
977 print "Already connected, disconnect first..."
978 return 0
979
980 if (len(args) > 1):
981 url = args[1]
982 else:
983 url = None
984
985 if (len(args) > 2):
986 user = args[2]
987 else:
988 user = ""
989
990 if (len(args) > 3):
991 passwd = args[3]
992 else:
993 passwd = ""
994
995 vbox = ctx['global'].platform.connect(url, user, passwd)
996 ctx['vb'] = vbox
997 print "Running VirtualBox version %s" %(vbox.version)
998 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
999 return 0
1000
1001def disconnectCmd(ctx, args):
1002 if (len(args) != 1):
1003 print "usage: disconnect"
1004 return 0
1005
1006 if ctx['vb'] is None:
1007 print "Not connected yet."
1008 return 0
1009
1010 try:
1011 ctx['global'].platform.disconnect()
1012 except:
1013 ctx['vb'] = None
1014 raise
1015
1016 ctx['vb'] = None
1017 return 0
1018
1019def exportVMCmd(ctx, args):
1020 import sys
1021
1022 if len(args) < 3:
1023 print "usage: exportVm <machine> <path> <format> <license>"
1024 return 0
1025 mach = ctx['machById'](args[1])
1026 if mach is None:
1027 return 0
1028 path = args[2]
1029 if (len(args) > 3):
1030 format = args[3]
1031 else:
1032 format = "ovf-1.0"
1033 if (len(args) > 4):
1034 license = args[4]
1035 else:
1036 license = "GPL"
1037
1038 app = ctx['vb'].createAppliance()
1039 desc = mach.export(app)
1040 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1041 p = app.write(format, path)
1042 progressBar(ctx, p)
1043 print "Exported to %s in format %s" %(path, format)
1044 return 0
1045
1046aliases = {'s':'start',
1047 'i':'info',
1048 'l':'list',
1049 'h':'help',
1050 'a':'alias',
1051 'q':'quit', 'exit':'quit',
1052 'v':'verbose'}
1053
1054commands = {'help':['Prints help information', helpCmd, 0],
1055 'start':['Start virtual machine by name or uuid', startCmd, 0],
1056 'create':['Create virtual machine', createCmd, 0],
1057 'remove':['Remove virtual machine', removeCmd, 0],
1058 'pause':['Pause virtual machine', pauseCmd, 0],
1059 'resume':['Resume virtual machine', resumeCmd, 0],
1060 'save':['Save execution state of virtual machine', saveCmd, 0],
1061 'stats':['Stats for virtual machine', statsCmd, 0],
1062 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1063 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1064 'list':['Shows known virtual machines', listCmd, 0],
1065 'info':['Shows info on machine', infoCmd, 0],
1066 'alias':['Control aliases', aliasCmd, 0],
1067 'verbose':['Toggle verbosity', verboseCmd, 0],
1068 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1069 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1070 'quit':['Exits', quitCmd, 0],
1071 'host':['Show host information', hostCmd, 0],
1072 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
1073 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1074 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1075 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1076 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1077 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1078 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1079 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1080 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1081 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
1082 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1083 'teleport':['Teleport VM to another box (see makeportal): teleport Win anotherhost:8000 <passwd>', teleportCmd, 0],
1084 'makeportal':['Make portal for teleportation of VM from another box (see teleport): makeportal Win 8000 <passwd>', makeportalCmd, 0],
1085 'closeportal':['Close portal for teleportation of VM from another box (see teleport): closeportal Win', closeportalCmd, 0]
1086 }
1087
1088def runCommandArgs(ctx, args):
1089 c = args[0]
1090 if aliases.get(c, None) != None:
1091 c = aliases[c]
1092 ci = commands.get(c,None)
1093 if ci == None:
1094 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
1095 return 0
1096 return ci[1](ctx, args)
1097
1098
1099def runCommand(ctx, cmd):
1100 if len(cmd) == 0: return 0
1101 args = split_no_quotes(cmd)
1102 if len(args) == 0: return 0
1103 return runCommandArgs(ctx, args)
1104
1105#
1106# To write your own custom commands to vboxshell, create
1107# file ~/.VirtualBox/shellext.py with content like
1108#
1109# def runTestCmd(ctx, args):
1110# print "Testy test", ctx['vb']
1111# return 0
1112#
1113# commands = {
1114# 'test': ['Test help', runTestCmd]
1115# }
1116# and issue reloadExt shell command.
1117# This file also will be read automatically on startup or 'reloadExt'.
1118#
1119# Also one can put shell extensions into ~/.VirtualBox/shexts and
1120# they will also be picked up, so this way one can exchange
1121# shell extensions easily.
1122def addExtsFromFile(ctx, cmds, file):
1123 if not os.path.isfile(file):
1124 return
1125 d = {}
1126 try:
1127 execfile(file, d, d)
1128 for (k,v) in d['commands'].items():
1129 if g_verbose:
1130 print "customize: adding \"%s\" - %s" %(k, v[0])
1131 cmds[k] = [v[0], v[1], file]
1132 except:
1133 print "Error loading user extensions from %s" %(file)
1134 traceback.print_exc()
1135
1136
1137def checkUserExtensions(ctx, cmds, folder):
1138 folder = str(folder)
1139 name = os.path.join(folder, "shellext.py")
1140 addExtsFromFile(ctx, cmds, name)
1141 # also check 'exts' directory for all files
1142 shextdir = os.path.join(folder, "shexts")
1143 if not os.path.isdir(shextdir):
1144 return
1145 exts = os.listdir(shextdir)
1146 for e in exts:
1147 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
1148
1149def getHomeFolder(ctx):
1150 if ctx['remote'] or ctx['vb'] is None:
1151 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
1152 else:
1153 return ctx['vb'].homeFolder
1154
1155def interpret(ctx):
1156 if ctx['remote']:
1157 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
1158 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
1159
1160 vbox = ctx['vb']
1161
1162 if vbox is not None:
1163 print "Running VirtualBox version %s" %(vbox.version)
1164 ctx['perf'] = ctx['global'].getPerfCollector(vbox)
1165 else:
1166 ctx['perf'] = None
1167
1168 home = getHomeFolder(ctx)
1169 checkUserExtensions(ctx, commands, home)
1170
1171 autoCompletion(commands, ctx)
1172
1173 # to allow to print actual host information, we collect info for
1174 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
1175 if ctx['perf']:
1176 try:
1177 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
1178 except:
1179 pass
1180
1181 while True:
1182 try:
1183 cmd = raw_input("vbox> ")
1184 done = runCommand(ctx, cmd)
1185 if done != 0: break
1186 except KeyboardInterrupt:
1187 print '====== You can type quit or q to leave'
1188 break
1189 except EOFError:
1190 break;
1191 except Exception,e:
1192 print e
1193 if g_verbose:
1194 traceback.print_exc()
1195 ctx['global'].waitForEvents(0)
1196 try:
1197 # There is no need to disable metric collection. This is just an example.
1198 if ct['perf']:
1199 ctx['perf'].disable(['*'], [vbox.host])
1200 except:
1201 pass
1202
1203def runCommandCb(ctx, cmd, args):
1204 args.insert(0, cmd)
1205 return runCommandArgs(ctx, args)
1206
1207def main(argv):
1208 style = None
1209 autopath = False
1210 argv.pop(0)
1211 while len(argv) > 0:
1212 if argv[0] == "-w":
1213 style = "WEBSERVICE"
1214 if argv[0] == "-a":
1215 autopath = True
1216 argv.pop(0)
1217
1218 if autopath:
1219 cwd = os.getcwd()
1220 vpp = os.environ.get("VBOX_PROGRAM_PATH")
1221 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
1222 vpp = cwd
1223 print "Autodetected VBOX_PROGRAM_PATH as",vpp
1224 os.environ["VBOX_PROGRAM_PATH"] = cwd
1225 sys.path.append(os.path.join(vpp, "sdk", "installer"))
1226
1227 from vboxapi import VirtualBoxManager
1228 g_virtualBoxManager = VirtualBoxManager(style, None)
1229 ctx = {'global':g_virtualBoxManager,
1230 'mgr':g_virtualBoxManager.mgr,
1231 'vb':g_virtualBoxManager.vbox,
1232 'ifaces':g_virtualBoxManager.constants,
1233 'remote':g_virtualBoxManager.remote,
1234 'type':g_virtualBoxManager.type,
1235 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1236 'machById': lambda id: machById(ctx,id),
1237 'progressBar': lambda p: progressBar(ctx,p),
1238 '_machlist':None
1239 }
1240 interpret(ctx)
1241 g_virtualBoxManager.deinit()
1242 del g_virtualBoxManager
1243
1244if __name__ == '__main__':
1245 main(sys.argv)
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette