VirtualBox

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

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

Python shell: more VM info

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 28.3 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
32import time
33
34# Simple implementation of IConsoleCallback, one can use it as skeleton
35# for custom implementations
36class GuestMonitor:
37 def __init__(self, mach):
38 self.mach = mach
39
40 def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
41 print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
42 def onMouseCapabilityChange(self, supportsAbsolute, needsHostCursor):
43 print "%s: onMouseCapabilityChange: needsHostCursor=%d" %(self.mach.name, needsHostCursor)
44
45 def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
46 print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
47
48 def onStateChange(self, state):
49 print "%s: onStateChange state=%d" %(self.mach.name, state)
50
51 def onAdditionsStateChange(self):
52 print "%s: onAdditionsStateChange" %(self.mach.name)
53
54 def onDVDDriveChange(self):
55 print "%s: onDVDDriveChange" %(self.mach.name)
56
57 def onFloppyDriveChange(self):
58 print "%s: onFloppyDriveChange" %(self.mach.name)
59
60 def onNetworkAdapterChange(self, adapter):
61 print "%s: onNetworkAdapterChange" %(self.mach.name)
62
63 def onSerialPortChange(self, port):
64 print "%s: onSerialPortChange" %(self.mach.name)
65
66 def onParallelPortChange(self, port):
67 print "%s: onParallelPortChange" %(self.mach.name)
68
69 def onStorageControllerChange(self):
70 print "%s: onStorageControllerChange" %(self.mach.name)
71
72 def onVRDPServerChange(self):
73 print "%s: onVRDPServerChange" %(self.mach.name)
74
75 def onUSBControllerChange(self):
76 print "%s: onUSBControllerChange" %(self.mach.name)
77
78 def onUSBDeviceStateChange(self, device, attached, error):
79 print "%s: onUSBDeviceStateChange" %(self.mach.name)
80
81 def onSharedFolderChange(self, scope):
82 print "%s: onSharedFolderChange" %(self.mach.name)
83
84 def onRuntimeError(self, fatal, id, message):
85 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
86
87 def onCanShowWindow(self):
88 print "%s: onCanShowWindow" %(self.mach.name)
89 return True
90
91 def onShowWindow(self, winId):
92 print "%s: onShowWindow: %d" %(self.mach.name, winId)
93
94class VBoxMonitor:
95 def __init__(self, vbox):
96 self.vbox = vbox
97 pass
98
99 def onMachineStateChange(self, id, state):
100 print "onMachineStateChange: %s %d" %(id, state)
101
102 def onMachineDataChange(self,id):
103 print "onMachineDataChange: %s" %(id)
104
105 def onExtraDataCanChange(self, id, key, value):
106 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
107 return True, ""
108
109 def onExtraDataChange(self, id, key, value):
110 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
111
112 def onMediaRegistred(self, id, type, registred):
113 print "onMediaRegistred: %s" %(id)
114
115 def onMachineRegistred(self, id, registred):
116 print "onMachineRegistred: %s" %(id)
117
118 def onSessionStateChange(self, id, state):
119 print "onSessionStateChange: %s %d" %(id, state)
120
121 def onSnapshotTaken(self, mach, id):
122 print "onSnapshotTaken: %s %s" %(mach, id)
123
124 def onSnapshotDiscarded(self, mach, id):
125 print "onSnapshotDiscarded: %s %s" %(mach, id)
126
127 def onSnapshotChange(self, mach, id):
128 print "onSnapshotChange: %s %s" %(mach, id)
129
130 def onGuestPropertyChange(self, id, name, newValue, flags):
131 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
132
133g_hasreadline = 1
134try:
135 import readline
136 import rlcompleter
137except:
138 g_hasreadline = 0
139
140
141if g_hasreadline:
142 class CompleterNG(rlcompleter.Completer):
143 def __init__(self, dic, ctx):
144 self.ctx = ctx
145 return rlcompleter.Completer.__init__(self,dic)
146
147 def complete(self, text, state):
148 """
149 taken from:
150 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
151 """
152 if text == "":
153 return ['\t',None][state]
154 else:
155 return rlcompleter.Completer.complete(self,text,state)
156
157 def global_matches(self, text):
158 """
159 Compute matches when text is a simple name.
160 Return a list of all names currently defined
161 in self.namespace that match.
162 """
163
164 matches = []
165 n = len(text)
166
167 for list in [ self.namespace ]:
168 for word in list:
169 if word[:n] == text:
170 matches.append(word)
171
172
173 try:
174 for m in getMachines(self.ctx):
175 # although it has autoconversion, we need to cast
176 # explicitly for subscripts to work
177 word = str(m.name)
178 if word[:n] == text:
179 matches.append(word)
180 word = str(m.id)
181 if word[0] == '{':
182 word = word[1:-1]
183 if word[:n] == text:
184 matches.append(word)
185 except Exception,e:
186 traceback.print_exc()
187 print e
188
189 return matches
190
191
192def autoCompletion(commands, ctx):
193 if not g_hasreadline:
194 return
195
196 comps = {}
197 for (k,v) in commands.items():
198 comps[k] = None
199 completer = CompleterNG(comps, ctx)
200 readline.set_completer(completer.complete)
201 readline.parse_and_bind("tab: complete")
202
203g_verbose = True
204
205def split_no_quotes(s):
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 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 vbox = ctx['vb']
296 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, vbox)
297 vbox.registerCallback(cb)
298 if dur == -1:
299 # not infinity, but close enough
300 dur = 100000
301 try:
302 end = time.time() + dur
303 while time.time() < end:
304 ctx['global'].waitForEvents(500)
305 # We need to catch all exceptions here, otherwise callback will never be unregistered
306 except:
307 if g_verbose:
308 traceback.print_exc()
309 vbox.unregisterCallback(cb)
310
311def cmdExistingVm(ctx,mach,cmd,args):
312 mgr=ctx['mgr']
313 vb=ctx['vb']
314 session = mgr.getSessionObject(vb)
315 uuid = mach.id
316 try:
317 progress = vb.openExistingSession(session, uuid)
318 except Exception,e:
319 print "Session to '%s' not open: %s" %(mach.name,e)
320 if g_verbose:
321 traceback.print_exc()
322 return
323 if session.state != ctx['ifaces'].SessionState_Open:
324 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
325 return
326 # unfortunately IGuest is suppressed, thus WebServices knows not about it
327 # this is an example how to handle local only functionality
328 if ctx['remote'] and cmd == 'stats2':
329 print 'Trying to use local only functionality, ignored'
330 return
331 console=session.console
332 ops={'pause': lambda: console.pause(),
333 'resume': lambda: console.resume(),
334 'powerdown': lambda: console.powerDown(),
335 'powerbutton': lambda: console.powerButton(),
336 'stats': lambda: guestStats(ctx, mach),
337 'guest': lambda: guestExec(ctx, mach, console, args),
338 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
339 'save': lambda: console.saveState().waitForCompletion(-1)
340 }
341 try:
342 ops[cmd]()
343 except Exception, e:
344 print 'failed: ',e
345 if g_verbose:
346 traceback.print_exc()
347
348 session.close()
349
350# can cache known machines, if needed
351def machById(ctx,id):
352 mach = None
353 for m in getMachines(ctx):
354 if m.name == id:
355 mach = m
356 break
357 mid = str(m.id)
358 if mid[0] == '{':
359 mid = mid[1:-1]
360 if mid == id:
361 mach = m
362 break
363 return mach
364
365def argsToMach(ctx,args):
366 if len(args) < 2:
367 print "usage: %s [vmname|uuid]" %(args[0])
368 return None
369 id = args[1]
370 m = machById(ctx, id)
371 if m == None:
372 print "Machine '%s' is unknown, use list command to find available machines" %(id)
373 return m
374
375def helpCmd(ctx, args):
376 if len(args) == 1:
377 print "Help page:"
378 names = commands.keys()
379 names.sort()
380 for i in names:
381 print " ",i,":", commands[i][0]
382 else:
383 c = commands.get(args[1], None)
384 if c == None:
385 print "Command '%s' not known" %(args[1])
386 else:
387 print " ",args[1],":", c[0]
388 return 0
389
390def listCmd(ctx, args):
391 for m in getMachines(ctx):
392 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
393 return 0
394
395def getControllerType(type):
396 if type == 0:
397 return "Null"
398 elif type == 1:
399 return "LsiLogic"
400 elif type == 2:
401 return "BusLogic"
402 elif type == 3:
403 return "IntelAhci"
404 elif type == 4:
405 return "PIIX3"
406 elif type == 5:
407 return "PIIX4"
408 elif type == 6:
409 return "ICH6"
410 else:
411 return "Unknown"
412
413def infoCmd(ctx,args):
414 if (len(args) < 2):
415 print "usage: info [vmname|uuid]"
416 return 0
417 mach = argsToMach(ctx,args)
418 if mach == None:
419 return 0
420 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
421 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
422 print " Name [name]: " + mach.name
423 print " ID [n/a]: " + mach.id
424 print " OS Type [n/a]: " + os.description
425 print
426 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
427 print " RAM [memorySize]: %dM" %(mach.memorySize)
428 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
429 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
430 print
431 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
432 print " Machine status [n/a]: %d" % (mach.sessionState)
433 print
434 bios = mach.BIOSSettings
435 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
436 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
437 print " PAE [PAEEnabled]: %s" %(asState(mach.PAEEnabled))
438 print " Hardware virtualization [HWVirtExEnabled]: " + asState(mach.HWVirtExEnabled)
439 print " VPID support [HWVirtExVPIDEnabled]: " + asState(mach.HWVirtExVPIDEnabled)
440 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
441 print " Nested paging [HWVirtExNestedPagingEnabled]: " + asState(mach.HWVirtExNestedPagingEnabled)
442 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
443 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
444
445 controllers = ctx['global'].getArray(mach, 'storageControllers')
446 if controllers:
447 print
448 print " Controllers:"
449 for controller in controllers:
450 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
451
452 disks = ctx['global'].getArray(mach, 'hardDiskAttachments')
453 if disks:
454 print
455 print " Hard disk(s):"
456 for disk in disks:
457 print " Controller: %s port: %d device: %d:" % (disk.controller, disk.port, disk.device)
458 hd = disk.hardDisk
459 print " id: " + hd.id
460 print " location: " + hd.location
461 print " name: " + hd.name
462 print " format: " + hd.format
463 print
464
465 dvd = mach.DVDDrive
466 if dvd.getHostDrive() is not None:
467 hdvd = dvd.getHostDrive()
468 print " DVD:"
469 print " Host disk:",hdvd.name
470 print
471
472 if dvd.getImage() is not None:
473 vdvd = dvd.getImage()
474 print " DVD:"
475 print " Image at:",vdvd.location
476 print " Size:",vdvd.size
477 print
478
479 floppy = mach.floppyDrive
480 if floppy.getHostDrive() is not None:
481 hfloppy = floppy.getHostDrive()
482 print " Floppy:"
483 print " Host disk:",hfloppy.name
484 print
485
486 if floppy.getImage() is not None:
487 vfloppy = floppy.getImage()
488 print " Floppy:"
489 print " Image at:",vfloppy.location
490 print " Size:",vfloppy.size
491 print
492
493 return 0
494
495def startCmd(ctx, args):
496 mach = argsToMach(ctx,args)
497 if mach == None:
498 return 0
499 if len(args) > 2:
500 type = args[2]
501 else:
502 type = "gui"
503 startVm(ctx, mach, type)
504 return 0
505
506def createCmd(ctx, args):
507 if (len(args) < 3 or len(args) > 4):
508 print "usage: create name ostype <basefolder>"
509 return 0
510 name = args[1]
511 oskind = args[2]
512 if len(args) == 4:
513 base = args[3]
514 else:
515 base = ''
516 try:
517 ctx['vb'].getGuestOSType(oskind)
518 except Exception, e:
519 print 'Unknown OS type:',oskind
520 return 0
521 createVm(ctx, name, oskind, base)
522 return 0
523
524def removeCmd(ctx, args):
525 mach = argsToMach(ctx,args)
526 if mach == None:
527 return 0
528 removeVm(ctx, mach)
529 return 0
530
531def pauseCmd(ctx, args):
532 mach = argsToMach(ctx,args)
533 if mach == None:
534 return 0
535 cmdExistingVm(ctx, mach, 'pause', '')
536 return 0
537
538def powerdownCmd(ctx, args):
539 mach = argsToMach(ctx,args)
540 if mach == None:
541 return 0
542 cmdExistingVm(ctx, mach, 'powerdown', '')
543 return 0
544
545def powerbuttonCmd(ctx, args):
546 mach = argsToMach(ctx,args)
547 if mach == None:
548 return 0
549 cmdExistingVm(ctx, mach, 'powerbutton', '')
550 return 0
551
552def resumeCmd(ctx, args):
553 mach = argsToMach(ctx,args)
554 if mach == None:
555 return 0
556 cmdExistingVm(ctx, mach, 'resume', '')
557 return 0
558
559def saveCmd(ctx, args):
560 mach = argsToMach(ctx,args)
561 if mach == None:
562 return 0
563 cmdExistingVm(ctx, mach, 'save', '')
564 return 0
565
566def statsCmd(ctx, args):
567 mach = argsToMach(ctx,args)
568 if mach == None:
569 return 0
570 cmdExistingVm(ctx, mach, 'stats', '')
571 return 0
572
573def guestCmd(ctx, args):
574 if (len(args) < 3):
575 print "usage: guest name commands"
576 return 0
577 mach = argsToMach(ctx,args)
578 if mach == None:
579 return 0
580 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
581 return 0
582
583def setvarCmd(ctx, args):
584 if (len(args) < 4):
585 print "usage: setvar [vmname|uuid] expr value"
586 return 0
587 mach = argsToMach(ctx,args)
588 if mach == None:
589 return 0
590 session = ctx['global'].openMachineSession(mach.id)
591 mach = session.machine
592 expr = 'mach.'+args[2]+' = '+args[3]
593 print "Executing",expr
594 try:
595 exec expr
596 except Exception, e:
597 print 'failed: ',e
598 if g_verbose:
599 traceback.print_exc()
600 mach.saveSettings()
601 session.close()
602 return 0
603
604def quitCmd(ctx, args):
605 return 1
606
607def aliasCmd(ctx, args):
608 if (len(args) == 3):
609 aliases[args[1]] = args[2]
610 return 0
611
612 for (k,v) in aliases.items():
613 print "'%s' is an alias for '%s'" %(k,v)
614 return 0
615
616def verboseCmd(ctx, args):
617 global g_verbose
618 g_verbose = not g_verbose
619 return 0
620
621def hostCmd(ctx, args):
622 host = ctx['vb'].host
623 cnt = host.processorCount
624 print "Processor count:",cnt
625 for i in range(0,cnt):
626 print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
627
628 if ctx['perf']:
629 for metric in ctx['perf'].query(["*"], [host]):
630 print metric['name'], metric['values_as_string']
631
632 return 0
633
634def monitorGuestCmd(ctx, args):
635 if (len(args) < 2):
636 print "usage: monitorGuest name (duration)"
637 return 0
638 mach = argsToMach(ctx,args)
639 if mach == None:
640 return 0
641 dur = 5
642 if len(args) > 2:
643 dur = float(args[2])
644 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
645 return 0
646
647def monitorVboxCmd(ctx, args):
648 if (len(args) > 2):
649 print "usage: monitorVbox (duration)"
650 return 0
651 dur = 5
652 if len(args) > 1:
653 dur = float(args[1])
654 monitorVbox(ctx, dur)
655 return 0
656
657def getAdapterType(ctx, type):
658 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
659 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
660 return "pcnet"
661 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
662 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
663 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
664 return "e1000"
665 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
666 return None
667 else:
668 raise Exception("Unknown adapter type: "+type)
669
670
671def portForwardCmd(ctx, args):
672 if (len(args) != 5):
673 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
674 return 0
675 mach = argsToMach(ctx,args)
676 if mach == None:
677 return 0
678 adapterNum = int(args[2])
679 hostPort = int(args[3])
680 guestPort = int(args[4])
681 proto = "TCP"
682 session = ctx['global'].openMachineSession(mach.id)
683 mach = session.machine
684
685 adapter = mach.getNetworkAdapter(adapterNum)
686 adapterType = getAdapterType(ctx, adapter.adapterType)
687
688 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
689 config = "VBoxInternal/Devices/" + adapterType + "/"
690 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
691
692 mach.setExtraData(config + "/Protocol", proto)
693 mach.setExtraData(config + "/HostPort", str(hostPort))
694 mach.setExtraData(config + "/GuestPort", str(guestPort))
695
696 mach.saveSettings()
697 session.close()
698
699 return 0
700
701
702def showLogCmd(ctx, args):
703 if (len(args) < 2):
704 print "usage: showLog <vm> <num>"
705 return 0
706 mach = argsToMach(ctx,args)
707 if mach == None:
708 return 0
709
710 log = "VBox.log"
711 if (len(args) > 2):
712 log += "."+args[2]
713 fileName = os.path.join(mach.logFolder, log)
714
715 try:
716 lf = open(fileName, 'r')
717 except IOError,e:
718 print "cannot open: ",e
719 return 0
720
721 for line in lf:
722 print line,
723 lf.close()
724
725 return 0
726
727def evalCmd(ctx, args):
728 expr = ' '.join(args[1:])
729 try:
730 exec expr
731 except Exception, e:
732 print 'failed: ',e
733 if g_verbose:
734 traceback.print_exc()
735 return 0
736
737def reloadExtCmd(ctx, args):
738 # maybe will want more args smartness
739 checkUserExtensions(ctx, commands, ctx['vb'].homeFolder)
740 autoCompletion(commands, ctx)
741 return 0
742
743
744def runScriptCmd(ctx, args):
745 if (len(args) != 2):
746 print "usage: runScript <script>"
747 return 0
748 try:
749 lf = open(args[1], 'r')
750 except IOError,e:
751 print "cannot open:",args[1], ":",e
752 return 0
753
754 try:
755 for line in lf:
756 done = runCommand(ctx, line)
757 if done != 0: break
758 except Exception,e:
759 print "error:",e
760 if g_verbose:
761 traceback.print_exc()
762 lf.close()
763 return 0
764
765def sleepCmd(ctx, args):
766 if (len(args) != 2):
767 print "usage: sleep <secs>"
768 return 0
769
770 time.sleep(float(args[1]))
771
772aliases = {'s':'start',
773 'i':'info',
774 'l':'list',
775 'h':'help',
776 'a':'alias',
777 'q':'quit', 'exit':'quit',
778 'v':'verbose'}
779
780commands = {'help':['Prints help information', helpCmd, 0],
781 'start':['Start virtual machine by name or uuid', startCmd, 0],
782 'create':['Create virtual machine', createCmd, 0],
783 'remove':['Remove virtual machine', removeCmd, 0],
784 'pause':['Pause virtual machine', pauseCmd, 0],
785 'resume':['Resume virtual machine', resumeCmd, 0],
786 'save':['Save execution state of virtual machine', saveCmd, 0],
787 'stats':['Stats for virtual machine', statsCmd, 0],
788 'powerdown':['Power down virtual machine', powerdownCmd, 0],
789 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
790 'list':['Shows known virtual machines', listCmd, 0],
791 'info':['Shows info on machine', infoCmd, 0],
792 'alias':['Control aliases', aliasCmd, 0],
793 'verbose':['Toggle verbosity', verboseCmd, 0],
794 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
795 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
796 'quit':['Exits', quitCmd, 0],
797 'host':['Show host information', hostCmd, 0],
798 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
799 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
800 'monitorVbox':['Monitor what happens with Virtual Box for some time: monitorVbox 10', monitorVboxCmd, 0],
801 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
802 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
803 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
804 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
805 'sleep':['Sleep for specified number of seconds: sleep <secs>', sleepCmd, 0],
806 }
807
808def runCommandArgs(ctx, args):
809 c = args[0]
810 if aliases.get(c, None) != None:
811 c = aliases[c]
812 ci = commands.get(c,None)
813 if ci == None:
814 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
815 return 0
816 return ci[1](ctx, args)
817
818
819def runCommand(ctx, cmd):
820 if len(cmd) == 0: return 0
821 args = split_no_quotes(cmd)
822 if len(args) == 0: return 0
823 return runCommandArgs(ctx, args)
824
825#
826# To write your own custom commands to vboxshell, create
827# file ~/.VirtualBox/shellext.py with content like
828#
829# def runTestCmd(ctx, args):
830# print "Testy test", ctx['vb']
831# return 0
832#
833# commands = {
834# 'test': ['Test help', runTestCmd]
835# }
836# and issue reloadExt shell command.
837# This file also will be read automatically on startup.
838#
839def checkUserExtensions(ctx, cmds, folder):
840 name = os.path.join(str(folder), "shellext.py")
841 if not os.path.isfile(name):
842 return
843 d = {}
844 try:
845 execfile(name, d, d)
846 for (k,v) in d['commands'].items():
847 if g_verbose:
848 print "customize: adding \"%s\" - %s" %(k, v[0])
849 cmds[k] = [v[0], v[1], 1]
850 except:
851 print "Error loading user extensions:"
852 traceback.print_exc()
853
854def interpret(ctx):
855 vbox = ctx['vb']
856 print "Running VirtualBox version %s" %(vbox.version)
857 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
858
859 checkUserExtensions(ctx, commands, vbox.homeFolder)
860
861 autoCompletion(commands, ctx)
862
863 # to allow to print actual host information, we collect info for
864 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
865 if ctx['perf']:
866 try:
867 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
868 except:
869 pass
870
871 while True:
872 try:
873 cmd = raw_input("vbox> ")
874 done = runCommand(ctx, cmd)
875 if done != 0: break
876 except KeyboardInterrupt:
877 print '====== You can type quit or q to leave'
878 break
879 except EOFError:
880 break;
881 except Exception,e:
882 print e
883 if g_verbose:
884 traceback.print_exc()
885
886 try:
887 # There is no need to disable metric collection. This is just an example.
888 if ct['perf']:
889 ctx['perf'].disable(['*'], [vbox.host])
890 except:
891 pass
892
893def runCommandCb(ctx, cmd, args):
894 args.insert(0, cmd)
895 return runCommandArgs(ctx, args)
896
897def main(argv):
898 style = None
899 autopath = False
900 argv.pop(0)
901 while len(argv) > 0:
902 if argv[0] == "-w":
903 style = "WEBSERVICE"
904 if argv[0] == "-a":
905 autopath = True
906 argv.pop(0)
907
908 if autopath:
909 cwd = os.getcwd()
910 vpp = os.environ.get("VBOX_PROGRAM_PATH")
911 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
912 vpp = cwd
913 print "Autodetected VBOX_PROGRAM_PATH as",vpp
914 os.environ["VBOX_PROGRAM_PATH"] = cwd
915 sys.path.append(os.path.join(vpp, "sdk", "installer"))
916
917 from vboxapi import VirtualBoxManager
918 g_virtualBoxManager = VirtualBoxManager(style, None)
919 ctx = {'global':g_virtualBoxManager,
920 'mgr':g_virtualBoxManager.mgr,
921 'vb':g_virtualBoxManager.vbox,
922 'ifaces':g_virtualBoxManager.constants,
923 'remote':g_virtualBoxManager.remote,
924 'type':g_virtualBoxManager.type,
925 'run':runCommandCb
926 }
927 interpret(ctx)
928 g_virtualBoxManager.deinit()
929 del g_virtualBoxManager
930
931if __name__ == '__main__':
932 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