VirtualBox

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

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

typo

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 27.2 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#################################################################################
19# This program is a simple interactive shell for VirtualBox. You can query #
20# information and issue commands from a simple command line. #
21# #
22# It also provides you with examples on how to use VirtualBox's Python API. #
23# This shell is even somewhat documented and supports TAB-completion and #
24# history if you have Python readline installed. #
25# #
26# Enjoy. #
27################################################################################
28
29import os,sys
30import traceback
31import shlex
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 onDVDDriveChange(self):
54 print "%s: onDVDDriveChange" %(self.mach.name)
55
56 def onFloppyDriveChange(self):
57 print "%s: onFloppyDriveChange" %(self.mach.name)
58
59 def onNetworkAdapterChange(self, adapter):
60 print "%s: onNetworkAdapterChange" %(self.mach.name)
61
62 def onSerialPortChange(self, port):
63 print "%s: onSerialPortChange" %(self.mach.name)
64
65 def onParallelPortChange(self, port):
66 print "%s: onParallelPortChange" %(self.mach.name)
67
68 def onStorageControllerChange(self):
69 print "%s: onStorageControllerChange" %(self.mach.name)
70
71 def onVRDPServerChange(self):
72 print "%s: onVRDPServerChange" %(self.mach.name)
73
74 def onUSBControllerChange(self):
75 print "%s: onUSBControllerChange" %(self.mach.name)
76
77 def onUSBDeviceStateChange(self, device, attached, error):
78 print "%s: onUSBDeviceStateChange" %(self.mach.name)
79
80 def onSharedFolderChange(self, scope):
81 print "%s: onSharedFolderChange" %(self.mach.name)
82
83 def onRuntimeError(self, fatal, id, message):
84 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
85
86 def onCanShowWindow(self):
87 print "%s: onCanShowWindow" %(self.mach.name)
88 return True
89
90 def onShowWindow(self, winId):
91 print "%s: onShowWindow: %d" %(self.mach.name, winId)
92
93class VBoxMonitor:
94 def __init__(self, vbox):
95 self.vbox = vbox
96 pass
97
98 def onMachineStateChange(self, id, state):
99 print "onMachineStateChange: %s %d" %(id, state)
100
101 def onMachineDataChange(self,id):
102 print "onMachineDataChange: %s" %(id)
103
104 def onExtraDataCanChange(self, id, key, value):
105 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
106 return True, ""
107
108 def onExtraDataChange(self, id, key, value):
109 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
110
111 def onMediaRegistred(self, id, type, registred):
112 print "onMediaRegistred: %s" %(id)
113
114 def onMachineRegistred(self, id, registred):
115 print "onMachineRegistred: %s" %(id)
116
117 def onSessionStateChange(self, id, state):
118 print "onSessionStateChange: %s %d" %(id, state)
119
120 def onSnapshotTaken(self, mach, id):
121 print "onSnapshotTaken: %s %s" %(mach, id)
122
123 def onSnapshotDiscarded(self, mach, id):
124 print "onSnapshotDiscarded: %s %s" %(mach, id)
125
126 def onSnapshotChange(self, mach, id):
127 print "onSnapshotChange: %s %s" %(mach, id)
128
129 def onGuestPropertyChange(self, id, name, newValue, flags):
130 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
131
132g_hasreadline = 1
133try:
134 import readline
135 import rlcompleter
136except:
137 g_hasreadline = 0
138
139
140if g_hasreadline:
141 class CompleterNG(rlcompleter.Completer):
142 def __init__(self, dic, ctx):
143 self.ctx = ctx
144 return rlcompleter.Completer.__init__(self,dic)
145
146 def complete(self, text, state):
147 """
148 taken from:
149 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
150 """
151 if text == "":
152 return ['\t',None][state]
153 else:
154 return rlcompleter.Completer.complete(self,text,state)
155
156 def global_matches(self, text):
157 """
158 Compute matches when text is a simple name.
159 Return a list of all names currently defined
160 in self.namespace that match.
161 """
162
163 matches = []
164 n = len(text)
165
166 for list in [ self.namespace ]:
167 for word in list:
168 if word[:n] == text:
169 matches.append(word)
170
171
172 try:
173 for m in getMachines(self.ctx):
174 # although it has autoconversion, we need to cast
175 # explicitly for subscripts to work
176 word = str(m.name)
177 if word[:n] == text:
178 matches.append(word)
179 word = str(m.id)
180 if word[0] == '{':
181 word = word[1:-1]
182 if word[:n] == text:
183 matches.append(word)
184 except Exception,e:
185 traceback.print_exc()
186 print e
187
188 return matches
189
190
191def autoCompletion(commands, ctx):
192 if not g_hasreadline:
193 return
194
195 comps = {}
196 for (k,v) in commands.items():
197 comps[k] = None
198 completer = CompleterNG(comps, ctx)
199 readline.set_completer(completer.complete)
200 readline.parse_and_bind("tab: complete")
201
202g_verbose = True
203
204def split_no_quotes(s):
205 return shlex.split(s)
206
207def createVm(ctx,name,kind,base):
208 mgr = ctx['mgr']
209 vb = ctx['vb']
210 mach = vb.createMachine(name, kind, base,
211 "00000000-0000-0000-0000-000000000000")
212 mach.saveSettings()
213 print "created machine with UUID",mach.id
214 vb.registerMachine(mach)
215
216def removeVm(ctx,mach):
217 mgr = ctx['mgr']
218 vb = ctx['vb']
219 id = mach.id
220 print "removing machine ",mach.name,"with UUID",id
221 session = ctx['global'].openMachineSession(id)
222 mach=session.machine
223 for d in mach.getHardDiskAttachments():
224 mach.detachHardDisk(d.controller, d.port, d.device)
225 ctx['global'].closeMachineSession(session)
226 mach = vb.unregisterMachine(id)
227 if mach:
228 mach.deleteSettings()
229
230def startVm(ctx,mach,type):
231 mgr = ctx['mgr']
232 vb = ctx['vb']
233 perf = ctx['perf']
234 session = mgr.getSessionObject(vb)
235 uuid = mach.id
236 progress = vb.openRemoteSession(session, uuid, type, "")
237 progress.waitForCompletion(-1)
238 completed = progress.completed
239 rc = int(progress.resultCode)
240 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
241 if rc == 0:
242 # we ignore exceptions to allow starting VM even if
243 # perf collector cannot be started
244 if perf:
245 try:
246 perf.setup(['*'], [mach], 10, 15)
247 except Exception,e:
248 print e
249 if g_verbose:
250 traceback.print_exc()
251 pass
252 # if session not opened, close doesn't make sense
253 session.close()
254 else:
255 # Not yet implemented error string query API for remote API
256 if not ctx['remote']:
257 print session.QueryErrorObject(rc)
258
259def getMachines(ctx):
260 return ctx['global'].getArray(ctx['vb'], 'machines')
261
262def asState(var):
263 if var:
264 return 'on'
265 else:
266 return 'off'
267
268def guestStats(ctx,mach):
269 if not ctx['perf']:
270 return
271 for metric in ctx['perf'].query(["*"], [mach]):
272 print metric['name'], metric['values_as_string']
273
274def guestExec(ctx, machine, console, cmds):
275 exec cmds
276
277def monitorGuest(ctx, machine, console, dur):
278 import time
279 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
280 console.registerCallback(cb)
281 if dur == -1:
282 # not infinity, but close enough
283 dur = 100000
284 try:
285 end = time.time() + dur
286 while time.time() < end:
287 ctx['global'].waitForEvents(500)
288 # We need to catch all exceptions here, otherwise callback will never be unregistered
289 except:
290 pass
291 console.unregisterCallback(cb)
292
293
294def monitorVbox(ctx, dur):
295 import time
296 vbox = ctx['vb']
297 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, vbox)
298 vbox.registerCallback(cb)
299 if dur == -1:
300 # not infinity, but close enough
301 dur = 100000
302 try:
303 end = time.time() + dur
304 while time.time() < end:
305 ctx['global'].waitForEvents(500)
306 # We need to catch all exceptions here, otherwise callback will never be unregistered
307 except:
308 if g_verbose:
309 traceback.print_exc()
310 vbox.unregisterCallback(cb)
311
312def cmdExistingVm(ctx,mach,cmd,args):
313 mgr=ctx['mgr']
314 vb=ctx['vb']
315 session = mgr.getSessionObject(vb)
316 uuid = mach.id
317 try:
318 progress = vb.openExistingSession(session, uuid)
319 except Exception,e:
320 print "Session to '%s' not open: %s" %(mach.name,e)
321 if g_verbose:
322 traceback.print_exc()
323 return
324 if session.state != ctx['ifaces'].SessionState_Open:
325 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
326 return
327 # unfortunately IGuest is suppressed, thus WebServices knows not about it
328 # this is an example how to handle local only functionality
329 if ctx['remote'] and cmd == 'stats2':
330 print 'Trying to use local only functionality, ignored'
331 return
332 console=session.console
333 ops={'pause': lambda: console.pause(),
334 'resume': lambda: console.resume(),
335 'powerdown': lambda: console.powerDown(),
336 'powerbutton': lambda: console.powerButton(),
337 'stats': lambda: guestStats(ctx, mach),
338 'guest': lambda: guestExec(ctx, mach, console, args),
339 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
340 'save': lambda: console.saveState().waitForCompletion(-1)
341 }
342 try:
343 ops[cmd]()
344 except Exception, e:
345 print 'failed: ',e
346 if g_verbose:
347 traceback.print_exc()
348
349 session.close()
350
351# can cache known machines, if needed
352def machById(ctx,id):
353 mach = None
354 for m in getMachines(ctx):
355 if m.name == id:
356 mach = m
357 break
358 mid = str(m.id)
359 if mid[0] == '{':
360 mid = mid[1:-1]
361 if mid == id:
362 mach = m
363 break
364 return mach
365
366def argsToMach(ctx,args):
367 if len(args) < 2:
368 print "usage: %s [vmname|uuid]" %(args[0])
369 return None
370 id = args[1]
371 m = machById(ctx, id)
372 if m == None:
373 print "Machine '%s' is unknown, use list command to find available machines" %(id)
374 return m
375
376def helpCmd(ctx, args):
377 if len(args) == 1:
378 print "Help page:"
379 names = commands.keys()
380 names.sort()
381 for i in names:
382 print " ",i,":", commands[i][0]
383 else:
384 c = commands.get(args[1], None)
385 if c == None:
386 print "Command '%s' not known" %(args[1])
387 else:
388 print " ",args[1],":", c[0]
389 return 0
390
391def listCmd(ctx, args):
392 for m in getMachines(ctx):
393 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
394 return 0
395
396def getControllerType(type):
397 if type == 0:
398 return "Null"
399 elif type == 1:
400 return "LsiLogic"
401 elif type == 2:
402 return "BusLogic"
403 elif type == 3:
404 return "IntelAhci"
405 elif type == 4:
406 return "PIIX3"
407 elif type == 5:
408 return "PIIX4"
409 elif type == 6:
410 return "ICH6"
411 else:
412 return "Unknown"
413
414def infoCmd(ctx,args):
415 import time
416 if (len(args) < 2):
417 print "usage: info [vmname|uuid]"
418 return 0
419 mach = argsToMach(ctx,args)
420 if mach == None:
421 return 0
422 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
423 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
424 print " Name [name]: " + mach.name
425 print " ID [n/a]: " + mach.id
426 print " OS Type [n/a]: " + os.description
427 print
428 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
429 print " RAM [memorySize]: %dM" %(mach.memorySize)
430 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
431 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
432 print
433 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
434 print " Machine status [n/a]: %d" % (mach.sessionState)
435 print
436 bios = mach.BIOSSettings
437 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
438 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
439 print " PAE [PAEEnabled]: %s" %(asState(mach.PAEEnabled))
440 print " Hardware virtualization [HWVirtExEnabled]: " + asState(mach.HWVirtExEnabled)
441 print " VPID support [HWVirtExVPIDEnabled]: " + asState(mach.HWVirtExVPIDEnabled)
442 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
443 print " Nested paging [HWVirtExNestedPagingEnabled]: " + asState(mach.HWVirtExNestedPagingEnabled)
444 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
445 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
446
447 controllers = ctx['global'].getArray(mach, 'storageControllers')
448 if controllers:
449 print
450 print " Controllers:"
451 for controller in controllers:
452 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
453
454 disks = ctx['global'].getArray(mach, 'hardDiskAttachments')
455 if disks:
456 print
457 print " Disks:"
458 for disk in disks:
459 print " Controller: %s port: %d device: %d:" % (disk.controller, disk.port, disk.device)
460 hd = disk.hardDisk
461 print " id: " + hd.id
462 print " location: " + hd.location
463 print " name: " + hd.name
464 print " format: " + hd.format
465 print
466 return 0
467
468def startCmd(ctx, args):
469 mach = argsToMach(ctx,args)
470 if mach == None:
471 return 0
472 if len(args) > 2:
473 type = args[2]
474 else:
475 type = "gui"
476 startVm(ctx, mach, type)
477 return 0
478
479def createCmd(ctx, args):
480 if (len(args) < 3 or len(args) > 4):
481 print "usage: create name ostype <basefolder>"
482 return 0
483 name = args[1]
484 oskind = args[2]
485 if len(args) == 4:
486 base = args[3]
487 else:
488 base = ''
489 try:
490 ctx['vb'].getGuestOSType(oskind)
491 except Exception, e:
492 print 'Unknown OS type:',oskind
493 return 0
494 createVm(ctx, name, oskind, base)
495 return 0
496
497def removeCmd(ctx, args):
498 mach = argsToMach(ctx,args)
499 if mach == None:
500 return 0
501 removeVm(ctx, mach)
502 return 0
503
504def pauseCmd(ctx, args):
505 mach = argsToMach(ctx,args)
506 if mach == None:
507 return 0
508 cmdExistingVm(ctx, mach, 'pause', '')
509 return 0
510
511def powerdownCmd(ctx, args):
512 mach = argsToMach(ctx,args)
513 if mach == None:
514 return 0
515 cmdExistingVm(ctx, mach, 'powerdown', '')
516 return 0
517
518def powerbuttonCmd(ctx, args):
519 mach = argsToMach(ctx,args)
520 if mach == None:
521 return 0
522 cmdExistingVm(ctx, mach, 'powerbutton', '')
523 return 0
524
525def resumeCmd(ctx, args):
526 mach = argsToMach(ctx,args)
527 if mach == None:
528 return 0
529 cmdExistingVm(ctx, mach, 'resume', '')
530 return 0
531
532def saveCmd(ctx, args):
533 mach = argsToMach(ctx,args)
534 if mach == None:
535 return 0
536 cmdExistingVm(ctx, mach, 'save', '')
537 return 0
538
539def statsCmd(ctx, args):
540 mach = argsToMach(ctx,args)
541 if mach == None:
542 return 0
543 cmdExistingVm(ctx, mach, 'stats', '')
544 return 0
545
546def guestCmd(ctx, args):
547 if (len(args) < 3):
548 print "usage: guest name commands"
549 return 0
550 mach = argsToMach(ctx,args)
551 if mach == None:
552 return 0
553 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
554 return 0
555
556def setvarCmd(ctx, args):
557 if (len(args) < 4):
558 print "usage: setvar [vmname|uuid] expr value"
559 return 0
560 mach = argsToMach(ctx,args)
561 if mach == None:
562 return 0
563 session = ctx['global'].openMachineSession(mach.id)
564 mach = session.machine
565 expr = 'mach.'+args[2]+' = '+args[3]
566 print "Executing",expr
567 try:
568 exec expr
569 except Exception, e:
570 print 'failed: ',e
571 if g_verbose:
572 traceback.print_exc()
573 mach.saveSettings()
574 session.close()
575 return 0
576
577def quitCmd(ctx, args):
578 return 1
579
580def aliasCmd(ctx, args):
581 if (len(args) == 3):
582 aliases[args[1]] = args[2]
583 return 0
584
585 for (k,v) in aliases.items():
586 print "'%s' is an alias for '%s'" %(k,v)
587 return 0
588
589def verboseCmd(ctx, args):
590 global g_verbose
591 g_verbose = not g_verbose
592 return 0
593
594def hostCmd(ctx, args):
595 host = ctx['vb'].host
596 cnt = host.processorCount
597 print "Processor count:",cnt
598 for i in range(0,cnt):
599 print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
600
601 if ctx['perf']:
602 for metric in ctx['perf'].query(["*"], [host]):
603 print metric['name'], metric['values_as_string']
604
605 return 0
606
607def monitorGuestCmd(ctx, args):
608 if (len(args) < 2):
609 print "usage: monitorGuest name (duration)"
610 return 0
611 mach = argsToMach(ctx,args)
612 if mach == None:
613 return 0
614 dur = 5
615 if len(args) > 2:
616 dur = float(args[2])
617 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
618 return 0
619
620def monitorVboxCmd(ctx, args):
621 if (len(args) > 2):
622 print "usage: monitorVbox (duration)"
623 return 0
624 dur = 5
625 if len(args) > 1:
626 dur = float(args[1])
627 monitorVbox(ctx, dur)
628 return 0
629
630def getAdapterType(ctx, type):
631 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
632 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
633 return "pcnet"
634 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
635 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
636 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
637 return "e1000"
638 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
639 return None
640 else:
641 raise Exception("Unknown adapter type: "+type)
642
643
644def portForwardCmd(ctx, args):
645 if (len(args) != 5):
646 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
647 return 0
648 mach = argsToMach(ctx,args)
649 if mach == None:
650 return 0
651 adapterNum = int(args[2])
652 hostPort = int(args[3])
653 guestPort = int(args[4])
654 proto = "TCP"
655 session = ctx['global'].openMachineSession(mach.id)
656 mach = session.machine
657
658 adapter = mach.getNetworkAdapter(adapterNum)
659 adapterType = getAdapterType(ctx, adapter.adapterType)
660
661 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
662 config = "VBoxInternal/Devices/" + adapterType + "/"
663 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
664
665 mach.setExtraData(config + "/Protocol", proto)
666 mach.setExtraData(config + "/HostPort", str(hostPort))
667 mach.setExtraData(config + "/GuestPort", str(guestPort))
668
669 mach.saveSettings()
670 session.close()
671
672 return 0
673
674
675def showLogCmd(ctx, args):
676 if (len(args) < 2):
677 print "usage: showLog <vm> <num>"
678 return 0
679 mach = argsToMach(ctx,args)
680 if mach == None:
681 return 0
682
683 log = "VBox.log"
684 if (len(args) > 2):
685 log += "."+args[2]
686 fileName = os.path.join(mach.logFolder, log)
687
688 try:
689 lf = open(fileName, 'r')
690 except IOError,e:
691 print "cannot open: ",e
692 return 0
693
694 for line in lf:
695 print line,
696 lf.close()
697
698 return 0
699
700def evalCmd(ctx, args):
701 expr = ' '.join(args[1:])
702 try:
703 exec expr
704 except Exception, e:
705 print 'failed: ',e
706 if g_verbose:
707 traceback.print_exc()
708 return 0
709
710def reloadExtCmd(ctx, args):
711 # maybe will want more args smartness
712 checkUserExtensions(ctx, commands, ctx['vb'].homeFolder)
713 autoCompletion(commands, ctx)
714 return 0
715
716
717def runScriptCmd(ctx, args):
718 if (len(args) != 2):
719 print "usage: runScript <script>"
720 return 0
721 try:
722 lf = open(args[1], 'r')
723 except IOError,e:
724 print "cannot open:",args[1], ":",e
725 return 0
726
727 try:
728 for line in lf:
729 done = runCommand(ctx, line)
730 if done != 0: break
731 except Exception,e:
732 print "error:",e
733 if g_verbose:
734 traceback.print_exc()
735 lf.close()
736 return 0
737
738
739aliases = {'s':'start',
740 'i':'info',
741 'l':'list',
742 'h':'help',
743 'a':'alias',
744 'q':'quit', 'exit':'quit',
745 'v':'verbose'}
746
747commands = {'help':['Prints help information', helpCmd, 0],
748 'start':['Start virtual machine by name or uuid', startCmd, 0],
749 'create':['Create virtual machine', createCmd, 0],
750 'remove':['Remove virtual machine', removeCmd, 0],
751 'pause':['Pause virtual machine', pauseCmd, 0],
752 'resume':['Resume virtual machine', resumeCmd, 0],
753 'save':['Save execution state of virtual machine', saveCmd, 0],
754 'stats':['Stats for virtual machine', statsCmd, 0],
755 'powerdown':['Power down virtual machine', powerdownCmd, 0],
756 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
757 'list':['Shows known virtual machines', listCmd, 0],
758 'info':['Shows info on machine', infoCmd, 0],
759 'alias':['Control aliases', aliasCmd, 0],
760 'verbose':['Toggle verbosity', verboseCmd, 0],
761 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
762 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
763 'quit':['Exits', quitCmd, 0],
764 'host':['Show host information', hostCmd, 0],
765 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
766 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
767 'monitorVbox':['Monitor what happens with Virtual Box for some time: monitorVbox 10', monitorVboxCmd, 0],
768 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
769 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
770 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
771 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
772 }
773
774def runCommand(ctx, cmd):
775 if len(cmd) == 0: return 0
776 args = split_no_quotes(cmd)
777 if len(args) == 0: return 0
778 c = args[0]
779 if aliases.get(c, None) != None:
780 c = aliases[c]
781 ci = commands.get(c,None)
782 if ci == None:
783 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
784 return 0
785 return ci[1](ctx, args)
786
787#
788# To write your own custom commands to vboxshell, create
789# file ~/.VirtualBox/shellext.py with content like
790#
791# def runTestCmd(ctx, args):
792# print "Testy test", ctx['vb']
793# return 0
794#
795# commands = {
796# 'test': ['Test help', runTestCmd]
797# }
798# and issue reloadExt shell command.
799# This file also will be read automatically on startup.
800#
801def checkUserExtensions(ctx, cmds, folder):
802 name = os.path.join(str(folder), "shellext.py")
803 if not os.path.isfile(name):
804 return
805 d = {}
806 try:
807 execfile(name, d, d)
808 for (k,v) in d['commands'].items():
809 if g_verbose:
810 print "customize: adding \"%s\" - %s" %(k, v[0])
811 cmds[k] = [v[0], v[1], 1]
812 except:
813 print "Error loading user extensions:"
814 traceback.print_exc()
815
816def interpret(ctx):
817 vbox = ctx['vb']
818 print "Running VirtualBox version %s" %(vbox.version)
819 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
820
821 checkUserExtensions(ctx, commands, vbox.homeFolder)
822
823 autoCompletion(commands, ctx)
824
825 # to allow to print actual host information, we collect info for
826 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
827 if ctx['perf']:
828 try:
829 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
830 except:
831 pass
832
833 while True:
834 try:
835 cmd = raw_input("vbox> ")
836 done = runCommand(ctx, cmd)
837 if done != 0: break
838 except KeyboardInterrupt:
839 print '====== You can type quit or q to leave'
840 break
841 except EOFError:
842 break;
843 except Exception,e:
844 print e
845 if g_verbose:
846 traceback.print_exc()
847
848 try:
849 # There is no need to disable metric collection. This is just an example.
850 if ct['perf']:
851 ctx['perf'].disable(['*'], [vbox.host])
852 except:
853 pass
854
855def main(argv):
856 style = None
857 autopath = False
858 argv.pop(0)
859 while len(argv) > 0:
860 if argv[0] == "-w":
861 style = "WEBSERVICE"
862 if argv[0] == "-a":
863 autopath = True
864 argv.pop(0)
865
866 if autopath:
867 cwd = os.getcwd()
868 vpp = os.environ.get("VBOX_PROGRAM_PATH")
869 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
870 vpp = cwd
871 print "Autodetected VBOX_PROGRAM_PATH as",vpp
872 os.environ["VBOX_PROGRAM_PATH"] = cwd
873 sys.path.append(os.path.join(vpp, "sdk", "installer"))
874
875 from vboxapi import VirtualBoxManager
876 g_virtualBoxManager = VirtualBoxManager(style, None)
877 ctx = {'global':g_virtualBoxManager,
878 'mgr':g_virtualBoxManager.mgr,
879 'vb':g_virtualBoxManager.vbox,
880 'ifaces':g_virtualBoxManager.constants,
881 'remote':g_virtualBoxManager.remote,
882 'type':g_virtualBoxManager.type
883 }
884 interpret(ctx)
885 g_virtualBoxManager.deinit()
886 del g_virtualBoxManager
887
888if __name__ == '__main__':
889 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