VirtualBox

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

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

vboxshell: extra arg to IConsole.teleport() was added

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