VirtualBox

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

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

Python shell: sweeter lambda for 'run'

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.2 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.virtualbox.org. 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, invalidate = False):
261 if ctx['vb'] is not None:
262 if ctx['_machlist'] is None or invalidate:
263 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
264 return ctx['_machlist']
265 else:
266 return []
267
268def asState(var):
269 if var:
270 return 'on'
271 else:
272 return 'off'
273
274def guestStats(ctx,mach):
275 if not ctx['perf']:
276 return
277 for metric in ctx['perf'].query(["*"], [mach]):
278 print metric['name'], metric['values_as_string']
279
280def guestExec(ctx, machine, console, cmds):
281 exec cmds
282
283def monitorGuest(ctx, machine, console, dur):
284 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
285 console.registerCallback(cb)
286 if dur == -1:
287 # not infinity, but close enough
288 dur = 100000
289 try:
290 end = time.time() + dur
291 while time.time() < end:
292 ctx['global'].waitForEvents(500)
293 # We need to catch all exceptions here, otherwise callback will never be unregistered
294 except:
295 pass
296 console.unregisterCallback(cb)
297
298
299def monitorVbox(ctx, dur):
300 vbox = ctx['vb']
301 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, vbox)
302 vbox.registerCallback(cb)
303 if dur == -1:
304 # not infinity, but close enough
305 dur = 100000
306 try:
307 end = time.time() + dur
308 while time.time() < end:
309 ctx['global'].waitForEvents(500)
310 # We need to catch all exceptions here, otherwise callback will never be unregistered
311 except:
312 if g_verbose:
313 traceback.print_exc()
314 vbox.unregisterCallback(cb)
315
316def cmdExistingVm(ctx,mach,cmd,args):
317 mgr=ctx['mgr']
318 vb=ctx['vb']
319 session = mgr.getSessionObject(vb)
320 uuid = mach.id
321 try:
322 progress = vb.openExistingSession(session, uuid)
323 except Exception,e:
324 print "Session to '%s' not open: %s" %(mach.name,e)
325 if g_verbose:
326 traceback.print_exc()
327 return
328 if session.state != ctx['ifaces'].SessionState_Open:
329 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
330 return
331 # unfortunately IGuest is suppressed, thus WebServices knows not about it
332 # this is an example how to handle local only functionality
333 if ctx['remote'] and cmd == 'stats2':
334 print 'Trying to use local only functionality, ignored'
335 return
336 console=session.console
337 ops={'pause': lambda: console.pause(),
338 'resume': lambda: console.resume(),
339 'powerdown': lambda: console.powerDown(),
340 'powerbutton': lambda: console.powerButton(),
341 'stats': lambda: guestStats(ctx, mach),
342 'guest': lambda: guestExec(ctx, mach, console, args),
343 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
344 'save': lambda: console.saveState().waitForCompletion(-1)
345 }
346 try:
347 ops[cmd]()
348 except Exception, e:
349 print 'failed: ',e
350 if g_verbose:
351 traceback.print_exc()
352
353 session.close()
354
355# can cache known machines, if needed
356def machById(ctx,id):
357 mach = None
358 for m in getMachines(ctx):
359 if m.name == id:
360 mach = m
361 break
362 mid = str(m.id)
363 if mid[0] == '{':
364 mid = mid[1:-1]
365 if mid == id:
366 mach = m
367 break
368 return mach
369
370def argsToMach(ctx,args):
371 if len(args) < 2:
372 print "usage: %s [vmname|uuid]" %(args[0])
373 return None
374 id = args[1]
375 m = machById(ctx, id)
376 if m == None:
377 print "Machine '%s' is unknown, use list command to find available machines" %(id)
378 return m
379
380def helpCmd(ctx, args):
381 if len(args) == 1:
382 print "Help page:"
383 names = commands.keys()
384 names.sort()
385 for i in names:
386 print " ",i,":", commands[i][0]
387 else:
388 c = commands.get(args[1], None)
389 if c == None:
390 print "Command '%s' not known" %(args[1])
391 else:
392 print " ",args[1],":", c[0]
393 return 0
394
395def listCmd(ctx, args):
396 for m in getMachines(ctx, True):
397 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
398 return 0
399
400def getControllerType(type):
401 if type == 0:
402 return "Null"
403 elif type == 1:
404 return "LsiLogic"
405 elif type == 2:
406 return "BusLogic"
407 elif type == 3:
408 return "IntelAhci"
409 elif type == 4:
410 return "PIIX3"
411 elif type == 5:
412 return "PIIX4"
413 elif type == 6:
414 return "ICH6"
415 else:
416 return "Unknown"
417
418def infoCmd(ctx,args):
419 if (len(args) < 2):
420 print "usage: info [vmname|uuid]"
421 return 0
422 mach = argsToMach(ctx,args)
423 if mach == None:
424 return 0
425 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
426 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
427 print " Name [name]: %s" %(mach.name)
428 print " ID [n/a]: %s" %(mach.id)
429 print " OS Type [n/a]: %s" %(os.description)
430 print
431 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
432 print " RAM [memorySize]: %dM" %(mach.memorySize)
433 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
434 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
435 print
436 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
437 print " Machine status [n/a]: %d" % (mach.sessionState)
438 print
439 bios = mach.BIOSSettings
440 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
441 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
442 print " PAE [PAEEnabled]: %s" %(asState(int(mach.PAEEnabled)))
443 print " Hardware virtualization [HWVirtExEnabled]: " + asState(mach.HWVirtExEnabled)
444 print " VPID support [HWVirtExVPIDEnabled]: " + asState(mach.HWVirtExVPIDEnabled)
445 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
446 print " Nested paging [HWVirtExNestedPagingEnabled]: " + asState(mach.HWVirtExNestedPagingEnabled)
447 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
448 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
449
450 controllers = ctx['global'].getArray(mach, 'storageControllers')
451 if controllers:
452 print
453 print " Controllers:"
454 for controller in controllers:
455 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
456
457 disks = ctx['global'].getArray(mach, 'hardDiskAttachments')
458 if disks:
459 print
460 print " Hard disk(s):"
461 for disk in disks:
462 print " Controller: %s port: %d device: %d:" % (disk.controller, disk.port, disk.device)
463 hd = disk.hardDisk
464 print " id: %s" %(hd.id)
465 print " location: %s" %(hd.location)
466 print " name: %s" %(hd.name)
467 print " format: %s" %(hd.format)
468 print
469
470 dvd = mach.DVDDrive
471 if dvd.getHostDrive():
472 hdvd = dvd.getHostDrive()
473 print " DVD:"
474 print " Host disk: %s" %(hdvd.name)
475 print
476
477 if dvd.getImage():
478 vdvd = dvd.getImage()
479 print " DVD:"
480 print " Image at: %s" %(vdvd.location)
481 print " Size: %s" %(vdvd.size)
482 print
483
484 floppy = mach.floppyDrive
485 if floppy.getHostDrive():
486 hfloppy = floppy.getHostDrive()
487 print " Floppy:"
488 print " Host disk: %s" %(hfloppy.name)
489 print
490
491 if floppy.getImage():
492 vfloppy = floppy.getImage()
493 print " Floppy:"
494 print " Image at: %s" %(vfloppy.location)
495 print " Size: %s" %(vfloppy.size)
496 print
497
498 return 0
499
500def startCmd(ctx, args):
501 mach = argsToMach(ctx,args)
502 if mach == None:
503 return 0
504 if len(args) > 2:
505 type = args[2]
506 else:
507 type = "gui"
508 startVm(ctx, mach, type)
509 return 0
510
511def createCmd(ctx, args):
512 if (len(args) < 3 or len(args) > 4):
513 print "usage: create name ostype <basefolder>"
514 return 0
515 name = args[1]
516 oskind = args[2]
517 if len(args) == 4:
518 base = args[3]
519 else:
520 base = ''
521 try:
522 ctx['vb'].getGuestOSType(oskind)
523 except Exception, e:
524 print 'Unknown OS type:',oskind
525 return 0
526 createVm(ctx, name, oskind, base)
527 return 0
528
529def removeCmd(ctx, args):
530 mach = argsToMach(ctx,args)
531 if mach == None:
532 return 0
533 removeVm(ctx, mach)
534 return 0
535
536def pauseCmd(ctx, args):
537 mach = argsToMach(ctx,args)
538 if mach == None:
539 return 0
540 cmdExistingVm(ctx, mach, 'pause', '')
541 return 0
542
543def powerdownCmd(ctx, args):
544 mach = argsToMach(ctx,args)
545 if mach == None:
546 return 0
547 cmdExistingVm(ctx, mach, 'powerdown', '')
548 return 0
549
550def powerbuttonCmd(ctx, args):
551 mach = argsToMach(ctx,args)
552 if mach == None:
553 return 0
554 cmdExistingVm(ctx, mach, 'powerbutton', '')
555 return 0
556
557def resumeCmd(ctx, args):
558 mach = argsToMach(ctx,args)
559 if mach == None:
560 return 0
561 cmdExistingVm(ctx, mach, 'resume', '')
562 return 0
563
564def saveCmd(ctx, args):
565 mach = argsToMach(ctx,args)
566 if mach == None:
567 return 0
568 cmdExistingVm(ctx, mach, 'save', '')
569 return 0
570
571def statsCmd(ctx, args):
572 mach = argsToMach(ctx,args)
573 if mach == None:
574 return 0
575 cmdExistingVm(ctx, mach, 'stats', '')
576 return 0
577
578def guestCmd(ctx, args):
579 if (len(args) < 3):
580 print "usage: guest name commands"
581 return 0
582 mach = argsToMach(ctx,args)
583 if mach == None:
584 return 0
585 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
586 return 0
587
588def setvarCmd(ctx, args):
589 if (len(args) < 4):
590 print "usage: setvar [vmname|uuid] expr value"
591 return 0
592 mach = argsToMach(ctx,args)
593 if mach == None:
594 return 0
595 session = ctx['global'].openMachineSession(mach.id)
596 mach = session.machine
597 expr = 'mach.'+args[2]+' = '+args[3]
598 print "Executing",expr
599 try:
600 exec expr
601 except Exception, e:
602 print 'failed: ',e
603 if g_verbose:
604 traceback.print_exc()
605 mach.saveSettings()
606 session.close()
607 return 0
608
609def quitCmd(ctx, args):
610 return 1
611
612def aliasCmd(ctx, args):
613 if (len(args) == 3):
614 aliases[args[1]] = args[2]
615 return 0
616
617 for (k,v) in aliases.items():
618 print "'%s' is an alias for '%s'" %(k,v)
619 return 0
620
621def verboseCmd(ctx, args):
622 global g_verbose
623 g_verbose = not g_verbose
624 return 0
625
626def getUSBStateString(state):
627 if state == 0:
628 return "NotSupported"
629 elif state == 1:
630 return "Unavailable"
631 elif state == 2:
632 return "Busy"
633 elif state == 3:
634 return "Available"
635 elif state == 4:
636 return "Held"
637 elif state == 5:
638 return "Captured"
639 else:
640 return "Unknown"
641
642def hostCmd(ctx, args):
643 host = ctx['vb'].host
644 cnt = host.processorCount
645 print "Processor count:",cnt
646 for i in range(0,cnt):
647 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
648
649 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
650 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
651 if host.Acceleration3DAvailable:
652 print "3D acceleration available"
653 else:
654 print "3D acceleration NOT available"
655
656 print "Network interfaces:"
657 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
658 print " %s (%s)" %(ni.name, ni.IPAddress)
659
660 print "DVD drives:"
661 for dd in ctx['global'].getArray(host, 'DVDDrives'):
662 print " %s - %s" %(dd.name, dd.description)
663
664 print "USB devices:"
665 for ud in ctx['global'].getArray(host, 'USBDevices'):
666 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
667
668 if ctx['perf']:
669 for metric in ctx['perf'].query(["*"], [host]):
670 print metric['name'], metric['values_as_string']
671
672 return 0
673
674def monitorGuestCmd(ctx, args):
675 if (len(args) < 2):
676 print "usage: monitorGuest name (duration)"
677 return 0
678 mach = argsToMach(ctx,args)
679 if mach == None:
680 return 0
681 dur = 5
682 if len(args) > 2:
683 dur = float(args[2])
684 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
685 return 0
686
687def monitorVboxCmd(ctx, args):
688 if (len(args) > 2):
689 print "usage: monitorVbox (duration)"
690 return 0
691 dur = 5
692 if len(args) > 1:
693 dur = float(args[1])
694 monitorVbox(ctx, dur)
695 return 0
696
697def getAdapterType(ctx, type):
698 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
699 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
700 return "pcnet"
701 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
702 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
703 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
704 return "e1000"
705 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
706 return None
707 else:
708 raise Exception("Unknown adapter type: "+type)
709
710
711def portForwardCmd(ctx, args):
712 if (len(args) != 5):
713 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
714 return 0
715 mach = argsToMach(ctx,args)
716 if mach == None:
717 return 0
718 adapterNum = int(args[2])
719 hostPort = int(args[3])
720 guestPort = int(args[4])
721 proto = "TCP"
722 session = ctx['global'].openMachineSession(mach.id)
723 mach = session.machine
724
725 adapter = mach.getNetworkAdapter(adapterNum)
726 adapterType = getAdapterType(ctx, adapter.adapterType)
727
728 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
729 config = "VBoxInternal/Devices/" + adapterType + "/"
730 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
731
732 mach.setExtraData(config + "/Protocol", proto)
733 mach.setExtraData(config + "/HostPort", str(hostPort))
734 mach.setExtraData(config + "/GuestPort", str(guestPort))
735
736 mach.saveSettings()
737 session.close()
738
739 return 0
740
741
742def showLogCmd(ctx, args):
743 if (len(args) < 2):
744 print "usage: showLog <vm> <num>"
745 return 0
746 mach = argsToMach(ctx,args)
747 if mach == None:
748 return 0
749
750 log = "VBox.log"
751 if (len(args) > 2):
752 log += "."+args[2]
753 fileName = os.path.join(mach.logFolder, log)
754
755 try:
756 lf = open(fileName, 'r')
757 except IOError,e:
758 print "cannot open: ",e
759 return 0
760
761 for line in lf:
762 print line,
763 lf.close()
764
765 return 0
766
767def evalCmd(ctx, args):
768 expr = ' '.join(args[1:])
769 try:
770 exec expr
771 except Exception, e:
772 print 'failed: ',e
773 if g_verbose:
774 traceback.print_exc()
775 return 0
776
777def reloadExtCmd(ctx, args):
778 # maybe will want more args smartness
779 checkUserExtensions(ctx, commands, ctx['vb'].homeFolder)
780 autoCompletion(commands, ctx)
781 return 0
782
783
784def runScriptCmd(ctx, args):
785 if (len(args) != 2):
786 print "usage: runScript <script>"
787 return 0
788 try:
789 lf = open(args[1], 'r')
790 except IOError,e:
791 print "cannot open:",args[1], ":",e
792 return 0
793
794 try:
795 for line in lf:
796 done = runCommand(ctx, line)
797 if done != 0: break
798 except Exception,e:
799 print "error:",e
800 if g_verbose:
801 traceback.print_exc()
802 lf.close()
803 return 0
804
805def sleepCmd(ctx, args):
806 if (len(args) != 2):
807 print "usage: sleep <secs>"
808 return 0
809
810 try:
811 time.sleep(float(args[1]))
812 except:
813 # to allow sleep interrupt
814 pass
815 return 0
816
817
818def connectCmd(ctx, args):
819 if (len(args) > 4):
820 print "usage: connect [url] [username] [passwd]"
821 return 0
822
823 if ctx['vb'] is not None:
824 print "Already connected, disconnect first..."
825 return 0
826
827 if (len(args) > 1):
828 url = args[1]
829 else:
830 url = None
831
832 if (len(args) > 2):
833 user = args[2]
834 else:
835 user = ""
836
837 if (len(args) > 3):
838 passwd = args[3]
839 else:
840 passwd = ""
841
842 vbox = ctx['global'].platform.connect(url, user, passwd)
843 ctx['vb'] = vbox
844 print "Running VirtualBox version %s" %(vbox.version)
845 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
846 return 0
847
848def disconnectCmd(ctx, args):
849 if (len(args) != 1):
850 print "usage: disconnect"
851 return 0
852
853 if ctx['vb'] is None:
854 print "Not connected yet."
855 return 0
856
857 try:
858 ctx['global'].platform.disconnect()
859 except:
860 ctx['vb'] = None
861 raise
862
863 ctx['vb'] = None
864 return 0
865
866aliases = {'s':'start',
867 'i':'info',
868 'l':'list',
869 'h':'help',
870 'a':'alias',
871 'q':'quit', 'exit':'quit',
872 'v':'verbose'}
873
874commands = {'help':['Prints help information', helpCmd, 0],
875 'start':['Start virtual machine by name or uuid', startCmd, 0],
876 'create':['Create virtual machine', createCmd, 0],
877 'remove':['Remove virtual machine', removeCmd, 0],
878 'pause':['Pause virtual machine', pauseCmd, 0],
879 'resume':['Resume virtual machine', resumeCmd, 0],
880 'save':['Save execution state of virtual machine', saveCmd, 0],
881 'stats':['Stats for virtual machine', statsCmd, 0],
882 'powerdown':['Power down virtual machine', powerdownCmd, 0],
883 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
884 'list':['Shows known virtual machines', listCmd, 0],
885 'info':['Shows info on machine', infoCmd, 0],
886 'alias':['Control aliases', aliasCmd, 0],
887 'verbose':['Toggle verbosity', verboseCmd, 0],
888 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
889 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
890 'quit':['Exits', quitCmd, 0],
891 'host':['Show host information', hostCmd, 0],
892 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
893 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
894 'monitorVbox':['Monitor what happens with Virtual Box for some time: monitorVbox 10', monitorVboxCmd, 0],
895 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
896 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
897 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
898 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
899 'sleep':['Sleep for specified number of seconds: sleep <secs>', sleepCmd, 0],
900 }
901
902def runCommandArgs(ctx, args):
903 c = args[0]
904 if aliases.get(c, None) != None:
905 c = aliases[c]
906 ci = commands.get(c,None)
907 if ci == None:
908 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
909 return 0
910 return ci[1](ctx, args)
911
912
913def runCommand(ctx, cmd):
914 if len(cmd) == 0: return 0
915 args = split_no_quotes(cmd)
916 if len(args) == 0: return 0
917 return runCommandArgs(ctx, args)
918
919#
920# To write your own custom commands to vboxshell, create
921# file ~/.VirtualBox/shellext.py with content like
922#
923# def runTestCmd(ctx, args):
924# print "Testy test", ctx['vb']
925# return 0
926#
927# commands = {
928# 'test': ['Test help', runTestCmd]
929# }
930# and issue reloadExt shell command.
931# This file also will be read automatically on startup.
932#
933def checkUserExtensions(ctx, cmds, folder):
934 name = os.path.join(str(folder), "shellext.py")
935 if not os.path.isfile(name):
936 return
937 d = {}
938 try:
939 execfile(name, d, d)
940 for (k,v) in d['commands'].items():
941 if g_verbose:
942 print "customize: adding \"%s\" - %s" %(k, v[0])
943 cmds[k] = [v[0], v[1], 1]
944 except:
945 print "Error loading user extensions:"
946 traceback.print_exc()
947
948def interpret(ctx):
949 if ctx['remote']:
950 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
951 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
952
953 vbox = ctx['vb']
954
955 if vbox is not None:
956 print "Running VirtualBox version %s" %(vbox.version)
957 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
958 home = vbox.homeFolder
959 else:
960 ctx['perf'] = None
961 home = os.path.join(os.path.expanduser("~"), ".VirtualBox")
962
963 checkUserExtensions(ctx, commands, home)
964
965 autoCompletion(commands, ctx)
966
967 # to allow to print actual host information, we collect info for
968 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
969 if ctx['perf']:
970 try:
971 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
972 except:
973 pass
974
975 while True:
976 try:
977 cmd = raw_input("vbox> ")
978 done = runCommand(ctx, cmd)
979 if done != 0: break
980 except KeyboardInterrupt:
981 print '====== You can type quit or q to leave'
982 break
983 except EOFError:
984 break;
985 except Exception,e:
986 print e
987 if g_verbose:
988 traceback.print_exc()
989
990 try:
991 # There is no need to disable metric collection. This is just an example.
992 if ct['perf']:
993 ctx['perf'].disable(['*'], [vbox.host])
994 except:
995 pass
996
997def runCommandCb(ctx, cmd, args):
998 args.insert(0, cmd)
999 return runCommandArgs(ctx, args)
1000
1001def main(argv):
1002 style = None
1003 autopath = False
1004 argv.pop(0)
1005 while len(argv) > 0:
1006 if argv[0] == "-w":
1007 style = "WEBSERVICE"
1008 if argv[0] == "-a":
1009 autopath = True
1010 argv.pop(0)
1011
1012 if autopath:
1013 cwd = os.getcwd()
1014 vpp = os.environ.get("VBOX_PROGRAM_PATH")
1015 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
1016 vpp = cwd
1017 print "Autodetected VBOX_PROGRAM_PATH as",vpp
1018 os.environ["VBOX_PROGRAM_PATH"] = cwd
1019 sys.path.append(os.path.join(vpp, "sdk", "installer"))
1020
1021 from vboxapi import VirtualBoxManager
1022 g_virtualBoxManager = VirtualBoxManager(style, None)
1023 ctx = {'global':g_virtualBoxManager,
1024 'mgr':g_virtualBoxManager.mgr,
1025 'vb':g_virtualBoxManager.vbox,
1026 'ifaces':g_virtualBoxManager.constants,
1027 'remote':g_virtualBoxManager.remote,
1028 'type':g_virtualBoxManager.type,
1029 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1030 'machById': lambda id: machById(ctx,id),
1031 '_machlist':None
1032 }
1033 interpret(ctx)
1034 g_virtualBoxManager.deinit()
1035 del g_virtualBoxManager
1036
1037if __name__ == '__main__':
1038 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