VirtualBox

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

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

event queues cleaned up

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