VirtualBox

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

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

Frontends/vboxshell: enhance "info" command to list attached hard disks too. also whitespace cleanup

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