VirtualBox

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

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

Python shell: use shlex

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 24.5 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.virtualbox.org. 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 s.split()
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 import time
280 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
281 console.registerCallback(cb)
282 if dur == -1:
283 # not infinity, but close enough
284 dur = 100000
285 try:
286 end = time.time() + dur
287 while time.time() < end:
288 ctx['global'].waitForEvents(500)
289 # We need to catch all exceptions here, otherwise callback will never be unregistered
290 except:
291 pass
292 console.unregisterCallback(cb)
293
294
295def monitorVbox(ctx, dur):
296 import time
297 vbox = ctx['vb']
298 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, vbox)
299 vbox.registerCallback(cb)
300 if dur == -1:
301 # not infinity, but close enough
302 dur = 100000
303 try:
304 end = time.time() + dur
305 while time.time() < end:
306 ctx['global'].waitForEvents(500)
307 # We need to catch all exceptions here, otherwise callback will never be unregistered
308 except:
309 if g_verbose:
310 traceback.print_exc()
311 vbox.unregisterCallback(cb)
312
313def cmdExistingVm(ctx,mach,cmd,args):
314 mgr=ctx['mgr']
315 vb=ctx['vb']
316 session = mgr.getSessionObject(vb)
317 uuid = mach.id
318 try:
319 progress = vb.openExistingSession(session, uuid)
320 except Exception,e:
321 print "Session to '%s' not open: %s" %(mach.name,e)
322 if g_verbose:
323 traceback.print_exc()
324 return
325 if session.state != ctx['ifaces'].SessionState_Open:
326 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
327 return
328 # unfortunately IGuest is suppressed, thus WebServices knows not about it
329 # this is an example how to handle local only functionality
330 if ctx['remote'] and cmd == 'stats2':
331 print 'Trying to use local only functionality, ignored'
332 return
333 console=session.console
334 ops={'pause' : lambda: console.pause(),
335 'resume': lambda: console.resume(),
336 'powerdown': lambda: console.powerDown(),
337 'powerbutton': lambda: console.powerButton(),
338 'stats': lambda: guestStats(ctx, mach),
339 'guest': lambda: guestExec(ctx, mach, console, args),
340 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args)
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 statsCmd(ctx, args):
492 mach = argsToMach(ctx,args)
493 if mach == None:
494 return 0
495 cmdExistingVm(ctx, mach, 'stats', '')
496 return 0
497
498def guestCmd(ctx, args):
499 if (len(args) < 3):
500 print "usage: guest name commands"
501 return 0
502 mach = argsToMach(ctx,args)
503 if mach == None:
504 return 0
505 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
506 return 0
507
508def setvarCmd(ctx, args):
509 if (len(args) < 4):
510 print "usage: setvar [vmname|uuid] expr value"
511 return 0
512 mach = argsToMach(ctx,args)
513 if mach == None:
514 return 0
515 session = ctx['global'].openMachineSession(mach.id)
516 mach = session.machine
517 expr = 'mach.'+args[2]+' = '+args[3]
518 print "Executing",expr
519 try:
520 exec expr
521 except Exception, e:
522 print 'failed: ',e
523 if g_verbose:
524 traceback.print_exc()
525 mach.saveSettings()
526 session.close()
527 return 0
528
529def quitCmd(ctx, args):
530 return 1
531
532def aliasesCmd(ctx, args):
533 for (k,v) in aliases.items():
534 print "'%s' is an alias for '%s'" %(k,v)
535 return 0
536
537def verboseCmd(ctx, args):
538 global g_verbose
539 g_verbose = not g_verbose
540 return 0
541
542def hostCmd(ctx, args):
543 host = ctx['vb'].host
544 cnt = host.processorCount
545 print "Processor count:",cnt
546 for i in range(0,cnt):
547 print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
548
549 if ctx['perf']:
550 for metric in ctx['perf'].query(["*"], [host]):
551 print metric['name'], metric['values_as_string']
552
553 return 0
554
555
556def monitorGuestCmd(ctx, args):
557 if (len(args) < 2):
558 print "usage: monitorGuest name (duration)"
559 return 0
560 mach = argsToMach(ctx,args)
561 if mach == None:
562 return 0
563 dur = 5
564 if len(args) > 2:
565 dur = float(args[2])
566 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
567 return 0
568
569def monitorVboxCmd(ctx, args):
570 if (len(args) > 2):
571 print "usage: monitorVbox (duration)"
572 return 0
573 dur = 5
574 if len(args) > 1:
575 dur = float(args[1])
576 monitorVbox(ctx, dur)
577 return 0
578
579def getAdapterType(ctx, type):
580 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
581 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
582 return "pcnet"
583 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
584 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
585 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
586 return "e1000"
587 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
588 return None
589 else:
590 raise Exception("Unknown adapter type: "+type)
591
592
593def portForwardCmd(ctx, args):
594 if (len(args) != 5):
595 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
596 return 0
597 mach = argsToMach(ctx,args)
598 if mach == None:
599 return 0
600 adapterNum = int(args[2])
601 hostPort = int(args[3])
602 guestPort = int(args[4])
603 proto = "TCP"
604 session = ctx['global'].openMachineSession(mach.id)
605 mach = session.machine
606
607 adapter = mach.getNetworkAdapter(adapterNum)
608 adapterType = getAdapterType(ctx, adapter.adapterType)
609
610 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
611 config = "VBoxInternal/Devices/" + adapterType + "/"
612 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
613
614 mach.setExtraData(config + "/Protocol", proto)
615 mach.setExtraData(config + "/HostPort", str(hostPort))
616 mach.setExtraData(config + "/GuestPort", str(guestPort))
617
618 mach.saveSettings()
619 session.close()
620
621 return 0
622
623
624def showLogCmd(ctx, args):
625 if (len(args) < 2):
626 print "usage: showLog <vm> <num>"
627 return 0
628 mach = argsToMach(ctx,args)
629 if mach == None:
630 return 0
631
632 log = "VBox.log"
633 if (len(args) > 2):
634 log += "."+args[2]
635 fileName = os.path.join(mach.logFolder, log)
636
637 try:
638 lf = open(fileName, 'r')
639 except IOError,e:
640 print "cannot open: ",e
641 return 0
642
643 for line in lf:
644 print line,
645 lf.close()
646
647 return 0
648
649def evalCmd(ctx, args):
650 expr = ' '.join(args[1:])
651 try:
652 exec expr
653 except Exception, e:
654 print 'failed: ',e
655 if g_verbose:
656 traceback.print_exc()
657 return 0
658
659def reloadExtCmd(ctx, args):
660 # maybe will want more args smartness
661 checkUserExtensions(ctx, commands, ctx['vb'].homeFolder)
662 autoCompletion(commands, ctx)
663 return 0
664
665aliases = {'s':'start',
666 'i':'info',
667 'l':'list',
668 'h':'help',
669 'a':'aliases',
670 'q':'quit', 'exit':'quit',
671 'v':'verbose'}
672
673commands = {'help':['Prints help information', helpCmd, 0],
674 'start':['Start virtual machine by name or uuid', startCmd, 0],
675 'create':['Create virtual machine', createCmd, 0],
676 'remove':['Remove virtual machine', removeCmd, 0],
677 'pause':['Pause virtual machine', pauseCmd, 0],
678 'resume':['Resume virtual machine', resumeCmd, 0],
679 'stats':['Stats for virtual machine', statsCmd, 0],
680 'powerdown':['Power down virtual machine', powerdownCmd, 0],
681 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
682 'list':['Shows known virtual machines', listCmd, 0],
683 'info':['Shows info on machine', infoCmd, 0],
684 'aliases':['Shows aliases', aliasesCmd, 0],
685 'verbose':['Toggle verbosity', verboseCmd, 0],
686 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
687 'eval':['Evaluate arbitrary Python construction: eval for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"', evalCmd, 0],
688 'quit':['Exits', quitCmd, 0],
689 'host':['Show host information', hostCmd, 0],
690 'guest':['Execute command for guest: guest Win32 console.mouse.putMouseEvent(20, 20, 0, 0)', guestCmd, 0],
691 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
692 'monitorVbox':['Monitor what happens with Virtual Box for some time: monitorVbox 10', monitorVboxCmd, 0],
693 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
694 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
695 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
696 }
697
698def runCommand(ctx, cmd):
699 if len(cmd) == 0: return 0
700 args = split_no_quotes(cmd)
701 if len(args) == 0: return 0
702 c = args[0]
703 if aliases.get(c, None) != None:
704 c = aliases[c]
705 ci = commands.get(c,None)
706 if ci == None:
707 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
708 return 0
709 return ci[1](ctx, args)
710
711#
712# To write your own custom commands to vboxshell, create
713# file ~/.VirtualBox/shellext.py with content like
714#
715# def runTestCmd(ctx, args):
716# print "Testy test", ctx['vb']
717# return 0
718#
719# commands = {
720# 'test': ['Test help', runTestCmd]
721# }
722# and issue reloadExt shell command.
723# This file also will be read automatically on startup.
724#
725def checkUserExtensions(ctx, cmds, folder):
726 name = os.path.join(folder, "shellext.py")
727 if not os.path.isfile(name):
728 return
729 d = {}
730 try:
731 execfile(name, d, d)
732 for (k,v) in d['commands'].items():
733 if g_verbose:
734 print "customize: adding \"%s\" - %s" %(k, v[0])
735 cmds[k] = [v[0], v[1], 1]
736 except:
737 print "Error loading user extensions:"
738 traceback.print_exc()
739
740def interpret(ctx):
741 vbox = ctx['vb']
742 print "Running VirtualBox version %s" %(vbox.version)
743 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
744
745 checkUserExtensions(ctx, commands, vbox.homeFolder)
746
747 autoCompletion(commands, ctx)
748
749 # to allow to print actual host information, we collect info for
750 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
751 if ctx['perf']:
752 try:
753 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
754 except:
755 pass
756
757 while True:
758 try:
759 cmd = raw_input("vbox> ")
760 done = runCommand(ctx, cmd)
761 if done != 0: break
762 except KeyboardInterrupt:
763 print '====== You can type quit or q to leave'
764 break
765 except EOFError:
766 break;
767 except Exception,e:
768 print e
769 if g_verbose:
770 traceback.print_exc()
771
772 try:
773 # There is no need to disable metric collection. This is just an example.
774 if ct['perf']:
775 ctx['perf'].disable(['*'], [vbox.host])
776 except:
777 pass
778
779
780from vboxapi import VirtualBoxManager
781
782def main(argv):
783 style = None
784 if len(argv) > 1:
785 if argv[1] == "-w":
786 style = "WEBSERVICE"
787
788 g_virtualBoxManager = VirtualBoxManager(style, None)
789 ctx = {'global':g_virtualBoxManager,
790 'mgr':g_virtualBoxManager.mgr,
791 'vb':g_virtualBoxManager.vbox,
792 'ifaces':g_virtualBoxManager.constants,
793 'remote':g_virtualBoxManager.remote,
794 'type':g_virtualBoxManager.type
795 }
796 interpret(ctx)
797 g_virtualBoxManager.deinit()
798 del g_virtualBoxManager
799
800if __name__ == '__main__':
801 main(sys.argv)
Note: See TracBrowser for help on using the repository browser.

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