VirtualBox

source: vbox/trunk/src/libs/xpcom18a4/python/sample/vboxshell.py@ 11848

Last change on this file since 11848 was 11848, checked in by vboxsync, 17 years ago

docs, other sdk cleanups

  • Property svn:eol-style set to native
File size: 10.8 KB
Line 
1#!/usr/bin/python
2#
3#################################################################################
4# This program is a simple interactive shell for VirtualBox. You can query #
5# information and issue commands from a simple command line. #
6# #
7# It also provides you with examples on how to use VirtualBox's Python API. #
8# This shell is even somewhat documented and supports TAB-completion and #
9# history if you have Python readline installed. #
10# #
11# Enjoy. #
12#################################################################################
13#
14# To make it work, the following variables have to be set.
15# Please note the trailing slash in VBOX_PROGRAM_PATH - it's a must.
16#
17# This is the place where VirtualBox resides
18# export VBOX_PROGRAM_PATH=/home/nike/work/ws/out/linux.amd64/debug/bin/
19# To allow Python find modules
20# export PYTHONPATH=$VBOX_PROGRAM_PATH/sdk/bindings/xpcom/python:$VBOX_PROGRAM_PATH
21# To allow library resolution
22# export LD_LIBRARY_PATH=$VBOX_PROGRAM_PATH
23# Additionally, on 64-bit Solaris, you need to use 64-bit Python from
24# /usr/bin/amd64/python and due to quirks in native modules loading of
25# Python do the following:
26# mkdir $VBOX_PROGRAM_PATH/64
27# ln -s $VBOX_PROGRAM_PATH/VBoxPython.so $VBOX_PROGRAM_PATH/64/VBoxPython.so
28#
29import traceback
30import sys
31import pdb
32
33g_hasreadline = 1
34try:
35 import readline
36 import rlcompleter
37except:
38 g_hasreadline = 0
39
40# this one has to be the first XPCOM related import
41import xpcom.vboxxpcom
42import xpcom
43import xpcom.components
44
45class LocalManager:
46 def getSessionObject(self, vb):
47 return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()
48
49if g_hasreadline:
50 class CompleterNG(rlcompleter.Completer):
51 def __init__(self, dic, ctx):
52 self.ctx = ctx
53 return rlcompleter.Completer.__init__(self,dic)
54
55 def complete(self, text, state):
56 """
57 taken from:
58 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
59 """
60 if text == "":
61 return ['\t',None][state]
62 else:
63 return rlcompleter.Completer.complete(self,text,state)
64
65 def global_matches(self, text):
66 """
67 Compute matches when text is a simple name.
68 Return a list of all names currently defined
69 in self.namespace that match.
70 """
71
72 matches = []
73 n = len(text)
74
75 for list in [ self.namespace ]:
76 for word in list:
77 if word[:n] == text:
78 matches.append(word)
79
80 for m in getMachines(self.ctx):
81 word = m.name
82 if word[:n] == text:
83 matches.append(word)
84 word = str(m.id)[1:-1]
85 if word[:n] == text:
86 matches.append(word)
87
88 return matches
89
90
91def autoCompletion(commands, ctx):
92 if not g_hasreadline:
93 return
94
95 comps = {}
96 for (k,v) in commands.items():
97 comps[k] = None
98 completer = CompleterNG(comps, ctx)
99 readline.set_completer(completer.complete)
100 readline.parse_and_bind("tab: complete")
101
102g_verbose = True
103
104def split_no_quotes(s):
105 return s.split()
106
107def startVm(mgr,vb,mach,type):
108 session = mgr.getSessionObject(vb)
109 uuid = mach.id
110 progress = vb.openRemoteSession(session, uuid, type, "")
111 progress.waitForCompletion(-1)
112 completed = progress.completed
113 rc = progress.resultCode
114 print "Completed:", completed, "rc:",rc
115 session.close()
116
117def getMachines(ctx):
118 return ctx['vb'].getMachines2()
119
120def asState(var):
121 if var:
122 return 'on'
123 else:
124 return 'off'
125
126def guestStats(ctx,guest):
127 stats = {
128 'Guest statistics for sample': xpcom.components.interfaces.GuestStatisticType.SampleNumber,
129 'CPU Load Idle': xpcom.components.interfaces.GuestStatisticType.CPULoad_Idle,
130 'CPU Load User': xpcom.components.interfaces.GuestStatisticType.CPULoad_User,
131 'CPU Load Kernel': xpcom.components.interfaces.GuestStatisticType.CPULoad_Kernel,
132 'Threads': xpcom.components.interfaces.GuestStatisticType.Threads,
133 'Processes': xpcom.components.interfaces.GuestStatisticType.Processes,
134 'Handles': xpcom.components.interfaces.GuestStatisticType.Handles,
135 }
136 for (k,v) in stats.items():
137 try:
138 val = guest.getStatistic(0, v)
139 print "'%s' = '%s'" %(k,str(v))
140 except:
141 print "Cannot get value for '%s'" %(k)
142 pass
143
144def cmdExistingVm(ctx,mach,cmd):
145 mgr=ctx['mgr']
146 vb=ctx['vb']
147 session = mgr.getSessionObject(vb)
148 uuid = mach.id
149 try:
150 progress = vb.openExistingSession(session, uuid)
151 except Exception,e:
152 print "Session to '%s' not open: %s" %(mach.name,e)
153 if g_verbose:
154 traceback.print_exc()
155 return
156 if session.state != xpcom.components.interfaces.SessionState.Open:
157 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
158 return
159 console=session.console
160 ops={'pause' : lambda: console.pause(),
161 'resume': lambda: console.resume(),
162 'powerdown': lambda: console.powerDown(),
163 'stats': lambda: guestStats(ctx, console.guest)}
164 ops[cmd]()
165 session.close()
166
167# can cache known machines, if needed
168def machById(ctx,id):
169 mach = None
170 for m in getMachines(ctx):
171 if str(m.id) == '{'+id+'}' or m.name == id:
172 mach = m
173 break
174 return mach
175
176def argsToMach(ctx,args):
177 if len(args) < 2:
178 print "usage: %s [vmname|uuid]" %(args[0])
179 return None
180 id = args[1]
181 m = machById(ctx, id)
182 if m == None:
183 print "Machine '%s' is unknown, use list command to find available machines" %(id)
184 return m
185
186def helpCmd(ctx, args):
187 if len(args) == 1:
188 print "Help page:"
189 for i in commands:
190 print " ",i,":", commands[i][0]
191 else:
192 c = commands.get(args[1], None)
193 if c == None:
194 print "Command '%s' not known" %(args[1])
195 else:
196 print " ",args[1],":", c[0]
197 return 0
198
199def listCmd(ctx, args):
200 for m in getMachines(ctx):
201 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
202 return 0
203
204def infoCmd(ctx,args):
205 if (len(args) < 2):
206 print "usage: info [vmname|uuid]"
207 return 0
208 mach = argsToMach(ctx,args)
209 if mach == None:
210 return 0
211 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
212 print " Name: ",mach.name
213 print " ID: ",mach.id
214 print " OS Type: ",os.description
215 print " RAM: %dM" %(mach.memorySize)
216 print " VRAM: %dM" %(mach.VRAMSize)
217 print " Monitors: %d" %(mach.MonitorCount)
218 print " Clipboard mode: %d" %(mach.clipboardMode)
219 print " Machine status: " ,mach.sessionState
220 bios = mach.BIOSSettings
221 print " BIOS ACPI: ",bios.ACPIEnabled
222 print " PAE: ",mach.PAEEnabled
223 print " Hardware virtualization: ",asState(mach.HWVirtExEnabled)
224 print " Nested paging: ",asState(mach.HWVirtExNestedPagingEnabled)
225 print " Last changed: ",mach.lastStateChange
226
227 return 0
228
229def startCmd(ctx, args):
230 mach = argsToMach(ctx,args)
231 if mach == None:
232 return 0
233 if len(args) > 2:
234 type = args[2]
235 else:
236 type = "gui"
237 startVm(ctx['mgr'], ctx['vb'], mach, type)
238 return 0
239
240def pauseCmd(ctx, args):
241 mach = argsToMach(ctx,args)
242 if mach == None:
243 return 0
244 cmdExistingVm(ctx, mach, 'pause')
245 return 0
246
247def powerdownCmd(ctx, args):
248 mach = argsToMach(ctx,args)
249 if mach == None:
250 return 0
251 cmdExistingVm(ctx, mach, 'powerdown')
252 return 0
253
254def resumeCmd(ctx, args):
255 mach = argsToMach(ctx,args)
256 if mach == None:
257 return 0
258 cmdExistingVm(ctx, mach, 'resume')
259 return 0
260
261def statsCmd(ctx, args):
262 mach = argsToMach(ctx,args)
263 if mach == None:
264 return 0
265 cmdExistingVm(ctx, mach, 'stats')
266 return 0
267
268def quitCmd(ctx, args):
269 return 1
270
271def aliasesCmd(ctx, args):
272 for (k,v) in aliases.items():
273 print "'%s' is an alias for '%s'" %(k,v)
274 return 0
275
276def verboseCmd(ctx, args):
277 global g_verbose
278 g_verbose = not g_verbose
279 return 0
280
281def hostCmd(ctx, args):
282 host = ctx['vb'].host
283 cnt = host.processorCount
284 print "Processor count:",cnt
285 for i in range(0,cnt):
286 print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
287
288 collector = ctx['vb'].performanceCollector
289
290 (vals, names, objs, idxs, lens) = collector.queryMetricsData(["*"], [host])
291 for i in range(0,len(vals)):
292 print "for name:",names[i]," val:",vals[i]
293
294 return 0
295
296aliases = {'s':'start',
297 'i':'info',
298 'l':'list',
299 'h':'help',
300 'a':'aliases',
301 'q':'quit', 'exit':'quit',
302 'v':'verbose'}
303
304commands = {'help':['Prints help information', helpCmd],
305 'start':['Start virtual machine by name or uuid', startCmd],
306 'pause':['Pause virtual machine', pauseCmd],
307 'resume':['Resume virtual machine', resumeCmd],
308 'stats':['Stats for virtual machine', statsCmd],
309 'powerdown':['Power down virtual machine', powerdownCmd],
310 'list':['Shows known virtual machines', listCmd],
311 'info':['Shows info on machine', infoCmd],
312 'aliases':['Shows aliases', aliasesCmd],
313 'verbose':['Toggle verbosity', verboseCmd],
314 'quit':['Exits', quitCmd],
315 'host':['Show host information', hostCmd]}
316
317def runCommand(ctx, cmd):
318 if len(cmd) == 0: return 0
319 args = split_no_quotes(cmd)
320 c = args[0]
321 if aliases.get(c, None) != None:
322 c = aliases[c]
323 ci = commands.get(c,None)
324 if ci == None:
325 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
326 return 0
327 return ci[1](ctx, args)
328
329def interpret():
330 vbox = None
331 try:
332 vbox = xpcom.components.classes["@virtualbox.org/VirtualBox;1"].createInstance()
333 except xpcom.Exception, e:
334 print "XPCOM exception: ",e
335 traceback.print_exc()
336 return
337 print "Running VirtualBox version %s" %(vbox.version)
338 mgr = LocalManager()
339 ctx = {'mgr':mgr, 'vb':vbox }
340
341 autoCompletion(commands, ctx)
342
343 while True:
344 try:
345 cmd = raw_input("vbox> ")
346 done = runCommand(ctx, cmd)
347 if done != 0: break
348 except KeyboardInterrupt:
349 print '====== You can type quit or q to leave'
350 break
351 except EOFError:
352 break;
353 except Exception,e:
354 print e
355 if g_verbose:
356 traceback.print_exc()
357
358
359interpret()
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