VirtualBox

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

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

Python shell: allow executing existing commands from extensions

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