VirtualBox

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

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

IDisplay API changes for multimonitor (xTracker 4655)

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

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