VirtualBox

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

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

Python shell: taking screenshot works again

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