VirtualBox

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

Last change on this file since 26548 was 26548, checked in by vboxsync, 15 years ago

Main, FE: HPET review feedback

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