VirtualBox

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

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

Python shell: minor improvments

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 24.9 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 infoCmd(ctx,args):
397 import time
398 if (len(args) < 2):
399 print "usage: info [vmname|uuid]"
400 return 0
401 mach = argsToMach(ctx,args)
402 if mach == None:
403 return 0
404 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
405 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
406 print " Name [name]: ",mach.name
407 print " ID [n/a]: ",mach.id
408 print " OS Type [n/a]: ",os.description
409 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
410 print " RAM [memorySize]: %dM" %(mach.memorySize)
411 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
412 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
413 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
414 print " Machine status [n/a]: " ,mach.sessionState
415 bios = mach.BIOSSettings
416 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
417 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
418 print " PAE [PAEEnabled]: %s" %(asState(mach.PAEEnabled))
419 print " Hardware virtualization [HWVirtExEnabled]: ",asState(mach.HWVirtExEnabled)
420 print " VPID support [HWVirtExVPIDEnabled]: ",asState(mach.HWVirtExVPIDEnabled)
421 print " Hardware 3d acceleration[accelerate3DEnabled]: ",asState(mach.accelerate3DEnabled)
422 print " Nested paging [HWVirtExNestedPagingEnabled]: ",asState(mach.HWVirtExNestedPagingEnabled)
423 print " Last changed [n/a]: ",time.asctime(time.localtime(mach.lastStateChange/1000))
424
425 return 0
426
427def startCmd(ctx, args):
428 mach = argsToMach(ctx,args)
429 if mach == None:
430 return 0
431 if len(args) > 2:
432 type = args[2]
433 else:
434 type = "gui"
435 startVm(ctx, mach, type)
436 return 0
437
438def createCmd(ctx, args):
439 if (len(args) < 3 or len(args) > 4):
440 print "usage: create name ostype <basefolder>"
441 return 0
442 name = args[1]
443 oskind = args[2]
444 if len(args) == 4:
445 base = args[3]
446 else:
447 base = ''
448 try:
449 ctx['vb'].getGuestOSType(oskind)
450 except Exception, e:
451 print 'Unknown OS type:',oskind
452 return 0
453 createVm(ctx, name, oskind, base)
454 return 0
455
456def removeCmd(ctx, args):
457 mach = argsToMach(ctx,args)
458 if mach == None:
459 return 0
460 removeVm(ctx, mach)
461 return 0
462
463def pauseCmd(ctx, args):
464 mach = argsToMach(ctx,args)
465 if mach == None:
466 return 0
467 cmdExistingVm(ctx, mach, 'pause', '')
468 return 0
469
470def powerdownCmd(ctx, args):
471 mach = argsToMach(ctx,args)
472 if mach == None:
473 return 0
474 cmdExistingVm(ctx, mach, 'powerdown', '')
475 return 0
476
477def powerbuttonCmd(ctx, args):
478 mach = argsToMach(ctx,args)
479 if mach == None:
480 return 0
481 cmdExistingVm(ctx, mach, 'powerbutton', '')
482 return 0
483
484def resumeCmd(ctx, args):
485 mach = argsToMach(ctx,args)
486 if mach == None:
487 return 0
488 cmdExistingVm(ctx, mach, 'resume', '')
489 return 0
490
491def saveCmd(ctx, args):
492 mach = argsToMach(ctx,args)
493 if mach == None:
494 return 0
495 cmdExistingVm(ctx, mach, 'save', '')
496 return 0
497
498def statsCmd(ctx, args):
499 mach = argsToMach(ctx,args)
500 if mach == None:
501 return 0
502 cmdExistingVm(ctx, mach, 'stats', '')
503 return 0
504
505def guestCmd(ctx, args):
506 if (len(args) < 3):
507 print "usage: guest name commands"
508 return 0
509 mach = argsToMach(ctx,args)
510 if mach == None:
511 return 0
512 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
513 return 0
514
515def setvarCmd(ctx, args):
516 if (len(args) < 4):
517 print "usage: setvar [vmname|uuid] expr value"
518 return 0
519 mach = argsToMach(ctx,args)
520 if mach == None:
521 return 0
522 session = ctx['global'].openMachineSession(mach.id)
523 mach = session.machine
524 expr = 'mach.'+args[2]+' = '+args[3]
525 print "Executing",expr
526 try:
527 exec expr
528 except Exception, e:
529 print 'failed: ',e
530 if g_verbose:
531 traceback.print_exc()
532 mach.saveSettings()
533 session.close()
534 return 0
535
536def quitCmd(ctx, args):
537 return 1
538
539def aliasCmd(ctx, args):
540 if (len(args) == 3):
541 aliases[args[1]] = args[2]
542 return 0
543
544 for (k,v) in aliases.items():
545 print "'%s' is an alias for '%s'" %(k,v)
546 return 0
547
548def verboseCmd(ctx, args):
549 global g_verbose
550 g_verbose = not g_verbose
551 return 0
552
553def hostCmd(ctx, args):
554 host = ctx['vb'].host
555 cnt = host.processorCount
556 print "Processor count:",cnt
557 for i in range(0,cnt):
558 print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
559
560 if ctx['perf']:
561 for metric in ctx['perf'].query(["*"], [host]):
562 print metric['name'], metric['values_as_string']
563
564 return 0
565
566def monitorGuestCmd(ctx, args):
567 if (len(args) < 2):
568 print "usage: monitorGuest name (duration)"
569 return 0
570 mach = argsToMach(ctx,args)
571 if mach == None:
572 return 0
573 dur = 5
574 if len(args) > 2:
575 dur = float(args[2])
576 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
577 return 0
578
579def monitorVboxCmd(ctx, args):
580 if (len(args) > 2):
581 print "usage: monitorVbox (duration)"
582 return 0
583 dur = 5
584 if len(args) > 1:
585 dur = float(args[1])
586 monitorVbox(ctx, dur)
587 return 0
588
589def getAdapterType(ctx, type):
590 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
591 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
592 return "pcnet"
593 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
594 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
595 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
596 return "e1000"
597 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
598 return None
599 else:
600 raise Exception("Unknown adapter type: "+type)
601
602
603def portForwardCmd(ctx, args):
604 if (len(args) != 5):
605 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
606 return 0
607 mach = argsToMach(ctx,args)
608 if mach == None:
609 return 0
610 adapterNum = int(args[2])
611 hostPort = int(args[3])
612 guestPort = int(args[4])
613 proto = "TCP"
614 session = ctx['global'].openMachineSession(mach.id)
615 mach = session.machine
616
617 adapter = mach.getNetworkAdapter(adapterNum)
618 adapterType = getAdapterType(ctx, adapter.adapterType)
619
620 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
621 config = "VBoxInternal/Devices/" + adapterType + "/"
622 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
623
624 mach.setExtraData(config + "/Protocol", proto)
625 mach.setExtraData(config + "/HostPort", str(hostPort))
626 mach.setExtraData(config + "/GuestPort", str(guestPort))
627
628 mach.saveSettings()
629 session.close()
630
631 return 0
632
633
634def showLogCmd(ctx, args):
635 if (len(args) < 2):
636 print "usage: showLog <vm> <num>"
637 return 0
638 mach = argsToMach(ctx,args)
639 if mach == None:
640 return 0
641
642 log = "VBox.log"
643 if (len(args) > 2):
644 log += "."+args[2]
645 fileName = os.path.join(mach.logFolder, log)
646
647 try:
648 lf = open(fileName, 'r')
649 except IOError,e:
650 print "cannot open: ",e
651 return 0
652
653 for line in lf:
654 print line,
655 lf.close()
656
657 return 0
658
659def evalCmd(ctx, args):
660 expr = ' '.join(args[1:])
661 try:
662 exec expr
663 except Exception, e:
664 print 'failed: ',e
665 if g_verbose:
666 traceback.print_exc()
667 return 0
668
669def reloadExtCmd(ctx, args):
670 # maybe will want more args smartness
671 checkUserExtensions(ctx, commands, ctx['vb'].homeFolder)
672 autoCompletion(commands, ctx)
673 return 0
674
675aliases = {'s':'start',
676 'i':'info',
677 'l':'list',
678 'h':'help',
679 'a':'alias',
680 'q':'quit', 'exit':'quit',
681 'v':'verbose'}
682
683commands = {'help':['Prints help information', helpCmd, 0],
684 'start':['Start virtual machine by name or uuid', startCmd, 0],
685 'create':['Create virtual machine', createCmd, 0],
686 'remove':['Remove virtual machine', removeCmd, 0],
687 'pause':['Pause virtual machine', pauseCmd, 0],
688 'resume':['Resume virtual machine', resumeCmd, 0],
689 'save':['Save execution state of virtual machine', saveCmd, 0],
690 'stats':['Stats for virtual machine', statsCmd, 0],
691 'powerdown':['Power down virtual machine', powerdownCmd, 0],
692 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
693 'list':['Shows known virtual machines', listCmd, 0],
694 'info':['Shows info on machine', infoCmd, 0],
695 'alias':['Control aliases', aliasCmd, 0],
696 'verbose':['Toggle verbosity', verboseCmd, 0],
697 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
698 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
699 'quit':['Exits', quitCmd, 0],
700 'host':['Show host information', hostCmd, 0],
701 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
702 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
703 'monitorVbox':['Monitor what happens with Virtual Box for some time: monitorVbox 10', monitorVboxCmd, 0],
704 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
705 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
706 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
707 }
708
709def runCommand(ctx, cmd):
710 if len(cmd) == 0: return 0
711 args = split_no_quotes(cmd)
712 if len(args) == 0: return 0
713 c = args[0]
714 if aliases.get(c, None) != None:
715 c = aliases[c]
716 ci = commands.get(c,None)
717 if ci == None:
718 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
719 return 0
720 return ci[1](ctx, args)
721
722#
723# To write your own custom commands to vboxshell, create
724# file ~/.VirtualBox/shellext.py with content like
725#
726# def runTestCmd(ctx, args):
727# print "Testy test", ctx['vb']
728# return 0
729#
730# commands = {
731# 'test': ['Test help', runTestCmd]
732# }
733# and issue reloadExt shell command.
734# This file also will be read automatically on startup.
735#
736def checkUserExtensions(ctx, cmds, folder):
737 name = os.path.join(folder, "shellext.py")
738 if not os.path.isfile(name):
739 return
740 d = {}
741 try:
742 execfile(name, d, d)
743 for (k,v) in d['commands'].items():
744 if g_verbose:
745 print "customize: adding \"%s\" - %s" %(k, v[0])
746 cmds[k] = [v[0], v[1], 1]
747 except:
748 print "Error loading user extensions:"
749 traceback.print_exc()
750
751def interpret(ctx):
752 vbox = ctx['vb']
753 print "Running VirtualBox version %s" %(vbox.version)
754 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
755
756 checkUserExtensions(ctx, commands, vbox.homeFolder)
757
758 autoCompletion(commands, ctx)
759
760 # to allow to print actual host information, we collect info for
761 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
762 if ctx['perf']:
763 try:
764 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
765 except:
766 pass
767
768 while True:
769 try:
770 cmd = raw_input("vbox> ")
771 done = runCommand(ctx, cmd)
772 if done != 0: break
773 except KeyboardInterrupt:
774 print '====== You can type quit or q to leave'
775 break
776 except EOFError:
777 break;
778 except Exception,e:
779 print e
780 if g_verbose:
781 traceback.print_exc()
782
783 try:
784 # There is no need to disable metric collection. This is just an example.
785 if ct['perf']:
786 ctx['perf'].disable(['*'], [vbox.host])
787 except:
788 pass
789
790
791from vboxapi import VirtualBoxManager
792
793def main(argv):
794 style = None
795 if len(argv) > 1:
796 if argv[1] == "-w":
797 style = "WEBSERVICE"
798
799 g_virtualBoxManager = VirtualBoxManager(style, None)
800 ctx = {'global':g_virtualBoxManager,
801 'mgr':g_virtualBoxManager.mgr,
802 'vb':g_virtualBoxManager.vbox,
803 'ifaces':g_virtualBoxManager.constants,
804 'remote':g_virtualBoxManager.remote,
805 'type':g_virtualBoxManager.type
806 }
807 interpret(ctx)
808 g_virtualBoxManager.deinit()
809 del g_virtualBoxManager
810
811if __name__ == '__main__':
812 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