VirtualBox

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

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

vboxshell: HID info, symbolic lookup of enumeration element sample

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 42.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# 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, supportsRelative, needsHostCursor):
42 print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, 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 reportError(ctx,session,rc):
222 if not ctx['remote']:
223 print session.QueryErrorObject(rc)
224
225
226def createVm(ctx,name,kind,base):
227 mgr = ctx['mgr']
228 vb = ctx['vb']
229 mach = vb.createMachine(name, kind, base, "")
230 mach.saveSettings()
231 print "created machine with UUID",mach.id
232 vb.registerMachine(mach)
233 # update cache
234 getMachines(ctx, True)
235
236def removeVm(ctx,mach):
237 mgr = ctx['mgr']
238 vb = ctx['vb']
239 id = mach.id
240 print "removing machine ",mach.name,"with UUID",id
241 session = ctx['global'].openMachineSession(id)
242 try:
243 mach = session.machine
244 for d in ctx['global'].getArray(mach, 'mediumAttachments'):
245 mach.detachDevice(d.controller, d.port, d.device)
246 except:
247 traceback.print_exc()
248 mach.saveSettings()
249 ctx['global'].closeMachineSession(session)
250 mach = vb.unregisterMachine(id)
251 if mach:
252 mach.deleteSettings()
253 # update cache
254 getMachines(ctx, True)
255
256def startVm(ctx,mach,type):
257 mgr = ctx['mgr']
258 vb = ctx['vb']
259 perf = ctx['perf']
260 session = mgr.getSessionObject(vb)
261 uuid = mach.id
262 progress = vb.openRemoteSession(session, uuid, type, "")
263 progressBar(ctx, progress, 100)
264 completed = progress.completed
265 rc = int(progress.resultCode)
266 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
267 if rc == 0:
268 # we ignore exceptions to allow starting VM even if
269 # perf collector cannot be started
270 if perf:
271 try:
272 perf.setup(['*'], [mach], 10, 15)
273 except Exception,e:
274 print e
275 if g_verbose:
276 traceback.print_exc()
277 pass
278 # if session not opened, close doesn't make sense
279 session.close()
280 else:
281 reportError(ctx,session,rc)
282
283def getMachines(ctx, invalidate = False):
284 if ctx['vb'] is not None:
285 if ctx['_machlist'] is None or invalidate:
286 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
287 return ctx['_machlist']
288 else:
289 return []
290
291def asState(var):
292 if var:
293 return 'on'
294 else:
295 return 'off'
296
297def perfStats(ctx,mach):
298 if not ctx['perf']:
299 return
300 for metric in ctx['perf'].query(["*"], [mach]):
301 print metric['name'], metric['values_as_string']
302
303def guestExec(ctx, machine, console, cmds):
304 exec cmds
305
306def monitorGuest(ctx, machine, console, dur):
307 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
308 console.registerCallback(cb)
309 if dur == -1:
310 # not infinity, but close enough
311 dur = 100000
312 try:
313 end = time.time() + dur
314 while time.time() < end:
315 ctx['global'].waitForEvents(500)
316 # We need to catch all exceptions here, otherwise callback will never be unregistered
317 except:
318 pass
319 console.unregisterCallback(cb)
320
321
322def monitorVBox(ctx, dur):
323 vbox = ctx['vb']
324 isMscom = (ctx['global'].type == 'MSCOM')
325 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
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
339
340def takeScreenshot(ctx,console,args):
341 from PIL import Image
342 display = console.display
343 if len(args) > 0:
344 f = args[0]
345 else:
346 f = "/tmp/screenshot.png"
347 if len(args) > 1:
348 w = args[1]
349 else:
350 w = console.display.width
351 if len(args) > 2:
352 h = args[2]
353 else:
354 h = console.display.height
355 print "Saving screenshot (%d x %d) in %s..." %(w,h,f)
356 data = display.takeScreenShotSlow(w,h)
357 size = (w,h)
358 mode = "RGBA"
359 im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
360 im.save(f, "PNG")
361
362
363def teleport(ctx,session,console,args):
364 if args[0].find(":") == -1:
365 print "Use host:port format for teleport target"
366 return
367 (host,port) = args[0].split(":")
368 if len(args) > 1:
369 passwd = args[1]
370 else:
371 passwd = ""
372
373 port = int(port)
374 print "Teleporting to %s:%d..." %(host,port)
375 progress = console.teleport(host, port, passwd)
376 progressBar(ctx, progress, 100)
377 completed = progress.completed
378 rc = int(progress.resultCode)
379 if rc == 0:
380 print "Success!"
381 else:
382 reportError(ctx,session,rc)
383
384
385def guestStats(ctx,console,args):
386 guest = console.guest
387 # we need to set up guest statistics
388 if len(args) > 0 :
389 update = args[0]
390 else:
391 update = 1
392 if guest.statisticsUpdateInterval != update:
393 guest.statisticsUpdateInterval = update
394 try:
395 time.sleep(float(update)+0.1)
396 except:
397 # to allow sleep interruption
398 pass
399 all_stats = ctx['ifaces'].all_values('GuestStatisticType')
400 cpu = 0
401 for s in all_stats.keys():
402 try:
403 val = guest.getStatistic( cpu, all_stats[s])
404 print "%s: %d" %(s, val)
405 except:
406 # likely not implemented
407 pass
408
409def plugCpu(ctx,machine,session,args):
410 cpu = int(args)
411 print "Adding CPU %d..." %(cpu)
412 machine.HotPlugCPU(cpu)
413
414def unplugCpu(ctx,machine,session,args):
415 cpu = int(args)
416 print "Removing CPU %d..." %(cpu)
417 machine.HotUnplugCPU(cpu)
418
419def cmdExistingVm(ctx,mach,cmd,args):
420 mgr=ctx['mgr']
421 vb=ctx['vb']
422 session = mgr.getSessionObject(vb)
423 uuid = mach.id
424 try:
425 progress = vb.openExistingSession(session, uuid)
426 except Exception,e:
427 print "Session to '%s' not open: %s" %(mach.name,e)
428 if g_verbose:
429 traceback.print_exc()
430 return
431 if str(session.state) != str(ctx['ifaces'].SessionState_Open):
432 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
433 return
434 # this could be an example how to handle local only (i.e. unavailable
435 # in Webservices) functionality
436 if ctx['remote'] and cmd == 'some_local_only_command':
437 print 'Trying to use local only functionality, ignored'
438 return
439 console=session.console
440 ops={'pause': lambda: console.pause(),
441 'resume': lambda: console.resume(),
442 'powerdown': lambda: console.powerDown(),
443 'powerbutton': lambda: console.powerButton(),
444 'stats': lambda: perfStats(ctx, mach),
445 'guest': lambda: guestExec(ctx, mach, console, args),
446 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
447 'save': lambda: progressBar(ctx,console.saveState()),
448 'screenshot': lambda: takeScreenshot(ctx,console,args),
449 'teleport': lambda: teleport(ctx,session,console,args),
450 'gueststats': lambda: guestStats(ctx, console, args),
451 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
452 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
453 }
454 try:
455 ops[cmd]()
456 except Exception, e:
457 print 'failed: ',e
458 if g_verbose:
459 traceback.print_exc()
460
461 session.close()
462
463def machById(ctx,id):
464 mach = None
465 for m in getMachines(ctx):
466 if m.name == id:
467 mach = m
468 break
469 mid = str(m.id)
470 if mid[0] == '{':
471 mid = mid[1:-1]
472 if mid == id:
473 mach = m
474 break
475 return mach
476
477def argsToMach(ctx,args):
478 if len(args) < 2:
479 print "usage: %s [vmname|uuid]" %(args[0])
480 return None
481 id = args[1]
482 m = machById(ctx, id)
483 if m == None:
484 print "Machine '%s' is unknown, use list command to find available machines" %(id)
485 return m
486
487def helpSingleCmd(cmd,h,sp):
488 if sp != 0:
489 spec = " [ext from "+sp+"]"
490 else:
491 spec = ""
492 print " %s: %s%s" %(cmd,h,spec)
493
494def helpCmd(ctx, args):
495 if len(args) == 1:
496 print "Help page:"
497 names = commands.keys()
498 names.sort()
499 for i in names:
500 helpSingleCmd(i, commands[i][0], commands[i][2])
501 else:
502 cmd = args[1]
503 c = commands.get(cmd)
504 if c == None:
505 print "Command '%s' not known" %(cmd)
506 else:
507 helpSingleCmd(cmd, c[0], c[2])
508 return 0
509
510def listCmd(ctx, args):
511 for m in getMachines(ctx, True):
512 if m.teleporterEnabled:
513 tele = "[T] "
514 else:
515 tele = " "
516 print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,m.sessionState)
517 return 0
518
519def getControllerType(type):
520 if type == 0:
521 return "Null"
522 elif type == 1:
523 return "LsiLogic"
524 elif type == 2:
525 return "BusLogic"
526 elif type == 3:
527 return "IntelAhci"
528 elif type == 4:
529 return "PIIX3"
530 elif type == 5:
531 return "PIIX4"
532 elif type == 6:
533 return "ICH6"
534 else:
535 return "Unknown"
536
537def getFirmwareType(type):
538 if type == 0:
539 return "invalid"
540 elif type == 1:
541 return "bios"
542 elif type == 2:
543 return "efi"
544 elif type == 3:
545 return "efi64"
546 elif type == 4:
547 return "efidual"
548 else:
549 return "Unknown"
550
551
552def asEnumElem(ctx,enum,elem):
553 all = ctx['ifaces'].all_values(enum)
554 for e in all.keys():
555 if elem == all[e]:
556 return e
557 return "<unknown>"
558
559def infoCmd(ctx,args):
560 if (len(args) < 2):
561 print "usage: info [vmname|uuid]"
562 return 0
563 mach = argsToMach(ctx,args)
564 if mach == None:
565 return 0
566 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
567 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
568 print " Name [name]: %s" %(mach.name)
569 print " ID [n/a]: %s" %(mach.id)
570 print " OS Type [n/a]: %s" %(os.description)
571 print " Firmware [firmwareType]: %s (%s)" %(getFirmwareType(mach.firmwareType),mach.firmwareType)
572 print
573 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
574 print " RAM [memorySize]: %dM" %(mach.memorySize)
575 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
576 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
577 print
578 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
579 print " Machine status [n/a]: %d" % (mach.sessionState)
580 print
581 if mach.teleporterEnabled:
582 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
583 print
584 bios = mach.BIOSSettings
585 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
586 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
587 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
588 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
589 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
590 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
591 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
592 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
593
594 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
595 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
596
597 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
598 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
599 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
600 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
601 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
602
603 controllers = ctx['global'].getArray(mach, 'storageControllers')
604 if controllers:
605 print
606 print " Controllers:"
607 for controller in controllers:
608 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
609
610 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
611 if attaches:
612 print
613 print " Mediums:"
614 for a in attaches:
615 print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
616 m = a.medium
617 if a.type == ctx['global'].constants.DeviceType_HardDisk:
618 print " HDD:"
619 print " Id: %s" %(m.id)
620 print " Location: %s" %(m.location)
621 print " Name: %s" %(m.name)
622 print " Format: %s" %(m.format)
623
624 if a.type == ctx['global'].constants.DeviceType_DVD:
625 print " DVD:"
626 if m:
627 print " Id: %s" %(m.id)
628 print " Name: %s" %(m.name)
629 if m.hostDrive:
630 print " Host DVD %s" %(m.location)
631 if a.passthrough:
632 print " [passthrough mode]"
633 else:
634 print " Virtual image at %s" %(m.location)
635 print " Size: %s" %(m.size)
636
637 if a.type == ctx['global'].constants.DeviceType_Floppy:
638 print " Floppy:"
639 if m:
640 print " Id: %s" %(m.id)
641 print " Name: %s" %(m.name)
642 if m.hostDrive:
643 print " Host floppy %s" %(m.location)
644 else:
645 print " Virtual image at %s" %(m.location)
646 print " Size: %s" %(m.size)
647
648 return 0
649
650def startCmd(ctx, args):
651 mach = argsToMach(ctx,args)
652 if mach == None:
653 return 0
654 if len(args) > 2:
655 type = args[2]
656 else:
657 type = "gui"
658 startVm(ctx, mach, type)
659 return 0
660
661def createCmd(ctx, args):
662 if (len(args) < 3 or len(args) > 4):
663 print "usage: create name ostype <basefolder>"
664 return 0
665 name = args[1]
666 oskind = args[2]
667 if len(args) == 4:
668 base = args[3]
669 else:
670 base = ''
671 try:
672 ctx['vb'].getGuestOSType(oskind)
673 except Exception, e:
674 print 'Unknown OS type:',oskind
675 return 0
676 createVm(ctx, name, oskind, base)
677 return 0
678
679def removeCmd(ctx, args):
680 mach = argsToMach(ctx,args)
681 if mach == None:
682 return 0
683 removeVm(ctx, mach)
684 return 0
685
686def pauseCmd(ctx, args):
687 mach = argsToMach(ctx,args)
688 if mach == None:
689 return 0
690 cmdExistingVm(ctx, mach, 'pause', '')
691 return 0
692
693def powerdownCmd(ctx, args):
694 mach = argsToMach(ctx,args)
695 if mach == None:
696 return 0
697 cmdExistingVm(ctx, mach, 'powerdown', '')
698 return 0
699
700def powerbuttonCmd(ctx, args):
701 mach = argsToMach(ctx,args)
702 if mach == None:
703 return 0
704 cmdExistingVm(ctx, mach, 'powerbutton', '')
705 return 0
706
707def resumeCmd(ctx, args):
708 mach = argsToMach(ctx,args)
709 if mach == None:
710 return 0
711 cmdExistingVm(ctx, mach, 'resume', '')
712 return 0
713
714def saveCmd(ctx, args):
715 mach = argsToMach(ctx,args)
716 if mach == None:
717 return 0
718 cmdExistingVm(ctx, mach, 'save', '')
719 return 0
720
721def statsCmd(ctx, args):
722 mach = argsToMach(ctx,args)
723 if mach == None:
724 return 0
725 cmdExistingVm(ctx, mach, 'stats', '')
726 return 0
727
728def guestCmd(ctx, args):
729 if (len(args) < 3):
730 print "usage: guest name commands"
731 return 0
732 mach = argsToMach(ctx,args)
733 if mach == None:
734 return 0
735 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
736 return 0
737
738def screenshotCmd(ctx, args):
739 if (len(args) < 3):
740 print "usage: screenshot name file <width> <height>"
741 return 0
742 mach = argsToMach(ctx,args)
743 if mach == None:
744 return 0
745 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
746 return 0
747
748def teleportCmd(ctx, args):
749 if (len(args) < 3):
750 print "usage: teleport name host:port <password>"
751 return 0
752 mach = argsToMach(ctx,args)
753 if mach == None:
754 return 0
755 cmdExistingVm(ctx, mach, 'teleport', args[2:])
756 return 0
757
758def openportalCmd(ctx, args):
759 if (len(args) < 3):
760 print "usage: openportal name port <password>"
761 return 0
762 mach = argsToMach(ctx,args)
763 if mach == None:
764 return 0
765 port = int(args[2])
766 if (len(args) > 3):
767 passwd = args[3]
768 else:
769 passwd = ""
770 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
771 session = ctx['global'].openMachineSession(mach.id)
772 mach1 = session.machine
773 mach1.teleporterEnabled = True
774 mach1.teleporterPort = port
775 mach1.teleporterPassword = passwd
776 mach1.saveSettings()
777 session.close()
778 startVm(ctx, mach, "gui")
779 return 0
780
781def closeportalCmd(ctx, args):
782 if (len(args) < 2):
783 print "usage: closeportal name"
784 return 0
785 mach = argsToMach(ctx,args)
786 if mach == None:
787 return 0
788 if mach.teleporterEnabled:
789 session = ctx['global'].openMachineSession(mach.id)
790 mach1 = session.machine
791 mach1.teleporterEnabled = False
792 mach1.saveSettings()
793 session.close()
794 return 0
795
796def gueststatsCmd(ctx, args):
797 if (len(args) < 2):
798 print "usage: gueststats name <check interval>"
799 return 0
800 mach = argsToMach(ctx,args)
801 if mach == None:
802 return 0
803 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
804 return 0
805
806def plugcpuCmd(ctx, args):
807 if (len(args) < 2):
808 print "usage: plugcpu name cpuid"
809 return 0
810 mach = argsToMach(ctx,args)
811 if mach == None:
812 return 0
813 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
814 return 0
815
816def unplugcpuCmd(ctx, args):
817 if (len(args) < 2):
818 print "usage: unplugcpu name cpuid"
819 return 0
820 mach = argsToMach(ctx,args)
821 if mach == None:
822 return 0
823 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
824 return 0
825
826def setvarCmd(ctx, args):
827 if (len(args) < 4):
828 print "usage: setvar [vmname|uuid] expr value"
829 return 0
830 mach = argsToMach(ctx,args)
831 if mach == None:
832 return 0
833 session = ctx['global'].openMachineSession(mach.id)
834 mach = session.machine
835 expr = 'mach.'+args[2]+' = '+args[3]
836 print "Executing",expr
837 try:
838 exec expr
839 except Exception, e:
840 print 'failed: ',e
841 if g_verbose:
842 traceback.print_exc()
843 mach.saveSettings()
844 session.close()
845 return 0
846
847
848def setExtraDataCmd(ctx, args):
849 if (len(args) < 3):
850 print "usage: setextra [vmname|uuid|global] key <value>"
851 return 0
852 key = args[2]
853 if len(args) == 4:
854 value = args[3]
855 else:
856 value = None
857 if args[1] == 'global':
858 ctx['vb'].setExtraData(key, value)
859 return 0
860
861 mach = argsToMach(ctx,args)
862 if mach == None:
863 return 0
864 session = ctx['global'].openMachineSession(mach.id)
865 mach = session.machine
866 mach.setExtraData(key, value)
867 mach.saveSettings()
868 session.close()
869 return 0
870
871def printExtraKey(obj, key, value):
872 print "%s: '%s' = '%s'" %(obj, key, value)
873
874def getExtraDataCmd(ctx, args):
875 if (len(args) < 2):
876 print "usage: getextra [vmname|uuid|global] <key>"
877 return 0
878 if len(args) == 3:
879 key = args[2]
880 else:
881 key = None
882
883 if args[1] == 'global':
884 obj = ctx['vb']
885 else:
886 obj = argsToMach(ctx,args)
887 if obj == None:
888 return 0
889
890 if key == None:
891 keys = obj.getExtraDataKeys()
892 else:
893 keys = [ key ]
894 for k in keys:
895 printExtraKey(args[1], k, ctx['vb'].getExtraData(k))
896
897 return 0
898
899def quitCmd(ctx, args):
900 return 1
901
902def aliasCmd(ctx, args):
903 if (len(args) == 3):
904 aliases[args[1]] = args[2]
905 return 0
906
907 for (k,v) in aliases.items():
908 print "'%s' is an alias for '%s'" %(k,v)
909 return 0
910
911def verboseCmd(ctx, args):
912 global g_verbose
913 g_verbose = not g_verbose
914 return 0
915
916def getUSBStateString(state):
917 if state == 0:
918 return "NotSupported"
919 elif state == 1:
920 return "Unavailable"
921 elif state == 2:
922 return "Busy"
923 elif state == 3:
924 return "Available"
925 elif state == 4:
926 return "Held"
927 elif state == 5:
928 return "Captured"
929 else:
930 return "Unknown"
931
932def hostCmd(ctx, args):
933 host = ctx['vb'].host
934 cnt = host.processorCount
935 print "Processor count:",cnt
936 for i in range(0,cnt):
937 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
938
939 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
940 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
941 if host.Acceleration3DAvailable:
942 print "3D acceleration available"
943 else:
944 print "3D acceleration NOT available"
945
946 print "Network interfaces:"
947 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
948 print " %s (%s)" %(ni.name, ni.IPAddress)
949
950 print "DVD drives:"
951 for dd in ctx['global'].getArray(host, 'DVDDrives'):
952 print " %s - %s" %(dd.name, dd.description)
953
954 print "USB devices:"
955 for ud in ctx['global'].getArray(host, 'USBDevices'):
956 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
957
958 if ctx['perf']:
959 for metric in ctx['perf'].query(["*"], [host]):
960 print metric['name'], metric['values_as_string']
961
962 return 0
963
964def monitorGuestCmd(ctx, args):
965 if (len(args) < 2):
966 print "usage: monitorGuest name (duration)"
967 return 0
968 mach = argsToMach(ctx,args)
969 if mach == None:
970 return 0
971 dur = 5
972 if len(args) > 2:
973 dur = float(args[2])
974 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
975 return 0
976
977def monitorVBoxCmd(ctx, args):
978 if (len(args) > 2):
979 print "usage: monitorVBox (duration)"
980 return 0
981 dur = 5
982 if len(args) > 1:
983 dur = float(args[1])
984 monitorVBox(ctx, dur)
985 return 0
986
987def getAdapterType(ctx, type):
988 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
989 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
990 return "pcnet"
991 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
992 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
993 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
994 return "e1000"
995 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
996 return "virtio"
997 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
998 return None
999 else:
1000 raise Exception("Unknown adapter type: "+type)
1001
1002
1003def portForwardCmd(ctx, args):
1004 if (len(args) != 5):
1005 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1006 return 0
1007 mach = argsToMach(ctx,args)
1008 if mach == None:
1009 return 0
1010 adapterNum = int(args[2])
1011 hostPort = int(args[3])
1012 guestPort = int(args[4])
1013 proto = "TCP"
1014 session = ctx['global'].openMachineSession(mach.id)
1015 mach = session.machine
1016
1017 adapter = mach.getNetworkAdapter(adapterNum)
1018 adapterType = getAdapterType(ctx, adapter.adapterType)
1019
1020 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1021 config = "VBoxInternal/Devices/" + adapterType + "/"
1022 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1023
1024 mach.setExtraData(config + "/Protocol", proto)
1025 mach.setExtraData(config + "/HostPort", str(hostPort))
1026 mach.setExtraData(config + "/GuestPort", str(guestPort))
1027
1028 mach.saveSettings()
1029 session.close()
1030
1031 return 0
1032
1033
1034def showLogCmd(ctx, args):
1035 if (len(args) < 2):
1036 print "usage: showLog <vm> <num>"
1037 return 0
1038 mach = argsToMach(ctx,args)
1039 if mach == None:
1040 return 0
1041
1042 log = "VBox.log"
1043 if (len(args) > 2):
1044 log += "."+args[2]
1045 fileName = os.path.join(mach.logFolder, log)
1046
1047 try:
1048 lf = open(fileName, 'r')
1049 except IOError,e:
1050 print "cannot open: ",e
1051 return 0
1052
1053 for line in lf:
1054 print line,
1055 lf.close()
1056
1057 return 0
1058
1059def evalCmd(ctx, args):
1060 expr = ' '.join(args[1:])
1061 try:
1062 exec expr
1063 except Exception, e:
1064 print 'failed: ',e
1065 if g_verbose:
1066 traceback.print_exc()
1067 return 0
1068
1069def reloadExtCmd(ctx, args):
1070 # maybe will want more args smartness
1071 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1072 autoCompletion(commands, ctx)
1073 return 0
1074
1075
1076def runScriptCmd(ctx, args):
1077 if (len(args) != 2):
1078 print "usage: runScript <script>"
1079 return 0
1080 try:
1081 lf = open(args[1], 'r')
1082 except IOError,e:
1083 print "cannot open:",args[1], ":",e
1084 return 0
1085
1086 try:
1087 for line in lf:
1088 done = runCommand(ctx, line)
1089 if done != 0: break
1090 except Exception,e:
1091 print "error:",e
1092 if g_verbose:
1093 traceback.print_exc()
1094 lf.close()
1095 return 0
1096
1097def sleepCmd(ctx, args):
1098 if (len(args) != 2):
1099 print "usage: sleep <secs>"
1100 return 0
1101
1102 try:
1103 time.sleep(float(args[1]))
1104 except:
1105 # to allow sleep interrupt
1106 pass
1107 return 0
1108
1109
1110def shellCmd(ctx, args):
1111 if (len(args) < 2):
1112 print "usage: shell <commands>"
1113 return 0
1114 cmd = ' '.join(args[1:])
1115 try:
1116 os.system(cmd)
1117 except KeyboardInterrupt:
1118 # to allow shell command interruption
1119 pass
1120 return 0
1121
1122
1123def connectCmd(ctx, args):
1124 if (len(args) > 4):
1125 print "usage: connect [url] [username] [passwd]"
1126 return 0
1127
1128 if ctx['vb'] is not None:
1129 print "Already connected, disconnect first..."
1130 return 0
1131
1132 if (len(args) > 1):
1133 url = args[1]
1134 else:
1135 url = None
1136
1137 if (len(args) > 2):
1138 user = args[2]
1139 else:
1140 user = ""
1141
1142 if (len(args) > 3):
1143 passwd = args[3]
1144 else:
1145 passwd = ""
1146
1147 vbox = ctx['global'].platform.connect(url, user, passwd)
1148 ctx['vb'] = vbox
1149 print "Running VirtualBox version %s" %(vbox.version)
1150 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1151 return 0
1152
1153def disconnectCmd(ctx, args):
1154 if (len(args) != 1):
1155 print "usage: disconnect"
1156 return 0
1157
1158 if ctx['vb'] is None:
1159 print "Not connected yet."
1160 return 0
1161
1162 try:
1163 ctx['global'].platform.disconnect()
1164 except:
1165 ctx['vb'] = None
1166 raise
1167
1168 ctx['vb'] = None
1169 return 0
1170
1171def exportVMCmd(ctx, args):
1172 import sys
1173
1174 if len(args) < 3:
1175 print "usage: exportVm <machine> <path> <format> <license>"
1176 return 0
1177 mach = ctx['machById'](args[1])
1178 if mach is None:
1179 return 0
1180 path = args[2]
1181 if (len(args) > 3):
1182 format = args[3]
1183 else:
1184 format = "ovf-1.0"
1185 if (len(args) > 4):
1186 license = args[4]
1187 else:
1188 license = "GPL"
1189
1190 app = ctx['vb'].createAppliance()
1191 desc = mach.export(app)
1192 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1193 p = app.write(format, path)
1194 progressBar(ctx, p)
1195 print "Exported to %s in format %s" %(path, format)
1196 return 0
1197
1198aliases = {'s':'start',
1199 'i':'info',
1200 'l':'list',
1201 'h':'help',
1202 'a':'alias',
1203 'q':'quit', 'exit':'quit',
1204 'v':'verbose'}
1205
1206commands = {'help':['Prints help information', helpCmd, 0],
1207 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
1208 'create':['Create virtual machine', createCmd, 0],
1209 'remove':['Remove virtual machine', removeCmd, 0],
1210 'pause':['Pause virtual machine', pauseCmd, 0],
1211 'resume':['Resume virtual machine', resumeCmd, 0],
1212 'save':['Save execution state of virtual machine', saveCmd, 0],
1213 'stats':['Stats for virtual machine', statsCmd, 0],
1214 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1215 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1216 'list':['Shows known virtual machines', listCmd, 0],
1217 'info':['Shows info on machine', infoCmd, 0],
1218 'alias':['Control aliases', aliasCmd, 0],
1219 'verbose':['Toggle verbosity', verboseCmd, 0],
1220 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1221 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1222 'quit':['Exits', quitCmd, 0],
1223 'host':['Show host information', hostCmd, 0],
1224 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
1225 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1226 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1227 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1228 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1229 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1230 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1231 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1232 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1233 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
1234 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1235 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd>', teleportCmd, 0],
1236 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
1237 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
1238 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
1239 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
1240 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
1241 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
1242 'unplugcpu':['Remove a CPU from a running VM: plugcpu Win 1', unplugcpuCmd, 0],
1243 }
1244
1245def runCommandArgs(ctx, args):
1246 c = args[0]
1247 if aliases.get(c, None) != None:
1248 c = aliases[c]
1249 ci = commands.get(c,None)
1250 if ci == None:
1251 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
1252 return 0
1253 return ci[1](ctx, args)
1254
1255
1256def runCommand(ctx, cmd):
1257 if len(cmd) == 0: return 0
1258 args = split_no_quotes(cmd)
1259 if len(args) == 0: return 0
1260 return runCommandArgs(ctx, args)
1261
1262#
1263# To write your own custom commands to vboxshell, create
1264# file ~/.VirtualBox/shellext.py with content like
1265#
1266# def runTestCmd(ctx, args):
1267# print "Testy test", ctx['vb']
1268# return 0
1269#
1270# commands = {
1271# 'test': ['Test help', runTestCmd]
1272# }
1273# and issue reloadExt shell command.
1274# This file also will be read automatically on startup or 'reloadExt'.
1275#
1276# Also one can put shell extensions into ~/.VirtualBox/shexts and
1277# they will also be picked up, so this way one can exchange
1278# shell extensions easily.
1279def addExtsFromFile(ctx, cmds, file):
1280 if not os.path.isfile(file):
1281 return
1282 d = {}
1283 try:
1284 execfile(file, d, d)
1285 for (k,v) in d['commands'].items():
1286 if g_verbose:
1287 print "customize: adding \"%s\" - %s" %(k, v[0])
1288 cmds[k] = [v[0], v[1], file]
1289 except:
1290 print "Error loading user extensions from %s" %(file)
1291 traceback.print_exc()
1292
1293
1294def checkUserExtensions(ctx, cmds, folder):
1295 folder = str(folder)
1296 name = os.path.join(folder, "shellext.py")
1297 addExtsFromFile(ctx, cmds, name)
1298 # also check 'exts' directory for all files
1299 shextdir = os.path.join(folder, "shexts")
1300 if not os.path.isdir(shextdir):
1301 return
1302 exts = os.listdir(shextdir)
1303 for e in exts:
1304 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
1305
1306def getHomeFolder(ctx):
1307 if ctx['remote'] or ctx['vb'] is None:
1308 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
1309 else:
1310 return ctx['vb'].homeFolder
1311
1312def interpret(ctx):
1313 if ctx['remote']:
1314 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
1315 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
1316
1317 vbox = ctx['vb']
1318
1319 if vbox is not None:
1320 print "Running VirtualBox version %s" %(vbox.version)
1321 ctx['perf'] = ctx['global'].getPerfCollector(vbox)
1322 else:
1323 ctx['perf'] = None
1324
1325 home = getHomeFolder(ctx)
1326 checkUserExtensions(ctx, commands, home)
1327
1328 autoCompletion(commands, ctx)
1329
1330 # to allow to print actual host information, we collect info for
1331 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
1332 if ctx['perf']:
1333 try:
1334 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
1335 except:
1336 pass
1337
1338 while True:
1339 try:
1340 cmd = raw_input("vbox> ")
1341 done = runCommand(ctx, cmd)
1342 if done != 0: break
1343 except KeyboardInterrupt:
1344 print '====== You can type quit or q to leave'
1345 break
1346 except EOFError:
1347 break;
1348 except Exception,e:
1349 print e
1350 if g_verbose:
1351 traceback.print_exc()
1352 ctx['global'].waitForEvents(0)
1353 try:
1354 # There is no need to disable metric collection. This is just an example.
1355 if ct['perf']:
1356 ctx['perf'].disable(['*'], [vbox.host])
1357 except:
1358 pass
1359
1360def runCommandCb(ctx, cmd, args):
1361 args.insert(0, cmd)
1362 return runCommandArgs(ctx, args)
1363
1364def main(argv):
1365 style = None
1366 autopath = False
1367 argv.pop(0)
1368 while len(argv) > 0:
1369 if argv[0] == "-w":
1370 style = "WEBSERVICE"
1371 if argv[0] == "-a":
1372 autopath = True
1373 argv.pop(0)
1374
1375 if autopath:
1376 cwd = os.getcwd()
1377 vpp = os.environ.get("VBOX_PROGRAM_PATH")
1378 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
1379 vpp = cwd
1380 print "Autodetected VBOX_PROGRAM_PATH as",vpp
1381 os.environ["VBOX_PROGRAM_PATH"] = cwd
1382 sys.path.append(os.path.join(vpp, "sdk", "installer"))
1383
1384 from vboxapi import VirtualBoxManager
1385 g_virtualBoxManager = VirtualBoxManager(style, None)
1386 ctx = {'global':g_virtualBoxManager,
1387 'mgr':g_virtualBoxManager.mgr,
1388 'vb':g_virtualBoxManager.vbox,
1389 'ifaces':g_virtualBoxManager.constants,
1390 'remote':g_virtualBoxManager.remote,
1391 'type':g_virtualBoxManager.type,
1392 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1393 'machById': lambda id: machById(ctx,id),
1394 'argsToMach': lambda args: argsToMach(ctx,args),
1395 'progressBar': lambda p: progressBar(ctx,p),
1396 '_machlist':None
1397 }
1398 interpret(ctx)
1399 g_virtualBoxManager.deinit()
1400 del g_virtualBoxManager
1401
1402if __name__ == '__main__':
1403 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