VirtualBox

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

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

python shell: disable metrics collection

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