VirtualBox

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

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

Python shell: disk/ISO images manipulation commands

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