VirtualBox

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

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

python shell: bits

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 61.2 KB
Line 
1#!/usr/bin/python
2#
3# Copyright (C) 2009-2010 Sun Microsystems, Inc.
4#
5# This file is part of VirtualBox Open Source Edition (OSE), as
6# available from http://www.215389.xyz. 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, supports TAB-completion and #
23# history if you have Python readline installed. #
24# #
25# Finally, shell allows arbitrary custom extensions, just create #
26# .VirtualBox/shexts/ and drop your extensions there. #
27# Enjoy. #
28################################################################################
29
30import os,sys
31import traceback
32import shlex
33import time
34
35# Simple implementation of IConsoleCallback, one can use it as skeleton
36# for custom implementations
37class GuestMonitor:
38 def __init__(self, mach):
39 self.mach = mach
40
41 def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
42 print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
43 def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
44 print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, needsHostCursor)
45
46 def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
47 print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
48
49 def onStateChange(self, state):
50 print "%s: onStateChange state=%d" %(self.mach.name, state)
51
52 def onAdditionsStateChange(self):
53 print "%s: onAdditionsStateChange" %(self.mach.name)
54
55 def onNetworkAdapterChange(self, adapter):
56 print "%s: onNetworkAdapterChange" %(self.mach.name)
57
58 def onSerialPortChange(self, port):
59 print "%s: onSerialPortChange" %(self.mach.name)
60
61 def onParallelPortChange(self, port):
62 print "%s: onParallelPortChange" %(self.mach.name)
63
64 def onStorageControllerChange(self):
65 print "%s: onStorageControllerChange" %(self.mach.name)
66
67 def onMediumChange(self, attachment):
68 print "%s: onMediumChange" %(self.mach.name)
69
70 def onVRDPServerChange(self):
71 print "%s: onVRDPServerChange" %(self.mach.name)
72
73 def onUSBControllerChange(self):
74 print "%s: onUSBControllerChange" %(self.mach.name)
75
76 def onUSBDeviceStateChange(self, device, attached, error):
77 print "%s: onUSBDeviceStateChange" %(self.mach.name)
78
79 def onSharedFolderChange(self, scope):
80 print "%s: onSharedFolderChange" %(self.mach.name)
81
82 def onRuntimeError(self, fatal, id, message):
83 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
84
85 def onCanShowWindow(self):
86 print "%s: onCanShowWindow" %(self.mach.name)
87 return True
88
89 def onShowWindow(self, winId):
90 print "%s: onShowWindow: %d" %(self.mach.name, winId)
91
92class VBoxMonitor:
93 def __init__(self, params):
94 self.vbox = params[0]
95 self.isMscom = params[1]
96 pass
97
98 def onMachineStateChange(self, id, state):
99 print "onMachineStateChange: %s %d" %(id, state)
100
101 def onMachineDataChange(self,id):
102 print "onMachineDataChange: %s" %(id)
103
104 def onExtraDataCanChange(self, id, key, value):
105 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
106 # Witty COM bridge thinks if someone wishes to return tuple, hresult
107 # is one of values we want to return
108 if self.isMscom:
109 return "", 0, True
110 else:
111 return True, ""
112
113 def onExtraDataChange(self, id, key, value):
114 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
115
116 def onMediaRegistered(self, id, type, registered):
117 print "onMediaRegistered: %s" %(id)
118
119 def onMachineRegistered(self, id, registred):
120 print "onMachineRegistered: %s" %(id)
121
122 def onSessionStateChange(self, id, state):
123 print "onSessionStateChange: %s %d" %(id, state)
124
125 def onSnapshotTaken(self, mach, id):
126 print "onSnapshotTaken: %s %s" %(mach, id)
127
128 def onSnapshotDeleted(self, mach, id):
129 print "onSnapshotDeleted: %s %s" %(mach, id)
130
131 def onSnapshotChange(self, mach, id):
132 print "onSnapshotChange: %s %s" %(mach, id)
133
134 def onGuestPropertyChange(self, id, name, newValue, flags):
135 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
136
137g_hasreadline = 1
138try:
139 import readline
140 import rlcompleter
141except:
142 g_hasreadline = 0
143
144
145if g_hasreadline:
146 class CompleterNG(rlcompleter.Completer):
147 def __init__(self, dic, ctx):
148 self.ctx = ctx
149 return rlcompleter.Completer.__init__(self,dic)
150
151 def complete(self, text, state):
152 """
153 taken from:
154 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
155 """
156 if text == "":
157 return ['\t',None][state]
158 else:
159 return rlcompleter.Completer.complete(self,text,state)
160
161 def global_matches(self, text):
162 """
163 Compute matches when text is a simple name.
164 Return a list of all names currently defined
165 in self.namespace that match.
166 """
167
168 matches = []
169 n = len(text)
170
171 for list in [ self.namespace ]:
172 for word in list:
173 if word[:n] == text:
174 matches.append(word)
175
176
177 try:
178 for m in getMachines(self.ctx):
179 # although it has autoconversion, we need to cast
180 # explicitly for subscripts to work
181 word = str(m.name)
182 if word[:n] == text:
183 matches.append(word)
184 word = str(m.id)
185 if word[0] == '{':
186 word = word[1:-1]
187 if word[:n] == text:
188 matches.append(word)
189 except Exception,e:
190 traceback.print_exc()
191 print e
192
193 return matches
194
195
196def autoCompletion(commands, ctx):
197 import platform
198 if not g_hasreadline:
199 return
200
201 comps = {}
202 for (k,v) in commands.items():
203 comps[k] = None
204 completer = CompleterNG(comps, ctx)
205 readline.set_completer(completer.complete)
206 # OSX need it
207 if platform.system() == 'Darwin':
208 readline.parse_and_bind ("bind ^I rl_complete")
209 readline.parse_and_bind("tab: complete")
210
211g_verbose = True
212
213def split_no_quotes(s):
214 return shlex.split(s)
215
216def progressBar(ctx,p,wait=1000):
217 try:
218 while not p.completed:
219 print "%d %%\r" %(p.percent),
220 sys.stdout.flush()
221 p.waitForCompletion(wait)
222 ctx['global'].waitForEvents(0)
223 except KeyboardInterrupt:
224 print "Interrupted."
225
226
227def reportError(ctx,session,rc):
228 if not ctx['remote']:
229 print session.QueryErrorObject(rc)
230
231
232def createVm(ctx,name,kind,base):
233 mgr = ctx['mgr']
234 vb = ctx['vb']
235 mach = vb.createMachine(name, kind, base, "", False)
236 mach.saveSettings()
237 print "created machine with UUID",mach.id
238 vb.registerMachine(mach)
239 # update cache
240 getMachines(ctx, True)
241
242def removeVm(ctx,mach):
243 mgr = ctx['mgr']
244 vb = ctx['vb']
245 id = mach.id
246 print "removing machine ",mach.name,"with UUID",id
247 cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
248 mach = vb.unregisterMachine(id)
249 if mach:
250 mach.deleteSettings()
251 # update cache
252 getMachines(ctx, True)
253
254def startVm(ctx,mach,type):
255 mgr = ctx['mgr']
256 vb = ctx['vb']
257 perf = ctx['perf']
258 session = mgr.getSessionObject(vb)
259 uuid = mach.id
260 progress = vb.openRemoteSession(session, uuid, type, "")
261 progressBar(ctx, progress, 100)
262 completed = progress.completed
263 rc = int(progress.resultCode)
264 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
265 if rc == 0:
266 # we ignore exceptions to allow starting VM even if
267 # perf collector cannot be started
268 if perf:
269 try:
270 perf.setup(['*'], [mach], 10, 15)
271 except Exception,e:
272 print e
273 if g_verbose:
274 traceback.print_exc()
275 # if session not opened, close doesn't make sense
276 session.close()
277 else:
278 reportError(ctx,session,rc)
279
280def getMachines(ctx, invalidate = False):
281 if ctx['vb'] is not None:
282 if ctx['_machlist'] is None or invalidate:
283 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
284 return ctx['_machlist']
285 else:
286 return []
287
288def asState(var):
289 if var:
290 return 'on'
291 else:
292 return 'off'
293
294def asFlag(var):
295 if var:
296 return 'yes'
297 else:
298 return 'no'
299
300def perfStats(ctx,mach):
301 if not ctx['perf']:
302 return
303 for metric in ctx['perf'].query(["*"], [mach]):
304 print metric['name'], metric['values_as_string']
305
306def guestExec(ctx, machine, console, cmds):
307 exec cmds
308
309def monitorGuest(ctx, machine, console, dur):
310 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
311 console.registerCallback(cb)
312 if dur == -1:
313 # not infinity, but close enough
314 dur = 100000
315 try:
316 end = time.time() + dur
317 while time.time() < end:
318 ctx['global'].waitForEvents(500)
319 # We need to catch all exceptions here, otherwise callback will never be unregistered
320 except:
321 pass
322 console.unregisterCallback(cb)
323
324
325def monitorVBox(ctx, dur):
326 vbox = ctx['vb']
327 isMscom = (ctx['global'].type == 'MSCOM')
328 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
329 vbox.registerCallback(cb)
330 if dur == -1:
331 # not infinity, but close enough
332 dur = 100000
333 try:
334 end = time.time() + dur
335 while time.time() < end:
336 ctx['global'].waitForEvents(500)
337 # We need to catch all exceptions here, otherwise callback will never be unregistered
338 except:
339 pass
340 vbox.unregisterCallback(cb)
341
342
343def takeScreenshot(ctx,console,args):
344 from PIL import Image
345 display = console.display
346 if len(args) > 0:
347 f = args[0]
348 else:
349 f = "/tmp/screenshot.png"
350 if len(args) > 3:
351 screen = int(args[3])
352 else:
353 screen = 0
354 (fb,xorig,yorig) = display.getFramebuffer(screen)
355 if len(args) > 1:
356 w = int(args[1])
357 else:
358 w = fb.width
359 if len(args) > 2:
360 h = int(args[2])
361 else:
362 h = fb.height
363
364 print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
365 data = display.takeScreenShotToArray(screen, w,h)
366 size = (w,h)
367 mode = "RGBA"
368 im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
369 im.save(f, "PNG")
370
371
372def teleport(ctx,session,console,args):
373 if args[0].find(":") == -1:
374 print "Use host:port format for teleport target"
375 return
376 (host,port) = args[0].split(":")
377 if len(args) > 1:
378 passwd = args[1]
379 else:
380 passwd = ""
381
382 if len(args) > 2:
383 maxDowntime = int(args[2])
384 else:
385 maxDowntime = 250
386
387 port = int(port)
388 print "Teleporting to %s:%d..." %(host,port)
389 progress = console.teleport(host, port, passwd, maxDowntime)
390 progressBar(ctx, progress, 100)
391 completed = progress.completed
392 rc = int(progress.resultCode)
393 if rc == 0:
394 print "Success!"
395 else:
396 reportError(ctx,session,rc)
397
398
399def guestStats(ctx,console,args):
400 guest = console.guest
401 # we need to set up guest statistics
402 if len(args) > 0 :
403 update = args[0]
404 else:
405 update = 1
406 if guest.statisticsUpdateInterval != update:
407 guest.statisticsUpdateInterval = update
408 try:
409 time.sleep(float(update)+0.1)
410 except:
411 # to allow sleep interruption
412 pass
413 all_stats = ctx['ifaces'].all_values('GuestStatisticType')
414 cpu = 0
415 for s in all_stats.keys():
416 try:
417 val = guest.getStatistic( cpu, all_stats[s])
418 print "%s: %d" %(s, val)
419 except:
420 # likely not implemented
421 pass
422
423def plugCpu(ctx,machine,session,args):
424 cpu = int(args[0])
425 print "Adding CPU %d..." %(cpu)
426 machine.hotPlugCPU(cpu)
427
428def unplugCpu(ctx,machine,session,args):
429 cpu = int(args[0])
430 print "Removing CPU %d..." %(cpu)
431 machine.hotUnplugCPU(cpu)
432
433def mountIso(ctx,machine,session,args):
434 machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
435 machine.saveSettings()
436
437def ginfo(ctx,console, args):
438 guest = console.guest
439 if guest.additionsActive:
440 vers = int(guest.additionsVersion)
441 print "Additions active, version %d.%d" %(vers >> 16, vers & 0xffff)
442 print "Support seamless: %s" %(asFlag(guest.supportsSeamless))
443 print "Support graphics: %s" %(asFlag(guest.supportsGraphics))
444 print "Baloon size: %d" %(guest.memoryBalloonSize)
445 print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
446 else:
447 print "No additions"
448
449def cmdExistingVm(ctx,mach,cmd,args):
450 mgr=ctx['mgr']
451 vb=ctx['vb']
452 session = mgr.getSessionObject(vb)
453 uuid = mach.id
454 try:
455 progress = vb.openExistingSession(session, uuid)
456 except Exception,e:
457 print "Session to '%s' not open: %s" %(mach.name,e)
458 if g_verbose:
459 traceback.print_exc()
460 return
461 if str(session.state) != str(ctx['ifaces'].SessionState_Open):
462 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
463 return
464 # this could be an example how to handle local only (i.e. unavailable
465 # in Webservices) functionality
466 if ctx['remote'] and cmd == 'some_local_only_command':
467 print 'Trying to use local only functionality, ignored'
468 return
469 console=session.console
470 ops={'pause': lambda: console.pause(),
471 'resume': lambda: console.resume(),
472 'powerdown': lambda: console.powerDown(),
473 'powerbutton': lambda: console.powerButton(),
474 'stats': lambda: perfStats(ctx, mach),
475 'guest': lambda: guestExec(ctx, mach, console, args),
476 'ginfo': lambda: ginfo(ctx, console, args),
477 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
478 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
479 'save': lambda: progressBar(ctx,console.saveState()),
480 'screenshot': lambda: takeScreenshot(ctx,console,args),
481 'teleport': lambda: teleport(ctx,session,console,args),
482 'gueststats': lambda: guestStats(ctx, console, args),
483 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
484 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
485 'mountiso': lambda: mountIso(ctx, session.machine, session, args)
486 }
487 try:
488 ops[cmd]()
489 except Exception, e:
490 print 'failed: ',e
491 if g_verbose:
492 traceback.print_exc()
493
494 session.close()
495
496
497def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
498 session = ctx['global'].openMachineSession(mach.id)
499 mach = session.machine
500 try:
501 cmd(ctx, mach, args)
502 except Exception, e:
503 print 'failed: ',e
504 if g_verbose:
505 traceback.print_exc()
506 if save:
507 mach.saveSettings()
508 session.close()
509
510def machById(ctx,id):
511 mach = None
512 for m in getMachines(ctx):
513 if m.name == id:
514 mach = m
515 break
516 mid = str(m.id)
517 if mid[0] == '{':
518 mid = mid[1:-1]
519 if mid == id:
520 mach = m
521 break
522 return mach
523
524def argsToMach(ctx,args):
525 if len(args) < 2:
526 print "usage: %s [vmname|uuid]" %(args[0])
527 return None
528 id = args[1]
529 m = machById(ctx, id)
530 if m == None:
531 print "Machine '%s' is unknown, use list command to find available machines" %(id)
532 return m
533
534def helpSingleCmd(cmd,h,sp):
535 if sp != 0:
536 spec = " [ext from "+sp+"]"
537 else:
538 spec = ""
539 print " %s: %s%s" %(cmd,h,spec)
540
541def helpCmd(ctx, args):
542 if len(args) == 1:
543 print "Help page:"
544 names = commands.keys()
545 names.sort()
546 for i in names:
547 helpSingleCmd(i, commands[i][0], commands[i][2])
548 else:
549 cmd = args[1]
550 c = commands.get(cmd)
551 if c == None:
552 print "Command '%s' not known" %(cmd)
553 else:
554 helpSingleCmd(cmd, c[0], c[2])
555 return 0
556
557def asEnumElem(ctx,enum,elem):
558 all = ctx['ifaces'].all_values(enum)
559 for e in all.keys():
560 if str(elem) == str(all[e]):
561 return e
562 return "<unknown>"
563
564def enumFromString(ctx,enum,str):
565 all = ctx['ifaces'].all_values(enum)
566 return all.get(str, None)
567
568def listCmd(ctx, args):
569 for m in getMachines(ctx, True):
570 if m.teleporterEnabled:
571 tele = "[T] "
572 else:
573 tele = " "
574 print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,asEnumElem(ctx,"SessionState", m.sessionState))
575 return 0
576
577def infoCmd(ctx,args):
578 if (len(args) < 2):
579 print "usage: info [vmname|uuid]"
580 return 0
581 mach = argsToMach(ctx,args)
582 if mach == None:
583 return 0
584 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
585 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
586 print " Name [name]: %s" %(mach.name)
587 print " Description [description]: %s" %(mach.description)
588 print " ID [n/a]: %s" %(mach.id)
589 print " OS Type [via OSTypeId]: %s" %(os.description)
590 print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
591 print
592 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
593 print " RAM [memorySize]: %dM" %(mach.memorySize)
594 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
595 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
596 print
597 print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
598 print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
599 print
600 if mach.teleporterEnabled:
601 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
602 print
603 bios = mach.BIOSSettings
604 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
605 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
606 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
607 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
608 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
609 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
610 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
611 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
612
613 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
614 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
615
616 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
617 if mach.audioAdapter.enabled:
618 print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
619 if mach.USBController.enabled:
620 print " USB [via USBController]: high speed %s" %(asState(mach.USBController.enabledEhci))
621 print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
622
623 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
624 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
625 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
626 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
627
628 controllers = ctx['global'].getArray(mach, 'storageControllers')
629 if controllers:
630 print
631 print " Controllers:"
632 for controller in controllers:
633 print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
634
635 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
636 if attaches:
637 print
638 print " Mediums:"
639 for a in attaches:
640 print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
641 m = a.medium
642 if a.type == ctx['global'].constants.DeviceType_HardDisk:
643 print " HDD:"
644 print " Id: %s" %(m.id)
645 print " Location: %s" %(m.location)
646 print " Name: %s" %(m.name)
647 print " Format: %s" %(m.format)
648
649 if a.type == ctx['global'].constants.DeviceType_DVD:
650 print " DVD:"
651 if m:
652 print " Id: %s" %(m.id)
653 print " Name: %s" %(m.name)
654 if m.hostDrive:
655 print " Host DVD %s" %(m.location)
656 if a.passthrough:
657 print " [passthrough mode]"
658 else:
659 print " Virtual image at %s" %(m.location)
660 print " Size: %s" %(m.size)
661
662 if a.type == ctx['global'].constants.DeviceType_Floppy:
663 print " Floppy:"
664 if m:
665 print " Id: %s" %(m.id)
666 print " Name: %s" %(m.name)
667 if m.hostDrive:
668 print " Host floppy %s" %(m.location)
669 else:
670 print " Virtual image at %s" %(m.location)
671 print " Size: %s" %(m.size)
672
673 return 0
674
675def startCmd(ctx, args):
676 mach = argsToMach(ctx,args)
677 if mach == None:
678 return 0
679 if len(args) > 2:
680 type = args[2]
681 else:
682 type = "gui"
683 startVm(ctx, mach, type)
684 return 0
685
686def createVmCmd(ctx, args):
687 if (len(args) < 3 or len(args) > 4):
688 print "usage: createvm name ostype <basefolder>"
689 return 0
690 name = args[1]
691 oskind = args[2]
692 if len(args) == 4:
693 base = args[3]
694 else:
695 base = ''
696 try:
697 ctx['vb'].getGuestOSType(oskind)
698 except Exception, e:
699 print 'Unknown OS type:',oskind
700 return 0
701 createVm(ctx, name, oskind, base)
702 return 0
703
704def ginfoCmd(ctx,args):
705 if (len(args) < 2):
706 print "usage: ginfo [vmname|uuid]"
707 return 0
708 mach = argsToMach(ctx,args)
709 if mach == None:
710 return 0
711 cmdExistingVm(ctx, mach, 'ginfo', '')
712 return 0
713
714def execInGuest(ctx,console,args):
715 if len(args) < 1:
716 print "exec in guest needs at least program name"
717 return
718 user = ""
719 passwd = ""
720 tmo = 0
721 print "executing %s with %s" %(args[0], args[1:])
722 (progress, pid) = console.guest.executeProcess(args[0], 0, args[1:], [], "", "", "", user, passwd, tmo)
723 print "executed with pid %d" %(pid)
724
725def gexecCmd(ctx,args):
726 if (len(args) < 2):
727 print "usage: gexec [vmname|uuid] command args"
728 return 0
729 mach = argsToMach(ctx,args)
730 if mach == None:
731 return 0
732 gargs = args[2:]
733 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args))
734 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
735 return 0
736
737def removeVmCmd(ctx, args):
738 mach = argsToMach(ctx,args)
739 if mach == None:
740 return 0
741 removeVm(ctx, mach)
742 return 0
743
744def pauseCmd(ctx, args):
745 mach = argsToMach(ctx,args)
746 if mach == None:
747 return 0
748 cmdExistingVm(ctx, mach, 'pause', '')
749 return 0
750
751def powerdownCmd(ctx, args):
752 mach = argsToMach(ctx,args)
753 if mach == None:
754 return 0
755 cmdExistingVm(ctx, mach, 'powerdown', '')
756 return 0
757
758def powerbuttonCmd(ctx, args):
759 mach = argsToMach(ctx,args)
760 if mach == None:
761 return 0
762 cmdExistingVm(ctx, mach, 'powerbutton', '')
763 return 0
764
765def resumeCmd(ctx, args):
766 mach = argsToMach(ctx,args)
767 if mach == None:
768 return 0
769 cmdExistingVm(ctx, mach, 'resume', '')
770 return 0
771
772def saveCmd(ctx, args):
773 mach = argsToMach(ctx,args)
774 if mach == None:
775 return 0
776 cmdExistingVm(ctx, mach, 'save', '')
777 return 0
778
779def statsCmd(ctx, args):
780 mach = argsToMach(ctx,args)
781 if mach == None:
782 return 0
783 cmdExistingVm(ctx, mach, 'stats', '')
784 return 0
785
786def guestCmd(ctx, args):
787 if (len(args) < 3):
788 print "usage: guest name commands"
789 return 0
790 mach = argsToMach(ctx,args)
791 if mach == None:
792 return 0
793 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
794 return 0
795
796def screenshotCmd(ctx, args):
797 if (len(args) < 2):
798 print "usage: screenshot vm <file> <width> <height> <monitor>"
799 return 0
800 mach = argsToMach(ctx,args)
801 if mach == None:
802 return 0
803 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
804 return 0
805
806def teleportCmd(ctx, args):
807 if (len(args) < 3):
808 print "usage: teleport name host:port <password>"
809 return 0
810 mach = argsToMach(ctx,args)
811 if mach == None:
812 return 0
813 cmdExistingVm(ctx, mach, 'teleport', args[2:])
814 return 0
815
816def portalsettings(ctx,mach,args):
817 enabled = args[0]
818 mach.teleporterEnabled = enabled
819 if enabled:
820 port = args[1]
821 passwd = args[2]
822 mach.teleporterPort = port
823 mach.teleporterPassword = passwd
824
825def openportalCmd(ctx, args):
826 if (len(args) < 3):
827 print "usage: openportal name port <password>"
828 return 0
829 mach = argsToMach(ctx,args)
830 if mach == None:
831 return 0
832 port = int(args[2])
833 if (len(args) > 3):
834 passwd = args[3]
835 else:
836 passwd = ""
837 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
838 cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
839 startVm(ctx, mach, "gui")
840 return 0
841
842def closeportalCmd(ctx, args):
843 if (len(args) < 2):
844 print "usage: closeportal name"
845 return 0
846 mach = argsToMach(ctx,args)
847 if mach == None:
848 return 0
849 if mach.teleporterEnabled:
850 cmdClosedVm(ctx, mach, portalsettings, [False])
851 return 0
852
853def gueststatsCmd(ctx, args):
854 if (len(args) < 2):
855 print "usage: gueststats name <check interval>"
856 return 0
857 mach = argsToMach(ctx,args)
858 if mach == None:
859 return 0
860 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
861 return 0
862
863def plugcpu(ctx,mach,args):
864 plug = args[0]
865 cpu = args[1]
866 if plug:
867 print "Adding CPU %d..." %(cpu)
868 mach.hotPlugCPU(cpu)
869 else:
870 print "Removing CPU %d..." %(cpu)
871 mach.hotUnplugCPU(cpu)
872
873def plugcpuCmd(ctx, args):
874 if (len(args) < 2):
875 print "usage: plugcpu name cpuid"
876 return 0
877 mach = argsToMach(ctx,args)
878 if mach == None:
879 return 0
880 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
881 if mach.CPUHotPlugEnabled:
882 cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
883 else:
884 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
885 return 0
886
887def unplugcpuCmd(ctx, args):
888 if (len(args) < 2):
889 print "usage: unplugcpu name cpuid"
890 return 0
891 mach = argsToMach(ctx,args)
892 if mach == None:
893 return 0
894 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
895 if mach.CPUHotPlugEnabled:
896 cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
897 else:
898 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
899 return 0
900
901def setvar(ctx,mach,args):
902 expr = 'mach.'+args[0]+' = '+args[1]
903 print "Executing",expr
904 exec expr
905
906def setvarCmd(ctx, args):
907 if (len(args) < 4):
908 print "usage: setvar [vmname|uuid] expr value"
909 return 0
910 mach = argsToMach(ctx,args)
911 if mach == None:
912 return 0
913 cmdClosedVm(ctx, mach, setvar, args[2:])
914 return 0
915
916def setvmextra(ctx,mach,args):
917 key = args[0]
918 value = args[1]
919 print "%s: setting %s to %s" %(mach.name, key, value)
920 mach.setExtraData(key, value)
921
922def setExtraDataCmd(ctx, args):
923 if (len(args) < 3):
924 print "usage: setextra [vmname|uuid|global] key <value>"
925 return 0
926 key = args[2]
927 if len(args) == 4:
928 value = args[3]
929 else:
930 value = None
931 if args[1] == 'global':
932 ctx['vb'].setExtraData(key, value)
933 return 0
934
935 mach = argsToMach(ctx,args)
936 if mach == None:
937 return 0
938 cmdClosedVm(ctx, mach, setvmextra, [key, value])
939 return 0
940
941def printExtraKey(obj, key, value):
942 print "%s: '%s' = '%s'" %(obj, key, value)
943
944def getExtraDataCmd(ctx, args):
945 if (len(args) < 2):
946 print "usage: getextra [vmname|uuid|global] <key>"
947 return 0
948 if len(args) == 3:
949 key = args[2]
950 else:
951 key = None
952
953 if args[1] == 'global':
954 obj = ctx['vb']
955 else:
956 obj = argsToMach(ctx,args)
957 if obj == None:
958 return 0
959
960 if key == None:
961 keys = obj.getExtraDataKeys()
962 else:
963 keys = [ key ]
964 for k in keys:
965 printExtraKey(args[1], k, obj.getExtraData(k))
966
967 return 0
968
969def quitCmd(ctx, args):
970 return 1
971
972def aliasCmd(ctx, args):
973 if (len(args) == 3):
974 aliases[args[1]] = args[2]
975 return 0
976
977 for (k,v) in aliases.items():
978 print "'%s' is an alias for '%s'" %(k,v)
979 return 0
980
981def verboseCmd(ctx, args):
982 global g_verbose
983 g_verbose = not g_verbose
984 return 0
985
986def getUSBStateString(state):
987 if state == 0:
988 return "NotSupported"
989 elif state == 1:
990 return "Unavailable"
991 elif state == 2:
992 return "Busy"
993 elif state == 3:
994 return "Available"
995 elif state == 4:
996 return "Held"
997 elif state == 5:
998 return "Captured"
999 else:
1000 return "Unknown"
1001
1002def hostCmd(ctx, args):
1003 host = ctx['vb'].host
1004 cnt = host.processorCount
1005 print "Processors available/online: %d/%d " %(cnt,host.processorOnlineCount)
1006 for i in range(0,cnt):
1007 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
1008
1009 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
1010 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
1011 if host.Acceleration3DAvailable:
1012 print "3D acceleration available"
1013 else:
1014 print "3D acceleration NOT available"
1015
1016 print "Network interfaces:"
1017 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
1018 print " %s (%s)" %(ni.name, ni.IPAddress)
1019
1020 print "DVD drives:"
1021 for dd in ctx['global'].getArray(host, 'DVDDrives'):
1022 print " %s - %s" %(dd.name, dd.description)
1023
1024 print "Floppy drives:"
1025 for dd in ctx['global'].getArray(host, 'floppyDrives'):
1026 print " %s - %s" %(dd.name, dd.description)
1027
1028 print "USB devices:"
1029 for ud in ctx['global'].getArray(host, 'USBDevices'):
1030 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
1031
1032 if ctx['perf']:
1033 for metric in ctx['perf'].query(["*"], [host]):
1034 print metric['name'], metric['values_as_string']
1035
1036 return 0
1037
1038def monitorGuestCmd(ctx, args):
1039 if (len(args) < 2):
1040 print "usage: monitorGuest name (duration)"
1041 return 0
1042 mach = argsToMach(ctx,args)
1043 if mach == None:
1044 return 0
1045 dur = 5
1046 if len(args) > 2:
1047 dur = float(args[2])
1048 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1049 return 0
1050
1051def monitorVBoxCmd(ctx, args):
1052 if (len(args) > 2):
1053 print "usage: monitorVBox (duration)"
1054 return 0
1055 dur = 5
1056 if len(args) > 1:
1057 dur = float(args[1])
1058 monitorVBox(ctx, dur)
1059 return 0
1060
1061def getAdapterType(ctx, type):
1062 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1063 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1064 return "pcnet"
1065 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1066 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1067 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1068 return "e1000"
1069 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1070 return "virtio"
1071 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1072 return None
1073 else:
1074 raise Exception("Unknown adapter type: "+type)
1075
1076
1077def portForwardCmd(ctx, args):
1078 if (len(args) != 5):
1079 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1080 return 0
1081 mach = argsToMach(ctx,args)
1082 if mach == None:
1083 return 0
1084 adapterNum = int(args[2])
1085 hostPort = int(args[3])
1086 guestPort = int(args[4])
1087 proto = "TCP"
1088 session = ctx['global'].openMachineSession(mach.id)
1089 mach = session.machine
1090
1091 adapter = mach.getNetworkAdapter(adapterNum)
1092 adapterType = getAdapterType(ctx, adapter.adapterType)
1093
1094 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1095 config = "VBoxInternal/Devices/" + adapterType + "/"
1096 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1097
1098 mach.setExtraData(config + "/Protocol", proto)
1099 mach.setExtraData(config + "/HostPort", str(hostPort))
1100 mach.setExtraData(config + "/GuestPort", str(guestPort))
1101
1102 mach.saveSettings()
1103 session.close()
1104
1105 return 0
1106
1107
1108def showLogCmd(ctx, args):
1109 if (len(args) < 2):
1110 print "usage: showLog <vm> <num>"
1111 return 0
1112 mach = argsToMach(ctx,args)
1113 if mach == None:
1114 return 0
1115
1116 log = 0;
1117 if (len(args) > 2):
1118 log = args[2];
1119
1120 uOffset = 0;
1121 while True:
1122 data = mach.readLog(log, uOffset, 1024*1024)
1123 if (len(data) == 0):
1124 break
1125 # print adds either NL or space to chunks not ending with a NL
1126 sys.stdout.write(data)
1127 uOffset += len(data)
1128
1129 return 0
1130
1131def evalCmd(ctx, args):
1132 expr = ' '.join(args[1:])
1133 try:
1134 exec expr
1135 except Exception, e:
1136 print 'failed: ',e
1137 if g_verbose:
1138 traceback.print_exc()
1139 return 0
1140
1141def reloadExtCmd(ctx, args):
1142 # maybe will want more args smartness
1143 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1144 autoCompletion(commands, ctx)
1145 return 0
1146
1147
1148def runScriptCmd(ctx, args):
1149 if (len(args) != 2):
1150 print "usage: runScript <script>"
1151 return 0
1152 try:
1153 lf = open(args[1], 'r')
1154 except IOError,e:
1155 print "cannot open:",args[1], ":",e
1156 return 0
1157
1158 try:
1159 for line in lf:
1160 done = runCommand(ctx, line)
1161 if done != 0: break
1162 except Exception,e:
1163 print "error:",e
1164 if g_verbose:
1165 traceback.print_exc()
1166 lf.close()
1167 return 0
1168
1169def sleepCmd(ctx, args):
1170 if (len(args) != 2):
1171 print "usage: sleep <secs>"
1172 return 0
1173
1174 try:
1175 time.sleep(float(args[1]))
1176 except:
1177 # to allow sleep interrupt
1178 pass
1179 return 0
1180
1181
1182def shellCmd(ctx, args):
1183 if (len(args) < 2):
1184 print "usage: shell <commands>"
1185 return 0
1186 cmd = ' '.join(args[1:])
1187 try:
1188 os.system(cmd)
1189 except KeyboardInterrupt:
1190 # to allow shell command interruption
1191 pass
1192 return 0
1193
1194
1195def connectCmd(ctx, args):
1196 if (len(args) > 4):
1197 print "usage: connect [url] [username] [passwd]"
1198 return 0
1199
1200 if ctx['vb'] is not None:
1201 print "Already connected, disconnect first..."
1202 return 0
1203
1204 if (len(args) > 1):
1205 url = args[1]
1206 else:
1207 url = None
1208
1209 if (len(args) > 2):
1210 user = args[2]
1211 else:
1212 user = ""
1213
1214 if (len(args) > 3):
1215 passwd = args[3]
1216 else:
1217 passwd = ""
1218
1219 vbox = ctx['global'].platform.connect(url, user, passwd)
1220 ctx['vb'] = vbox
1221 print "Running VirtualBox version %s" %(vbox.version)
1222 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1223 return 0
1224
1225def disconnectCmd(ctx, args):
1226 if (len(args) != 1):
1227 print "usage: disconnect"
1228 return 0
1229
1230 if ctx['vb'] is None:
1231 print "Not connected yet."
1232 return 0
1233
1234 try:
1235 ctx['global'].platform.disconnect()
1236 except:
1237 ctx['vb'] = None
1238 raise
1239
1240 ctx['vb'] = None
1241 return 0
1242
1243def exportVMCmd(ctx, args):
1244 import sys
1245
1246 if len(args) < 3:
1247 print "usage: exportVm <machine> <path> <format> <license>"
1248 return 0
1249 mach = argsToMach(ctx,args)
1250 if mach is None:
1251 return 0
1252 path = args[2]
1253 if (len(args) > 3):
1254 format = args[3]
1255 else:
1256 format = "ovf-1.0"
1257 if (len(args) > 4):
1258 license = args[4]
1259 else:
1260 license = "GPL"
1261
1262 app = ctx['vb'].createAppliance()
1263 desc = mach.export(app)
1264 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1265 p = app.write(format, path)
1266 progressBar(ctx, p)
1267 print "Exported to %s in format %s" %(path, format)
1268 return 0
1269
1270# PC XT scancodes
1271scancodes = {
1272 'a': 0x1e,
1273 'b': 0x30,
1274 'c': 0x2e,
1275 'd': 0x20,
1276 'e': 0x12,
1277 'f': 0x21,
1278 'g': 0x22,
1279 'h': 0x23,
1280 'i': 0x17,
1281 'j': 0x24,
1282 'k': 0x25,
1283 'l': 0x26,
1284 'm': 0x32,
1285 'n': 0x31,
1286 'o': 0x18,
1287 'p': 0x19,
1288 'q': 0x10,
1289 'r': 0x13,
1290 's': 0x1f,
1291 't': 0x14,
1292 'u': 0x16,
1293 'v': 0x2f,
1294 'w': 0x11,
1295 'x': 0x2d,
1296 'y': 0x15,
1297 'z': 0x2c,
1298 '0': 0x0b,
1299 '1': 0x02,
1300 '2': 0x03,
1301 '3': 0x04,
1302 '4': 0x05,
1303 '5': 0x06,
1304 '6': 0x07,
1305 '7': 0x08,
1306 '8': 0x09,
1307 '9': 0x0a,
1308 ' ': 0x39,
1309 '-': 0xc,
1310 '=': 0xd,
1311 '[': 0x1a,
1312 ']': 0x1b,
1313 ';': 0x27,
1314 '\'': 0x28,
1315 ',': 0x33,
1316 '.': 0x34,
1317 '/': 0x35,
1318 '\t': 0xf,
1319 '\n': 0x1c,
1320 '`': 0x29
1321};
1322
1323extScancodes = {
1324 'ESC' : [0x01],
1325 'BKSP': [0xe],
1326 'SPACE': [0x39],
1327 'TAB': [0x0f],
1328 'CAPS': [0x3a],
1329 'ENTER': [0x1c],
1330 'LSHIFT': [0x2a],
1331 'RSHIFT': [0x36],
1332 'INS': [0xe0, 0x52],
1333 'DEL': [0xe0, 0x53],
1334 'END': [0xe0, 0x4f],
1335 'HOME': [0xe0, 0x47],
1336 'PGUP': [0xe0, 0x49],
1337 'PGDOWN': [0xe0, 0x51],
1338 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
1339 'RGUI': [0xe0, 0x5c],
1340 'LCTR': [0x1d],
1341 'RCTR': [0xe0, 0x1d],
1342 'LALT': [0x38],
1343 'RALT': [0xe0, 0x38],
1344 'APPS': [0xe0, 0x5d],
1345 'F1': [0x3b],
1346 'F2': [0x3c],
1347 'F3': [0x3d],
1348 'F4': [0x3e],
1349 'F5': [0x3f],
1350 'F6': [0x40],
1351 'F7': [0x41],
1352 'F8': [0x42],
1353 'F9': [0x43],
1354 'F10': [0x44 ],
1355 'F11': [0x57],
1356 'F12': [0x58],
1357 'UP': [0xe0, 0x48],
1358 'LEFT': [0xe0, 0x4b],
1359 'DOWN': [0xe0, 0x50],
1360 'RIGHT': [0xe0, 0x4d],
1361};
1362
1363def keyDown(ch):
1364 code = scancodes.get(ch, 0x0)
1365 if code != 0:
1366 return [code]
1367 extCode = extScancodes.get(ch, [])
1368 if len(extCode) == 0:
1369 print "bad ext",ch
1370 return extCode
1371
1372def keyUp(ch):
1373 codes = keyDown(ch)[:] # make a copy
1374 if len(codes) > 0:
1375 codes[len(codes)-1] += 0x80
1376 return codes
1377
1378def typeInGuest(console, text, delay):
1379 import time
1380 pressed = []
1381 group = False
1382 modGroupEnd = True
1383 i = 0
1384 while i < len(text):
1385 ch = text[i]
1386 i = i+1
1387 if ch == '{':
1388 # start group, all keys to be pressed at the same time
1389 group = True
1390 continue
1391 if ch == '}':
1392 # end group, release all keys
1393 for c in pressed:
1394 console.keyboard.putScancodes(keyUp(c))
1395 pressed = []
1396 group = False
1397 continue
1398 if ch == 'W':
1399 # just wait a bit
1400 time.sleep(0.3)
1401 continue
1402 if ch == '^' or ch == '|' or ch == '$' or ch == '_':
1403 if ch == '^':
1404 ch = 'LCTR'
1405 if ch == '|':
1406 ch = 'LSHIFT'
1407 if ch == '_':
1408 ch = 'LALT'
1409 if ch == '$':
1410 ch = 'LGUI'
1411 if not group:
1412 modGroupEnd = False
1413 else:
1414 if ch == '\\':
1415 if i < len(text):
1416 ch = text[i]
1417 i = i+1
1418 if ch == 'n':
1419 ch = '\n'
1420 elif ch == '&':
1421 combo = ""
1422 while i < len(text):
1423 ch = text[i]
1424 i = i+1
1425 if ch == ';':
1426 break
1427 combo += ch
1428 ch = combo
1429 modGroupEnd = True
1430 console.keyboard.putScancodes(keyDown(ch))
1431 pressed.insert(0, ch)
1432 if not group and modGroupEnd:
1433 for c in pressed:
1434 console.keyboard.putScancodes(keyUp(c))
1435 pressed = []
1436 modGroupEnd = True
1437 time.sleep(delay)
1438
1439def typeGuestCmd(ctx, args):
1440 import sys
1441
1442 if len(args) < 3:
1443 print "usage: typeGuest <machine> <text> <charDelay>"
1444 return 0
1445 mach = argsToMach(ctx,args)
1446 if mach is None:
1447 return 0
1448
1449 text = args[2]
1450
1451 if len(args) > 3:
1452 delay = float(args[3])
1453 else:
1454 delay = 0.1
1455
1456 gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
1457 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1458
1459 return 0
1460
1461def optId(verbose,id):
1462 if verbose:
1463 return ": "+id
1464 else:
1465 return ""
1466
1467def asSize(val,inBytes):
1468 if inBytes:
1469 return int(val)/(1024*1024)
1470 else:
1471 return int(val)
1472
1473def listMediumsCmd(ctx,args):
1474 if len(args) > 1:
1475 verbose = int(args[1])
1476 else:
1477 verbose = False
1478 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
1479 print "Hard disks:"
1480 for hdd in hdds:
1481 if hdd.state != ctx['global'].constants.MediumState_Created:
1482 hdd.refreshState()
1483 print " %s (%s)%s %dM [logical %dM]" %(hdd.location, hdd.format, optId(verbose,hdd.id),asSize(hdd.size, True), asSize(hdd.logicalSize, False))
1484
1485 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
1486 print "CD/DVD disks:"
1487 for dvd in dvds:
1488 if dvd.state != ctx['global'].constants.MediumState_Created:
1489 dvd.refreshState()
1490 print " %s (%s)%s %dM" %(dvd.location, dvd.format,optId(verbose,hdd.id),asSize(hdd.size, True))
1491
1492 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
1493 print "Floopy disks:"
1494 for floppy in floppys:
1495 if floppy.state != ctx['global'].constants.MediumState_Created:
1496 floppy.refreshState()
1497 print " %s (%s)%s %dM" %(floppy.location, floppy.format,optId(verbose,hdd.id), asSize(hdd.size, True))
1498
1499 return 0
1500
1501def createHddCmd(ctx,args):
1502 if (len(args) < 3):
1503 print "usage: createHdd sizeM location type"
1504 return 0
1505
1506 size = int(args[1])
1507 loc = args[2]
1508 if len(args) > 3:
1509 format = args[3]
1510 else:
1511 format = "vdi"
1512
1513 hdd = ctx['vb'].createHardDisk(format, loc)
1514 progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
1515 ctx['progressBar'](progress)
1516
1517 if not hdd.id:
1518 print "cannot create disk (file %s exist?)" %(loc)
1519 return 0
1520
1521 print "created HDD at %s as %s" %(hdd.location, hdd.id)
1522
1523 return 0
1524
1525def registerHddCmd(ctx,args):
1526 if (len(args) < 2):
1527 print "usage: registerHdd location"
1528 return 0
1529
1530 vb = ctx['vb']
1531 loc = args[1]
1532 setImageId = False
1533 imageId = ""
1534 setParentId = False
1535 parentId = ""
1536 hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
1537 print "registered HDD as %s" %(hdd.id)
1538 return 0
1539
1540def controldevice(ctx,mach,args):
1541 [ctr,port,slot,type,id] = args
1542 mach.attachDevice(ctr, port, slot,type,id)
1543
1544def attachHddCmd(ctx,args):
1545 if (len(args) < 4):
1546 print "usage: attachHdd vm hdd controller port:slot"
1547 return 0
1548
1549 mach = argsToMach(ctx,args)
1550 if mach is None:
1551 return 0
1552 vb = ctx['vb']
1553 loc = args[2]
1554 try:
1555 hdd = vb.findHardDisk(loc)
1556 except:
1557 print "no HDD with path %s registered" %(loc)
1558 return 0
1559 ctr = args[3]
1560 (port,slot) = args[4].split(":")
1561 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
1562 return 0
1563
1564def detachVmDevice(ctx,mach,args):
1565 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1566 hid = args[0]
1567 for a in atts:
1568 if a.medium:
1569 if hid == "ALL" or a.medium.id == hid:
1570 mach.detachDevice(a.controller, a.port, a.device)
1571
1572def detachMedium(ctx,mid,medium):
1573 cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
1574
1575def detachHddCmd(ctx,args):
1576 if (len(args) < 3):
1577 print "usage: detachHdd vm hdd"
1578 return 0
1579
1580 mach = argsToMach(ctx,args)
1581 if mach is None:
1582 return 0
1583 vb = ctx['vb']
1584 loc = args[2]
1585 try:
1586 hdd = vb.findHardDisk(loc)
1587 except:
1588 print "no HDD with path %s registered" %(loc)
1589 return 0
1590
1591 detachMedium(ctx,mach.id,hdd)
1592 return 0
1593
1594def unregisterHddCmd(ctx,args):
1595 if (len(args) < 2):
1596 print "usage: unregisterHdd path <vmunreg>"
1597 return 0
1598
1599 vb = ctx['vb']
1600 loc = args[1]
1601 if (len(args) > 2):
1602 vmunreg = int(args[2])
1603 else:
1604 vmunreg = 0
1605 try:
1606 hdd = vb.findHardDisk(loc)
1607 except:
1608 print "no HDD with path %s registered" %(loc)
1609 return 0
1610
1611 if vmunreg != 0:
1612 machs = ctx['global'].getArray(hdd, 'machineIds')
1613 try:
1614 for m in machs:
1615 print "Trying to detach from %s" %(m)
1616 detachMedium(ctx,m,hdd)
1617 except Exception, e:
1618 print 'failed: ',e
1619 return 0
1620 hdd.close()
1621 return 0
1622
1623def removeHddCmd(ctx,args):
1624 if (len(args) != 2):
1625 print "usage: removeHdd path"
1626 return 0
1627
1628 vb = ctx['vb']
1629 loc = args[1]
1630 try:
1631 hdd = vb.findHardDisk(loc)
1632 except:
1633 print "no HDD with path %s registered" %(loc)
1634 return 0
1635
1636 progress = hdd.deleteStorage()
1637 ctx['progressBar'](progress)
1638
1639 return 0
1640
1641def registerIsoCmd(ctx,args):
1642 if (len(args) < 2):
1643 print "usage: registerIso location"
1644 return 0
1645 vb = ctx['vb']
1646 loc = args[1]
1647 id = ""
1648 iso = vb.openDVDImage(loc, id)
1649 print "registered ISO as %s" %(iso.id)
1650 return 0
1651
1652def unregisterIsoCmd(ctx,args):
1653 if (len(args) != 2):
1654 print "usage: unregisterIso path"
1655 return 0
1656
1657 vb = ctx['vb']
1658 loc = args[1]
1659 try:
1660 dvd = vb.findDVDImage(loc)
1661 except:
1662 print "no DVD with path %s registered" %(loc)
1663 return 0
1664
1665 progress = dvd.close()
1666 print "Unregistered ISO at %s" %(dvd.location)
1667
1668 return 0
1669
1670def removeIsoCmd(ctx,args):
1671 if (len(args) != 2):
1672 print "usage: removeIso path"
1673 return 0
1674
1675 vb = ctx['vb']
1676 loc = args[1]
1677 try:
1678 dvd = vb.findDVDImage(loc)
1679 except:
1680 print "no DVD with path %s registered" %(loc)
1681 return 0
1682
1683 progress = dvd.deleteStorage()
1684 ctx['progressBar'](progress)
1685 print "Removed ISO at %s" %(dvd.location)
1686
1687 return 0
1688
1689def attachIsoCmd(ctx,args):
1690 if (len(args) < 5):
1691 print "usage: attachIso vm iso controller port:slot"
1692 return 0
1693
1694 mach = argsToMach(ctx,args)
1695 if mach is None:
1696 return 0
1697 vb = ctx['vb']
1698 loc = args[2]
1699 try:
1700 dvd = vb.findDVDImage(loc)
1701 except:
1702 print "no DVD with path %s registered" %(loc)
1703 return 0
1704 ctr = args[3]
1705 (port,slot) = args[4].split(":")
1706 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
1707 return 0
1708
1709def detachIsoCmd(ctx,args):
1710 if (len(args) < 3):
1711 print "usage: detachIso vm iso"
1712 return 0
1713
1714 mach = argsToMach(ctx,args)
1715 if mach is None:
1716 return 0
1717 vb = ctx['vb']
1718 loc = args[2]
1719 try:
1720 dvd = vb.findDVDImage(loc)
1721 except:
1722 print "no DVD with path %s registered" %(loc)
1723 return 0
1724
1725 detachMedium(ctx,mach.id,dvd)
1726 return 0
1727
1728def mountIsoCmd(ctx,args):
1729 if (len(args) < 5):
1730 print "usage: mountIso vm iso controller port:slot"
1731 return 0
1732
1733 mach = argsToMach(ctx,args)
1734 if mach is None:
1735 return 0
1736 vb = ctx['vb']
1737 loc = args[2]
1738 try:
1739 dvd = vb.findDVDImage(loc)
1740 except:
1741 print "no DVD with path %s registered" %(loc)
1742 return 0
1743
1744 ctr = args[3]
1745 (port,slot) = args[4].split(":")
1746
1747 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
1748
1749 return 0
1750
1751def unmountIsoCmd(ctx,args):
1752 if (len(args) < 4):
1753 print "usage: unmountIso vm controller port:slot"
1754 return 0
1755
1756 mach = argsToMach(ctx,args)
1757 if mach is None:
1758 return 0
1759 vb = ctx['vb']
1760
1761 ctr = args[2]
1762 (port,slot) = args[3].split(":")
1763
1764 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
1765
1766 return 0
1767
1768def attachCtr(ctx,mach,args):
1769 [name, bus, type] = args
1770 ctr = mach.addStorageController(name, bus)
1771 if type != None:
1772 ctr.controllerType = type
1773
1774def attachCtrCmd(ctx,args):
1775 if (len(args) < 4):
1776 print "usage: attachCtr vm cname bus <type>"
1777 return 0
1778
1779 if len(args) > 4:
1780 type = enumFromString(ctx,'StorageControllerType', args[4])
1781 if type == None:
1782 print "Controller type %s unknown" %(args[4])
1783 return 0
1784 else:
1785 type = None
1786
1787 mach = argsToMach(ctx,args)
1788 if mach is None:
1789 return 0
1790 bus = enumFromString(ctx,'StorageBus', args[3])
1791 if bus is None:
1792 print "Bus type %s unknown" %(args[3])
1793 return 0
1794 name = args[2]
1795 cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
1796 return 0
1797
1798def detachCtrCmd(ctx,args):
1799 if (len(args) < 3):
1800 print "usage: detachCtr vm name"
1801 return 0
1802
1803 mach = argsToMach(ctx,args)
1804 if mach is None:
1805 return 0
1806 ctr = args[2]
1807 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
1808 return 0
1809
1810
1811aliases = {'s':'start',
1812 'i':'info',
1813 'l':'list',
1814 'h':'help',
1815 'a':'alias',
1816 'q':'quit', 'exit':'quit',
1817 'tg': 'typeGuest',
1818 'v':'verbose'}
1819
1820commands = {'help':['Prints help information', helpCmd, 0],
1821 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
1822 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
1823 'removeVm':['Remove virtual machine', removeVmCmd, 0],
1824 'pause':['Pause virtual machine', pauseCmd, 0],
1825 'resume':['Resume virtual machine', resumeCmd, 0],
1826 'save':['Save execution state of virtual machine', saveCmd, 0],
1827 'stats':['Stats for virtual machine', statsCmd, 0],
1828 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1829 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1830 'list':['Shows known virtual machines', listCmd, 0],
1831 'info':['Shows info on machine', infoCmd, 0],
1832 'ginfo':['Shows info on guest', ginfoCmd, 0],
1833 'gexec':['Executes program in the guest', gexecCmd, 0],
1834 'alias':['Control aliases', aliasCmd, 0],
1835 'verbose':['Toggle verbosity', verboseCmd, 0],
1836 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1837 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1838 'quit':['Exits', quitCmd, 0],
1839 'host':['Show host information', hostCmd, 0],
1840 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
1841 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1842 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1843 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1844 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1845 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1846 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1847 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1848 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1849 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
1850 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1851 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
1852 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
1853 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
1854 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
1855 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
1856 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
1857 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
1858 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
1859 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
1860 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
1861 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
1862 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
1863 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
1864 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
1865 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
1866 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
1867 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
1868 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
1869 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
1870 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
1871 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
1872 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
1873 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
1874 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
1875 'listMediums': ['List mediums known to this VBox instance', listMediumsCmd, 0]
1876 }
1877
1878def runCommandArgs(ctx, args):
1879 c = args[0]
1880 if aliases.get(c, None) != None:
1881 c = aliases[c]
1882 ci = commands.get(c,None)
1883 if ci == None:
1884 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
1885 return 0
1886 return ci[1](ctx, args)
1887
1888
1889def runCommand(ctx, cmd):
1890 if len(cmd) == 0: return 0
1891 args = split_no_quotes(cmd)
1892 if len(args) == 0: return 0
1893 return runCommandArgs(ctx, args)
1894
1895#
1896# To write your own custom commands to vboxshell, create
1897# file ~/.VirtualBox/shellext.py with content like
1898#
1899# def runTestCmd(ctx, args):
1900# print "Testy test", ctx['vb']
1901# return 0
1902#
1903# commands = {
1904# 'test': ['Test help', runTestCmd]
1905# }
1906# and issue reloadExt shell command.
1907# This file also will be read automatically on startup or 'reloadExt'.
1908#
1909# Also one can put shell extensions into ~/.VirtualBox/shexts and
1910# they will also be picked up, so this way one can exchange
1911# shell extensions easily.
1912def addExtsFromFile(ctx, cmds, file):
1913 if not os.path.isfile(file):
1914 return
1915 d = {}
1916 try:
1917 execfile(file, d, d)
1918 for (k,v) in d['commands'].items():
1919 if g_verbose:
1920 print "customize: adding \"%s\" - %s" %(k, v[0])
1921 cmds[k] = [v[0], v[1], file]
1922 except:
1923 print "Error loading user extensions from %s" %(file)
1924 traceback.print_exc()
1925
1926
1927def checkUserExtensions(ctx, cmds, folder):
1928 folder = str(folder)
1929 name = os.path.join(folder, "shellext.py")
1930 addExtsFromFile(ctx, cmds, name)
1931 # also check 'exts' directory for all files
1932 shextdir = os.path.join(folder, "shexts")
1933 if not os.path.isdir(shextdir):
1934 return
1935 exts = os.listdir(shextdir)
1936 for e in exts:
1937 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
1938
1939def getHomeFolder(ctx):
1940 if ctx['remote'] or ctx['vb'] is None:
1941 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
1942 else:
1943 return ctx['vb'].homeFolder
1944
1945def interpret(ctx):
1946 if ctx['remote']:
1947 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
1948 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
1949
1950 vbox = ctx['vb']
1951
1952 if vbox is not None:
1953 print "Running VirtualBox version %s" %(vbox.version)
1954 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
1955 else:
1956 ctx['perf'] = None
1957
1958 home = getHomeFolder(ctx)
1959 checkUserExtensions(ctx, commands, home)
1960
1961 autoCompletion(commands, ctx)
1962
1963 # to allow to print actual host information, we collect info for
1964 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
1965 if ctx['perf']:
1966 try:
1967 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
1968 except:
1969 pass
1970
1971 while True:
1972 try:
1973 cmd = raw_input("vbox> ")
1974 done = runCommand(ctx, cmd)
1975 if done != 0: break
1976 except KeyboardInterrupt:
1977 print '====== You can type quit or q to leave'
1978 break
1979 except EOFError:
1980 break;
1981 except Exception,e:
1982 print e
1983 if g_verbose:
1984 traceback.print_exc()
1985 ctx['global'].waitForEvents(0)
1986 try:
1987 # There is no need to disable metric collection. This is just an example.
1988 if ct['perf']:
1989 ctx['perf'].disable(['*'], [vbox.host])
1990 except:
1991 pass
1992
1993def runCommandCb(ctx, cmd, args):
1994 args.insert(0, cmd)
1995 return runCommandArgs(ctx, args)
1996
1997def runGuestCommandCb(ctx, id, guestLambda, args):
1998 mach = machById(ctx,id)
1999 if mach == None:
2000 return 0
2001 args.insert(0, guestLambda)
2002 cmdExistingVm(ctx, mach, 'guestlambda', args)
2003 return 0
2004
2005def main(argv):
2006 style = None
2007 autopath = False
2008 argv.pop(0)
2009 while len(argv) > 0:
2010 if argv[0] == "-w":
2011 style = "WEBSERVICE"
2012 if argv[0] == "-a":
2013 autopath = True
2014 argv.pop(0)
2015
2016 if autopath:
2017 cwd = os.getcwd()
2018 vpp = os.environ.get("VBOX_PROGRAM_PATH")
2019 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
2020 vpp = cwd
2021 print "Autodetected VBOX_PROGRAM_PATH as",vpp
2022 os.environ["VBOX_PROGRAM_PATH"] = cwd
2023 sys.path.append(os.path.join(vpp, "sdk", "installer"))
2024
2025 from vboxapi import VirtualBoxManager
2026 g_virtualBoxManager = VirtualBoxManager(style, None)
2027 ctx = {'global':g_virtualBoxManager,
2028 'mgr':g_virtualBoxManager.mgr,
2029 'vb':g_virtualBoxManager.vbox,
2030 'ifaces':g_virtualBoxManager.constants,
2031 'remote':g_virtualBoxManager.remote,
2032 'type':g_virtualBoxManager.type,
2033 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
2034 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
2035 'machById': lambda id: machById(ctx,id),
2036 'argsToMach': lambda args: argsToMach(ctx,args),
2037 'progressBar': lambda p: progressBar(ctx,p),
2038 'typeInGuest': typeInGuest,
2039 '_machlist':None
2040 }
2041 interpret(ctx)
2042 g_virtualBoxManager.deinit()
2043 del g_virtualBoxManager
2044
2045if __name__ == '__main__':
2046 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