VirtualBox

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

Last change on this file since 23994 was 23994, checked in by vboxsync, 15 years ago

#3987: Virtio: Network adapter available in all frontends.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.7 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# This program is a simple interactive shell for VirtualBox. You can query #
19# information and issue commands from a simple command line. #
20# #
21# It also provides you with examples on how to use VirtualBox's Python API. #
22# This shell is even somewhat documented and supports TAB-completion and #
23# history if you have Python readline installed. #
24# #
25# Enjoy. #
26################################################################################
27
28import os,sys
29import traceback
30import shlex
31import time
32
33# Simple implementation of IConsoleCallback, one can use it as skeleton
34# for custom implementations
35class GuestMonitor:
36 def __init__(self, mach):
37 self.mach = mach
38
39 def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
40 print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
41 def onMouseCapabilityChange(self, supportsAbsolute, needsHostCursor):
42 print "%s: onMouseCapabilityChange: needsHostCursor=%d" %(self.mach.name, needsHostCursor)
43
44 def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
45 print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
46
47 def onStateChange(self, state):
48 print "%s: onStateChange state=%d" %(self.mach.name, state)
49
50 def onAdditionsStateChange(self):
51 print "%s: onAdditionsStateChange" %(self.mach.name)
52
53 def onNetworkAdapterChange(self, adapter):
54 print "%s: onNetworkAdapterChange" %(self.mach.name)
55
56 def onSerialPortChange(self, port):
57 print "%s: onSerialPortChange" %(self.mach.name)
58
59 def onParallelPortChange(self, port):
60 print "%s: onParallelPortChange" %(self.mach.name)
61
62 def onStorageControllerChange(self):
63 print "%s: onStorageControllerChange" %(self.mach.name)
64
65 def onMediumChange(self, attachment):
66 print "%s: onMediumChange" %(self.mach.name)
67
68 def onVRDPServerChange(self):
69 print "%s: onVRDPServerChange" %(self.mach.name)
70
71 def onUSBControllerChange(self):
72 print "%s: onUSBControllerChange" %(self.mach.name)
73
74 def onUSBDeviceStateChange(self, device, attached, error):
75 print "%s: onUSBDeviceStateChange" %(self.mach.name)
76
77 def onSharedFolderChange(self, scope):
78 print "%s: onSharedFolderChange" %(self.mach.name)
79
80 def onRuntimeError(self, fatal, id, message):
81 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
82
83 def onCanShowWindow(self):
84 print "%s: onCanShowWindow" %(self.mach.name)
85 return True
86
87 def onShowWindow(self, winId):
88 print "%s: onShowWindow: %d" %(self.mach.name, winId)
89
90class VBoxMonitor:
91 def __init__(self, params):
92 self.vbox = params[0]
93 self.isMscom = params[1]
94 pass
95
96 def onMachineStateChange(self, id, state):
97 print "onMachineStateChange: %s %d" %(id, state)
98
99 def onMachineDataChange(self,id):
100 print "onMachineDataChange: %s" %(id)
101
102 def onExtraDataCanChange(self, id, key, value):
103 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
104 # Witty COM bridge thinks if someone wishes to return tuple, hresult
105 # is one of values we want to return
106 if self.isMscom:
107 return "", 0, True
108 else:
109 return True, ""
110
111 def onExtraDataChange(self, id, key, value):
112 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
113
114 def onMediaRegistered(self, id, type, registered):
115 print "onMediaRegistered: %s" %(id)
116
117 def onMachineRegistered(self, id, registred):
118 print "onMachineRegistered: %s" %(id)
119
120 def onSessionStateChange(self, id, state):
121 print "onSessionStateChange: %s %d" %(id, state)
122
123 def onSnapshotTaken(self, mach, id):
124 print "onSnapshotTaken: %s %s" %(mach, id)
125
126 def onSnapshotDiscarded(self, mach, id):
127 print "onSnapshotDiscarded: %s %s" %(mach, id)
128
129 def onSnapshotChange(self, mach, id):
130 print "onSnapshotChange: %s %s" %(mach, id)
131
132 def onGuestPropertyChange(self, id, name, newValue, flags):
133 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
134
135g_hasreadline = 1
136try:
137 import readline
138 import rlcompleter
139except:
140 g_hasreadline = 0
141
142
143if g_hasreadline:
144 class CompleterNG(rlcompleter.Completer):
145 def __init__(self, dic, ctx):
146 self.ctx = ctx
147 return rlcompleter.Completer.__init__(self,dic)
148
149 def complete(self, text, state):
150 """
151 taken from:
152 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
153 """
154 if text == "":
155 return ['\t',None][state]
156 else:
157 return rlcompleter.Completer.complete(self,text,state)
158
159 def global_matches(self, text):
160 """
161 Compute matches when text is a simple name.
162 Return a list of all names currently defined
163 in self.namespace that match.
164 """
165
166 matches = []
167 n = len(text)
168
169 for list in [ self.namespace ]:
170 for word in list:
171 if word[:n] == text:
172 matches.append(word)
173
174
175 try:
176 for m in getMachines(self.ctx):
177 # although it has autoconversion, we need to cast
178 # explicitly for subscripts to work
179 word = str(m.name)
180 if word[:n] == text:
181 matches.append(word)
182 word = str(m.id)
183 if word[0] == '{':
184 word = word[1:-1]
185 if word[:n] == text:
186 matches.append(word)
187 except Exception,e:
188 traceback.print_exc()
189 print e
190
191 return matches
192
193
194def autoCompletion(commands, ctx):
195 if not g_hasreadline:
196 return
197
198 comps = {}
199 for (k,v) in commands.items():
200 comps[k] = None
201 completer = CompleterNG(comps, ctx)
202 readline.set_completer(completer.complete)
203 readline.parse_and_bind("tab: complete")
204
205g_verbose = True
206
207def split_no_quotes(s):
208 return shlex.split(s)
209
210def progressBar(ctx,p,wait=1000):
211 try:
212 while not p.completed:
213 print "%d %%\r" %(p.percent),
214 sys.stdout.flush()
215 p.waitForCompletion(wait)
216 ctx['global'].waitForEvents(0)
217 except KeyboardInterrupt:
218 print "Interrupted."
219
220
221def createVm(ctx,name,kind,base):
222 mgr = ctx['mgr']
223 vb = ctx['vb']
224 mach = vb.createMachine(name, kind, base, "")
225 mach.saveSettings()
226 print "created machine with UUID",mach.id
227 vb.registerMachine(mach)
228 # update cache
229 getMachines(ctx, True)
230
231def removeVm(ctx,mach):
232 mgr = ctx['mgr']
233 vb = ctx['vb']
234 id = mach.id
235 print "removing machine ",mach.name,"with UUID",id
236 session = ctx['global'].openMachineSession(id)
237 try:
238 mach = session.machine
239 for d in ctx['global'].getArray(mach, 'hardDiskAttachments'):
240 mach.detachHardDisk(d.controller, d.port, d.device)
241 except:
242 traceback.print_exc()
243 mach.saveSettings()
244 ctx['global'].closeMachineSession(session)
245 mach = vb.unregisterMachine(id)
246 if mach:
247 mach.deleteSettings()
248 # update cache
249 getMachines(ctx, True)
250
251def startVm(ctx,mach,type):
252 mgr = ctx['mgr']
253 vb = ctx['vb']
254 perf = ctx['perf']
255 session = mgr.getSessionObject(vb)
256 uuid = mach.id
257 progress = vb.openRemoteSession(session, uuid, type, "")
258 progressBar(ctx, progress, 100)
259 completed = progress.completed
260 rc = int(progress.resultCode)
261 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
262 if rc == 0:
263 # we ignore exceptions to allow starting VM even if
264 # perf collector cannot be started
265 if perf:
266 try:
267 perf.setup(['*'], [mach], 10, 15)
268 except Exception,e:
269 print e
270 if g_verbose:
271 traceback.print_exc()
272 pass
273 # if session not opened, close doesn't make sense
274 session.close()
275 else:
276 # Not yet implemented error string query API for remote API
277 if not ctx['remote']:
278 print session.QueryErrorObject(rc)
279
280def getMachines(ctx, invalidate = False):
281 if ctx['vb'] is not None:
282 if ctx['_machlist'] is None or invalidate:
283 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
284 return ctx['_machlist']
285 else:
286 return []
287
288def asState(var):
289 if var:
290 return 'on'
291 else:
292 return 'off'
293
294def guestStats(ctx,mach):
295 if not ctx['perf']:
296 return
297 for metric in ctx['perf'].query(["*"], [mach]):
298 print metric['name'], metric['values_as_string']
299
300def guestExec(ctx, machine, console, cmds):
301 exec cmds
302
303def monitorGuest(ctx, machine, console, dur):
304 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
305 console.registerCallback(cb)
306 if dur == -1:
307 # not infinity, but close enough
308 dur = 100000
309 try:
310 end = time.time() + dur
311 while time.time() < end:
312 ctx['global'].waitForEvents(500)
313 # We need to catch all exceptions here, otherwise callback will never be unregistered
314 except:
315 pass
316 console.unregisterCallback(cb)
317
318
319def monitorVBox(ctx, dur):
320 vbox = ctx['vb']
321 isMscom = (ctx['global'].type == 'MSCOM')
322 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
323 vbox.registerCallback(cb)
324 if dur == -1:
325 # not infinity, but close enough
326 dur = 100000
327 try:
328 end = time.time() + dur
329 while time.time() < end:
330 ctx['global'].waitForEvents(500)
331 # We need to catch all exceptions here, otherwise callback will never be unregistered
332 except:
333 pass
334 vbox.unregisterCallback(cb)
335
336def cmdExistingVm(ctx,mach,cmd,args):
337 mgr=ctx['mgr']
338 vb=ctx['vb']
339 session = mgr.getSessionObject(vb)
340 uuid = mach.id
341 try:
342 progress = vb.openExistingSession(session, uuid)
343 except Exception,e:
344 print "Session to '%s' not open: %s" %(mach.name,e)
345 if g_verbose:
346 traceback.print_exc()
347 return
348 if session.state != ctx['ifaces'].SessionState_Open:
349 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
350 return
351 # unfortunately IGuest is suppressed, thus WebServices knows not about it
352 # this is an example how to handle local only functionality
353 if ctx['remote'] and cmd == 'stats2':
354 print 'Trying to use local only functionality, ignored'
355 return
356 console=session.console
357 ops={'pause': lambda: console.pause(),
358 'resume': lambda: console.resume(),
359 'powerdown': lambda: console.powerDown(),
360 'powerbutton': lambda: console.powerButton(),
361 'stats': lambda: guestStats(ctx, mach),
362 'guest': lambda: guestExec(ctx, mach, console, args),
363 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
364 'save': lambda: progressBar(ctx,console.saveState())
365 }
366 try:
367 ops[cmd]()
368 except Exception, e:
369 print 'failed: ',e
370 if g_verbose:
371 traceback.print_exc()
372
373 session.close()
374
375def machById(ctx,id):
376 mach = None
377 for m in getMachines(ctx):
378 if m.name == id:
379 mach = m
380 break
381 mid = str(m.id)
382 if mid[0] == '{':
383 mid = mid[1:-1]
384 if mid == id:
385 mach = m
386 break
387 return mach
388
389def argsToMach(ctx,args):
390 if len(args) < 2:
391 print "usage: %s [vmname|uuid]" %(args[0])
392 return None
393 id = args[1]
394 m = machById(ctx, id)
395 if m == None:
396 print "Machine '%s' is unknown, use list command to find available machines" %(id)
397 return m
398
399def helpSingleCmd(cmd,h,sp):
400 if sp != 0:
401 spec = " [ext from "+sp+"]"
402 else:
403 spec = ""
404 print " %s: %s%s" %(cmd,h,spec)
405
406def helpCmd(ctx, args):
407 if len(args) == 1:
408 print "Help page:"
409 names = commands.keys()
410 names.sort()
411 for i in names:
412 helpSingleCmd(i, commands[i][0], commands[i][2])
413 else:
414 cmd = args[1]
415 c = commands.get(cmd)
416 if c == None:
417 print "Command '%s' not known" %(cmd)
418 else:
419 helpSingleCmd(cmd, c[0], c[2])
420 return 0
421
422def listCmd(ctx, args):
423 for m in getMachines(ctx, True):
424 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
425 return 0
426
427def getControllerType(type):
428 if type == 0:
429 return "Null"
430 elif type == 1:
431 return "LsiLogic"
432 elif type == 2:
433 return "BusLogic"
434 elif type == 3:
435 return "IntelAhci"
436 elif type == 4:
437 return "PIIX3"
438 elif type == 5:
439 return "PIIX4"
440 elif type == 6:
441 return "ICH6"
442 else:
443 return "Unknown"
444
445def infoCmd(ctx,args):
446 if (len(args) < 2):
447 print "usage: info [vmname|uuid]"
448 return 0
449 mach = argsToMach(ctx,args)
450 if mach == None:
451 return 0
452 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
453 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
454 print " Name [name]: %s" %(mach.name)
455 print " ID [n/a]: %s" %(mach.id)
456 print " OS Type [n/a]: %s" %(os.description)
457 print " Firmware [firmwareType]: %s" %(mach.firmwareType)
458 print
459 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
460 print " RAM [memorySize]: %dM" %(mach.memorySize)
461 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
462 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
463 print
464 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
465 print " Machine status [n/a]: %d" % (mach.sessionState)
466 print
467 bios = mach.BIOSSettings
468 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
469 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
470 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
471 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
472 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
473 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
474 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
475 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
476
477 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
478 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
479
480 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
481 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
482
483 controllers = ctx['global'].getArray(mach, 'storageControllers')
484 if controllers:
485 print
486 print " Controllers:"
487 for controller in controllers:
488 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
489
490 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
491 if attaches:
492 print
493 print " Mediums:"
494 for a in attaches:
495 print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
496 m = a.medium
497 if a.type == ctx['global'].constants.DeviceType_HardDisk:
498 print " HDD:"
499 print " Id: %s" %(m.id)
500 print " Location: %s" %(m.location)
501 print " Name: %s" %(m.name)
502 print " Format: %s" %(m.format)
503
504 if a.type == ctx['global'].constants.DeviceType_DVD:
505 print " DVD:"
506 if m:
507 print " Id: %s" %(m.id)
508 print " Name: %s" %(m.name)
509 if m.hostDrive:
510 print " Host DVD %s" %(m.location)
511 if a.passthrough:
512 print " [passthrough mode]"
513 else:
514 print " Virtual image at %s" %(m.location)
515 print " Size: %s" %(m.size)
516
517 if a.type == ctx['global'].constants.DeviceType_Floppy:
518 print " Floppy:"
519 if m:
520 print " Id: %s" %(m.id)
521 print " Name: %s" %(m.name)
522 if m.hostDrive:
523 print " Host floppy %s" %(m.location)
524 else:
525 print " Virtual image at %s" %(m.location)
526 print " Size: %s" %(m.size)
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_Virtio):
736 return "virtio"
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