VirtualBox

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

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

Python shell: harmless typo

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