VirtualBox

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

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

python shell: couple missed bits

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette