VirtualBox

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

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

Python shell: handle subtel COM/XPCOM difference

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