VirtualBox

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

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

Python on the mac.

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