VirtualBox

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

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

export python lib to OSE

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