VirtualBox

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

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

Main API: fixed few missed IDispatch interface map entries

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