VirtualBox

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

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

Python shell: better naming

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.2 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.virtualbox.org. This file is free software;
7# you can redistribute it and/or modify it under the terms of the GNU
8# General Public License (GPL) as published by the Free Software
9# Foundation, in version 2 as it comes in the "COPYING" file of the
10# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
11# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
12#
13# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
14# Clara, CA 95054 USA or visit http://www.sun.com if you need
15# additional information or have any questions.
16#
17#################################################################################
18# This program is a simple interactive shell for VirtualBox. You can query #
19# information and issue commands from a simple command line. #
20# #
21# It also provides you with examples on how to use VirtualBox's Python API. #
22# This shell is even somewhat documented 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, needsHostCursor):
42 print "%s: onMouseCapabilityChange: needsHostCursor=%d" %(self.mach.name, 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 readline.parse_and_bind("tab: complete")
204
205g_verbose = True
206
207def split_no_quotes(s):
208 return shlex.split(s)
209
210def progressBar(ctx,p,wait=1000):
211 try:
212 while not p.completed:
213 print "%d %%\r" %(p.percent),
214 sys.stdout.flush()
215 p.waitForCompletion(wait)
216 ctx['global'].waitForEvents(0)
217 except KeyboardInterrupt:
218 print "Interrupted."
219
220
221def reportError(ctx,session,rc):
222 if not ctx['remote']:
223 print session.QueryErrorObject(rc)
224
225
226def createVm(ctx,name,kind,base):
227 mgr = ctx['mgr']
228 vb = ctx['vb']
229 mach = vb.createMachine(name, kind, base, "")
230 mach.saveSettings()
231 print "created machine with UUID",mach.id
232 vb.registerMachine(mach)
233 # update cache
234 getMachines(ctx, True)
235
236def removeVm(ctx,mach):
237 mgr = ctx['mgr']
238 vb = ctx['vb']
239 id = mach.id
240 print "removing machine ",mach.name,"with UUID",id
241 session = ctx['global'].openMachineSession(id)
242 try:
243 mach = session.machine
244 for d in ctx['global'].getArray(mach, 'hardDiskAttachments'):
245 mach.detachHardDisk(d.controller, d.port, d.device)
246 except:
247 traceback.print_exc()
248 mach.saveSettings()
249 ctx['global'].closeMachineSession(session)
250 mach = vb.unregisterMachine(id)
251 if mach:
252 mach.deleteSettings()
253 # update cache
254 getMachines(ctx, True)
255
256def startVm(ctx,mach,type):
257 mgr = ctx['mgr']
258 vb = ctx['vb']
259 perf = ctx['perf']
260 session = mgr.getSessionObject(vb)
261 uuid = mach.id
262 progress = vb.openRemoteSession(session, uuid, type, "")
263 progressBar(ctx, progress, 100)
264 completed = progress.completed
265 rc = int(progress.resultCode)
266 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
267 if rc == 0:
268 # we ignore exceptions to allow starting VM even if
269 # perf collector cannot be started
270 if perf:
271 try:
272 perf.setup(['*'], [mach], 10, 15)
273 except Exception,e:
274 print e
275 if g_verbose:
276 traceback.print_exc()
277 pass
278 # if session not opened, close doesn't make sense
279 session.close()
280 else:
281 reportError(ctx,session,rc)
282
283def getMachines(ctx, invalidate = False):
284 if ctx['vb'] is not None:
285 if ctx['_machlist'] is None or invalidate:
286 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
287 return ctx['_machlist']
288 else:
289 return []
290
291def asState(var):
292 if var:
293 return 'on'
294 else:
295 return 'off'
296
297def guestStats(ctx,mach):
298 if not ctx['perf']:
299 return
300 for metric in ctx['perf'].query(["*"], [mach]):
301 print metric['name'], metric['values_as_string']
302
303def guestExec(ctx, machine, console, cmds):
304 exec cmds
305
306def monitorGuest(ctx, machine, console, dur):
307 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
308 console.registerCallback(cb)
309 if dur == -1:
310 # not infinity, but close enough
311 dur = 100000
312 try:
313 end = time.time() + dur
314 while time.time() < end:
315 ctx['global'].waitForEvents(500)
316 # We need to catch all exceptions here, otherwise callback will never be unregistered
317 except:
318 pass
319 console.unregisterCallback(cb)
320
321
322def monitorVBox(ctx, dur):
323 vbox = ctx['vb']
324 isMscom = (ctx['global'].type == 'MSCOM')
325 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
326 vbox.registerCallback(cb)
327 if dur == -1:
328 # not infinity, but close enough
329 dur = 100000
330 try:
331 end = time.time() + dur
332 while time.time() < end:
333 ctx['global'].waitForEvents(500)
334 # We need to catch all exceptions here, otherwise callback will never be unregistered
335 except:
336 pass
337 vbox.unregisterCallback(cb)
338
339
340def takeScreenshot(ctx,console,args):
341 from PIL import Image
342 display = console.display
343 if len(args) > 0:
344 f = args[0]
345 else:
346 f = "/tmp/screenshot.png"
347 if len(args) > 1:
348 w = args[1]
349 else:
350 w = console.display.width
351 if len(args) > 2:
352 h = args[2]
353 else:
354 h = console.display.height
355 print "Saving screenshot (%d x %d) in %s..." %(w,h,f)
356 data = display.takeScreenShotSlow(w,h)
357 size = (w,h)
358 mode = "RGBA"
359 im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)
360 im.save(f, "PNG")
361
362
363def teleport(ctx,session,console,args):
364 if args[0].find(":") == -1:
365 print "Use host:port format for teleport target"
366 return
367 (host,port) = args[0].split(":")
368 if len(args) > 1:
369 passwd = args[1]
370 else:
371 passwd = ""
372
373 port = int(port)
374 print "Teleporting to %s:%d..." %(host,port)
375 progress = console.teleport(host, port, passwd)
376 progressBar(ctx, progress, 100)
377 completed = progress.completed
378 rc = int(progress.resultCode)
379 if rc == 0:
380 print "Success!"
381 else:
382 reportError(ctx,session,rc)
383
384def cmdExistingVm(ctx,mach,cmd,args):
385 mgr=ctx['mgr']
386 vb=ctx['vb']
387 session = mgr.getSessionObject(vb)
388 uuid = mach.id
389 try:
390 progress = vb.openExistingSession(session, uuid)
391 except Exception,e:
392 print "Session to '%s' not open: %s" %(mach.name,e)
393 if g_verbose:
394 traceback.print_exc()
395 return
396 if session.state != ctx['ifaces'].SessionState_Open:
397 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
398 return
399 # unfortunately IGuest is suppressed, thus WebServices knows not about it
400 # this is an example how to handle local only functionality
401 if ctx['remote'] and cmd == 'stats2':
402 print 'Trying to use local only functionality, ignored'
403 return
404 console=session.console
405 ops={'pause': lambda: console.pause(),
406 'resume': lambda: console.resume(),
407 'powerdown': lambda: console.powerDown(),
408 'powerbutton': lambda: console.powerButton(),
409 'stats': lambda: guestStats(ctx, mach),
410 'guest': lambda: guestExec(ctx, mach, console, args),
411 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
412 'save': lambda: progressBar(ctx,console.saveState()),
413 'screenshot': lambda: takeScreenshot(ctx,console,args),
414 'teleport': lambda: teleport(ctx,session,console,args)
415 }
416 try:
417 ops[cmd]()
418 except Exception, e:
419 print 'failed: ',e
420 if g_verbose:
421 traceback.print_exc()
422
423 session.close()
424
425def machById(ctx,id):
426 mach = None
427 for m in getMachines(ctx):
428 if m.name == id:
429 mach = m
430 break
431 mid = str(m.id)
432 if mid[0] == '{':
433 mid = mid[1:-1]
434 if mid == id:
435 mach = m
436 break
437 return mach
438
439def argsToMach(ctx,args):
440 if len(args) < 2:
441 print "usage: %s [vmname|uuid]" %(args[0])
442 return None
443 id = args[1]
444 m = machById(ctx, id)
445 if m == None:
446 print "Machine '%s' is unknown, use list command to find available machines" %(id)
447 return m
448
449def helpSingleCmd(cmd,h,sp):
450 if sp != 0:
451 spec = " [ext from "+sp+"]"
452 else:
453 spec = ""
454 print " %s: %s%s" %(cmd,h,spec)
455
456def helpCmd(ctx, args):
457 if len(args) == 1:
458 print "Help page:"
459 names = commands.keys()
460 names.sort()
461 for i in names:
462 helpSingleCmd(i, commands[i][0], commands[i][2])
463 else:
464 cmd = args[1]
465 c = commands.get(cmd)
466 if c == None:
467 print "Command '%s' not known" %(cmd)
468 else:
469 helpSingleCmd(cmd, c[0], c[2])
470 return 0
471
472def listCmd(ctx, args):
473 for m in getMachines(ctx, True):
474 if m.teleporterEnabled:
475 tele = "[T] "
476 else:
477 tele = " "
478 print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,m.sessionState)
479 return 0
480
481def getControllerType(type):
482 if type == 0:
483 return "Null"
484 elif type == 1:
485 return "LsiLogic"
486 elif type == 2:
487 return "BusLogic"
488 elif type == 3:
489 return "IntelAhci"
490 elif type == 4:
491 return "PIIX3"
492 elif type == 5:
493 return "PIIX4"
494 elif type == 6:
495 return "ICH6"
496 else:
497 return "Unknown"
498
499def infoCmd(ctx,args):
500 if (len(args) < 2):
501 print "usage: info [vmname|uuid]"
502 return 0
503 mach = argsToMach(ctx,args)
504 if mach == None:
505 return 0
506 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
507 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
508 print " Name [name]: %s" %(mach.name)
509 print " ID [n/a]: %s" %(mach.id)
510 print " OS Type [n/a]: %s" %(os.description)
511 print " Firmware [firmwareType]: %s" %(mach.firmwareType)
512 print
513 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
514 print " RAM [memorySize]: %dM" %(mach.memorySize)
515 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
516 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
517 print
518 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
519 print " Machine status [n/a]: %d" % (mach.sessionState)
520 print
521 if mach.teleporterEnabled:
522 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
523 print
524 bios = mach.BIOSSettings
525 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
526 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
527 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
528 print " Hardware virtualization [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
529 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
530 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
531 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
532 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
533
534 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
535 print " Hardware 2d video acceleration[accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
536
537 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
538 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
539
540 controllers = ctx['global'].getArray(mach, 'storageControllers')
541 if controllers:
542 print
543 print " Controllers:"
544 for controller in controllers:
545 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
546
547 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
548 if attaches:
549 print
550 print " Mediums:"
551 for a in attaches:
552 print " Controller: %s port: %d device: %d type: %s:" % (a.controller, a.port, a.device, a.type)
553 m = a.medium
554 if a.type == ctx['global'].constants.DeviceType_HardDisk:
555 print " HDD:"
556 print " Id: %s" %(m.id)
557 print " Location: %s" %(m.location)
558 print " Name: %s" %(m.name)
559 print " Format: %s" %(m.format)
560
561 if a.type == ctx['global'].constants.DeviceType_DVD:
562 print " DVD:"
563 if m:
564 print " Id: %s" %(m.id)
565 print " Name: %s" %(m.name)
566 if m.hostDrive:
567 print " Host DVD %s" %(m.location)
568 if a.passthrough:
569 print " [passthrough mode]"
570 else:
571 print " Virtual image at %s" %(m.location)
572 print " Size: %s" %(m.size)
573
574 if a.type == ctx['global'].constants.DeviceType_Floppy:
575 print " Floppy:"
576 if m:
577 print " Id: %s" %(m.id)
578 print " Name: %s" %(m.name)
579 if m.hostDrive:
580 print " Host floppy %s" %(m.location)
581 else:
582 print " Virtual image at %s" %(m.location)
583 print " Size: %s" %(m.size)
584
585 return 0
586
587def startCmd(ctx, args):
588 mach = argsToMach(ctx,args)
589 if mach == None:
590 return 0
591 if len(args) > 2:
592 type = args[2]
593 else:
594 type = "gui"
595 startVm(ctx, mach, type)
596 return 0
597
598def createCmd(ctx, args):
599 if (len(args) < 3 or len(args) > 4):
600 print "usage: create name ostype <basefolder>"
601 return 0
602 name = args[1]
603 oskind = args[2]
604 if len(args) == 4:
605 base = args[3]
606 else:
607 base = ''
608 try:
609 ctx['vb'].getGuestOSType(oskind)
610 except Exception, e:
611 print 'Unknown OS type:',oskind
612 return 0
613 createVm(ctx, name, oskind, base)
614 return 0
615
616def removeCmd(ctx, args):
617 mach = argsToMach(ctx,args)
618 if mach == None:
619 return 0
620 removeVm(ctx, mach)
621 return 0
622
623def pauseCmd(ctx, args):
624 mach = argsToMach(ctx,args)
625 if mach == None:
626 return 0
627 cmdExistingVm(ctx, mach, 'pause', '')
628 return 0
629
630def powerdownCmd(ctx, args):
631 mach = argsToMach(ctx,args)
632 if mach == None:
633 return 0
634 cmdExistingVm(ctx, mach, 'powerdown', '')
635 return 0
636
637def powerbuttonCmd(ctx, args):
638 mach = argsToMach(ctx,args)
639 if mach == None:
640 return 0
641 cmdExistingVm(ctx, mach, 'powerbutton', '')
642 return 0
643
644def resumeCmd(ctx, args):
645 mach = argsToMach(ctx,args)
646 if mach == None:
647 return 0
648 cmdExistingVm(ctx, mach, 'resume', '')
649 return 0
650
651def saveCmd(ctx, args):
652 mach = argsToMach(ctx,args)
653 if mach == None:
654 return 0
655 cmdExistingVm(ctx, mach, 'save', '')
656 return 0
657
658def statsCmd(ctx, args):
659 mach = argsToMach(ctx,args)
660 if mach == None:
661 return 0
662 cmdExistingVm(ctx, mach, 'stats', '')
663 return 0
664
665def guestCmd(ctx, args):
666 if (len(args) < 3):
667 print "usage: guest name commands"
668 return 0
669 mach = argsToMach(ctx,args)
670 if mach == None:
671 return 0
672 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
673 return 0
674
675def screenshotCmd(ctx, args):
676 if (len(args) < 3):
677 print "usage: screenshot name file <width> <height>"
678 return 0
679 mach = argsToMach(ctx,args)
680 if mach == None:
681 return 0
682 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
683 return 0
684
685def teleportCmd(ctx, args):
686 if (len(args) < 3):
687 print "usage: teleport name host:port <password>"
688 return 0
689 mach = argsToMach(ctx,args)
690 if mach == None:
691 return 0
692 cmdExistingVm(ctx, mach, 'teleport', args[2:])
693 return 0
694
695def openportalCmd(ctx, args):
696 if (len(args) < 3):
697 print "usage: openportal name port <password>"
698 return 0
699 mach = argsToMach(ctx,args)
700 if mach == None:
701 return 0
702 port = int(args[2])
703 if (len(args) > 3):
704 passwd = args[3]
705 else:
706 passwd = ""
707 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
708 session = ctx['global'].openMachineSession(mach.id)
709 mach1 = session.machine
710 mach1.teleporterEnabled = True
711 mach1.teleporterPort = port
712 mach1.teleporterPassword = passwd
713 mach1.saveSettings()
714 session.close()
715 startVm(ctx, mach, "gui")
716 return 0
717
718def closeportalCmd(ctx, args):
719 if (len(args) < 2):
720 print "usage: closeportal name"
721 return 0
722 mach = argsToMach(ctx,args)
723 if mach == None:
724 return 0
725 if mach.teleporterEnabled:
726 session = ctx['global'].openMachineSession(mach.id)
727 mach1 = session.machine
728 mach1.teleporterEnabled = False
729 mach1.saveSettings()
730 session.close()
731 return 0
732
733
734def setvarCmd(ctx, args):
735 if (len(args) < 4):
736 print "usage: setvar [vmname|uuid] expr value"
737 return 0
738 mach = argsToMach(ctx,args)
739 if mach == None:
740 return 0
741 session = ctx['global'].openMachineSession(mach.id)
742 mach = session.machine
743 expr = 'mach.'+args[2]+' = '+args[3]
744 print "Executing",expr
745 try:
746 exec expr
747 except Exception, e:
748 print 'failed: ',e
749 if g_verbose:
750 traceback.print_exc()
751 mach.saveSettings()
752 session.close()
753 return 0
754
755def quitCmd(ctx, args):
756 return 1
757
758def aliasCmd(ctx, args):
759 if (len(args) == 3):
760 aliases[args[1]] = args[2]
761 return 0
762
763 for (k,v) in aliases.items():
764 print "'%s' is an alias for '%s'" %(k,v)
765 return 0
766
767def verboseCmd(ctx, args):
768 global g_verbose
769 g_verbose = not g_verbose
770 return 0
771
772def getUSBStateString(state):
773 if state == 0:
774 return "NotSupported"
775 elif state == 1:
776 return "Unavailable"
777 elif state == 2:
778 return "Busy"
779 elif state == 3:
780 return "Available"
781 elif state == 4:
782 return "Held"
783 elif state == 5:
784 return "Captured"
785 else:
786 return "Unknown"
787
788def hostCmd(ctx, args):
789 host = ctx['vb'].host
790 cnt = host.processorCount
791 print "Processor count:",cnt
792 for i in range(0,cnt):
793 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
794
795 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
796 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
797 if host.Acceleration3DAvailable:
798 print "3D acceleration available"
799 else:
800 print "3D acceleration NOT available"
801
802 print "Network interfaces:"
803 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
804 print " %s (%s)" %(ni.name, ni.IPAddress)
805
806 print "DVD drives:"
807 for dd in ctx['global'].getArray(host, 'DVDDrives'):
808 print " %s - %s" %(dd.name, dd.description)
809
810 print "USB devices:"
811 for ud in ctx['global'].getArray(host, 'USBDevices'):
812 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
813
814 if ctx['perf']:
815 for metric in ctx['perf'].query(["*"], [host]):
816 print metric['name'], metric['values_as_string']
817
818 return 0
819
820def monitorGuestCmd(ctx, args):
821 if (len(args) < 2):
822 print "usage: monitorGuest name (duration)"
823 return 0
824 mach = argsToMach(ctx,args)
825 if mach == None:
826 return 0
827 dur = 5
828 if len(args) > 2:
829 dur = float(args[2])
830 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
831 return 0
832
833def monitorVBoxCmd(ctx, args):
834 if (len(args) > 2):
835 print "usage: monitorVBox (duration)"
836 return 0
837 dur = 5
838 if len(args) > 1:
839 dur = float(args[1])
840 monitorVBox(ctx, dur)
841 return 0
842
843def getAdapterType(ctx, type):
844 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
845 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
846 return "pcnet"
847 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
848 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
849 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
850 return "e1000"
851 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
852 return "virtio"
853 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
854 return None
855 else:
856 raise Exception("Unknown adapter type: "+type)
857
858
859def portForwardCmd(ctx, args):
860 if (len(args) != 5):
861 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
862 return 0
863 mach = argsToMach(ctx,args)
864 if mach == None:
865 return 0
866 adapterNum = int(args[2])
867 hostPort = int(args[3])
868 guestPort = int(args[4])
869 proto = "TCP"
870 session = ctx['global'].openMachineSession(mach.id)
871 mach = session.machine
872
873 adapter = mach.getNetworkAdapter(adapterNum)
874 adapterType = getAdapterType(ctx, adapter.adapterType)
875
876 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
877 config = "VBoxInternal/Devices/" + adapterType + "/"
878 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
879
880 mach.setExtraData(config + "/Protocol", proto)
881 mach.setExtraData(config + "/HostPort", str(hostPort))
882 mach.setExtraData(config + "/GuestPort", str(guestPort))
883
884 mach.saveSettings()
885 session.close()
886
887 return 0
888
889
890def showLogCmd(ctx, args):
891 if (len(args) < 2):
892 print "usage: showLog <vm> <num>"
893 return 0
894 mach = argsToMach(ctx,args)
895 if mach == None:
896 return 0
897
898 log = "VBox.log"
899 if (len(args) > 2):
900 log += "."+args[2]
901 fileName = os.path.join(mach.logFolder, log)
902
903 try:
904 lf = open(fileName, 'r')
905 except IOError,e:
906 print "cannot open: ",e
907 return 0
908
909 for line in lf:
910 print line,
911 lf.close()
912
913 return 0
914
915def evalCmd(ctx, args):
916 expr = ' '.join(args[1:])
917 try:
918 exec expr
919 except Exception, e:
920 print 'failed: ',e
921 if g_verbose:
922 traceback.print_exc()
923 return 0
924
925def reloadExtCmd(ctx, args):
926 # maybe will want more args smartness
927 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
928 autoCompletion(commands, ctx)
929 return 0
930
931
932def runScriptCmd(ctx, args):
933 if (len(args) != 2):
934 print "usage: runScript <script>"
935 return 0
936 try:
937 lf = open(args[1], 'r')
938 except IOError,e:
939 print "cannot open:",args[1], ":",e
940 return 0
941
942 try:
943 for line in lf:
944 done = runCommand(ctx, line)
945 if done != 0: break
946 except Exception,e:
947 print "error:",e
948 if g_verbose:
949 traceback.print_exc()
950 lf.close()
951 return 0
952
953def sleepCmd(ctx, args):
954 if (len(args) != 2):
955 print "usage: sleep <secs>"
956 return 0
957
958 try:
959 time.sleep(float(args[1]))
960 except:
961 # to allow sleep interrupt
962 pass
963 return 0
964
965
966def shellCmd(ctx, args):
967 if (len(args) < 2):
968 print "usage: shell <commands>"
969 return 0
970 cmd = ' '.join(args[1:])
971 try:
972 os.system(cmd)
973 except KeyboardInterrupt:
974 # to allow shell command interruption
975 pass
976 return 0
977
978
979def connectCmd(ctx, args):
980 if (len(args) > 4):
981 print "usage: connect [url] [username] [passwd]"
982 return 0
983
984 if ctx['vb'] is not None:
985 print "Already connected, disconnect first..."
986 return 0
987
988 if (len(args) > 1):
989 url = args[1]
990 else:
991 url = None
992
993 if (len(args) > 2):
994 user = args[2]
995 else:
996 user = ""
997
998 if (len(args) > 3):
999 passwd = args[3]
1000 else:
1001 passwd = ""
1002
1003 vbox = ctx['global'].platform.connect(url, user, passwd)
1004 ctx['vb'] = vbox
1005 print "Running VirtualBox version %s" %(vbox.version)
1006 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1007 return 0
1008
1009def disconnectCmd(ctx, args):
1010 if (len(args) != 1):
1011 print "usage: disconnect"
1012 return 0
1013
1014 if ctx['vb'] is None:
1015 print "Not connected yet."
1016 return 0
1017
1018 try:
1019 ctx['global'].platform.disconnect()
1020 except:
1021 ctx['vb'] = None
1022 raise
1023
1024 ctx['vb'] = None
1025 return 0
1026
1027def exportVMCmd(ctx, args):
1028 import sys
1029
1030 if len(args) < 3:
1031 print "usage: exportVm <machine> <path> <format> <license>"
1032 return 0
1033 mach = ctx['machById'](args[1])
1034 if mach is None:
1035 return 0
1036 path = args[2]
1037 if (len(args) > 3):
1038 format = args[3]
1039 else:
1040 format = "ovf-1.0"
1041 if (len(args) > 4):
1042 license = args[4]
1043 else:
1044 license = "GPL"
1045
1046 app = ctx['vb'].createAppliance()
1047 desc = mach.export(app)
1048 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1049 p = app.write(format, path)
1050 progressBar(ctx, p)
1051 print "Exported to %s in format %s" %(path, format)
1052 return 0
1053
1054aliases = {'s':'start',
1055 'i':'info',
1056 'l':'list',
1057 'h':'help',
1058 'a':'alias',
1059 'q':'quit', 'exit':'quit',
1060 'v':'verbose'}
1061
1062commands = {'help':['Prints help information', helpCmd, 0],
1063 'start':['Start virtual machine by name or uuid', startCmd, 0],
1064 'create':['Create virtual machine', createCmd, 0],
1065 'remove':['Remove virtual machine', removeCmd, 0],
1066 'pause':['Pause virtual machine', pauseCmd, 0],
1067 'resume':['Resume virtual machine', resumeCmd, 0],
1068 'save':['Save execution state of virtual machine', saveCmd, 0],
1069 'stats':['Stats for virtual machine', statsCmd, 0],
1070 'powerdown':['Power down virtual machine', powerdownCmd, 0],
1071 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
1072 'list':['Shows known virtual machines', listCmd, 0],
1073 'info':['Shows info on machine', infoCmd, 0],
1074 'alias':['Control aliases', aliasCmd, 0],
1075 'verbose':['Toggle verbosity', verboseCmd, 0],
1076 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
1077 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
1078 'quit':['Exits', quitCmd, 0],
1079 'host':['Show host information', hostCmd, 0],
1080 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
1081 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
1082 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
1083 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
1084 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
1085 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
1086 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
1087 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
1088 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
1089 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0],
1090 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
1091 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd>', teleportCmd, 0],
1092 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
1093 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0]
1094 }
1095
1096def runCommandArgs(ctx, args):
1097 c = args[0]
1098 if aliases.get(c, None) != None:
1099 c = aliases[c]
1100 ci = commands.get(c,None)
1101 if ci == None:
1102 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
1103 return 0
1104 return ci[1](ctx, args)
1105
1106
1107def runCommand(ctx, cmd):
1108 if len(cmd) == 0: return 0
1109 args = split_no_quotes(cmd)
1110 if len(args) == 0: return 0
1111 return runCommandArgs(ctx, args)
1112
1113#
1114# To write your own custom commands to vboxshell, create
1115# file ~/.VirtualBox/shellext.py with content like
1116#
1117# def runTestCmd(ctx, args):
1118# print "Testy test", ctx['vb']
1119# return 0
1120#
1121# commands = {
1122# 'test': ['Test help', runTestCmd]
1123# }
1124# and issue reloadExt shell command.
1125# This file also will be read automatically on startup or 'reloadExt'.
1126#
1127# Also one can put shell extensions into ~/.VirtualBox/shexts and
1128# they will also be picked up, so this way one can exchange
1129# shell extensions easily.
1130def addExtsFromFile(ctx, cmds, file):
1131 if not os.path.isfile(file):
1132 return
1133 d = {}
1134 try:
1135 execfile(file, d, d)
1136 for (k,v) in d['commands'].items():
1137 if g_verbose:
1138 print "customize: adding \"%s\" - %s" %(k, v[0])
1139 cmds[k] = [v[0], v[1], file]
1140 except:
1141 print "Error loading user extensions from %s" %(file)
1142 traceback.print_exc()
1143
1144
1145def checkUserExtensions(ctx, cmds, folder):
1146 folder = str(folder)
1147 name = os.path.join(folder, "shellext.py")
1148 addExtsFromFile(ctx, cmds, name)
1149 # also check 'exts' directory for all files
1150 shextdir = os.path.join(folder, "shexts")
1151 if not os.path.isdir(shextdir):
1152 return
1153 exts = os.listdir(shextdir)
1154 for e in exts:
1155 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
1156
1157def getHomeFolder(ctx):
1158 if ctx['remote'] or ctx['vb'] is None:
1159 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
1160 else:
1161 return ctx['vb'].homeFolder
1162
1163def interpret(ctx):
1164 if ctx['remote']:
1165 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
1166 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
1167
1168 vbox = ctx['vb']
1169
1170 if vbox is not None:
1171 print "Running VirtualBox version %s" %(vbox.version)
1172 ctx['perf'] = ctx['global'].getPerfCollector(vbox)
1173 else:
1174 ctx['perf'] = None
1175
1176 home = getHomeFolder(ctx)
1177 checkUserExtensions(ctx, commands, home)
1178
1179 autoCompletion(commands, ctx)
1180
1181 # to allow to print actual host information, we collect info for
1182 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
1183 if ctx['perf']:
1184 try:
1185 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
1186 except:
1187 pass
1188
1189 while True:
1190 try:
1191 cmd = raw_input("vbox> ")
1192 done = runCommand(ctx, cmd)
1193 if done != 0: break
1194 except KeyboardInterrupt:
1195 print '====== You can type quit or q to leave'
1196 break
1197 except EOFError:
1198 break;
1199 except Exception,e:
1200 print e
1201 if g_verbose:
1202 traceback.print_exc()
1203 ctx['global'].waitForEvents(0)
1204 try:
1205 # There is no need to disable metric collection. This is just an example.
1206 if ct['perf']:
1207 ctx['perf'].disable(['*'], [vbox.host])
1208 except:
1209 pass
1210
1211def runCommandCb(ctx, cmd, args):
1212 args.insert(0, cmd)
1213 return runCommandArgs(ctx, args)
1214
1215def main(argv):
1216 style = None
1217 autopath = False
1218 argv.pop(0)
1219 while len(argv) > 0:
1220 if argv[0] == "-w":
1221 style = "WEBSERVICE"
1222 if argv[0] == "-a":
1223 autopath = True
1224 argv.pop(0)
1225
1226 if autopath:
1227 cwd = os.getcwd()
1228 vpp = os.environ.get("VBOX_PROGRAM_PATH")
1229 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
1230 vpp = cwd
1231 print "Autodetected VBOX_PROGRAM_PATH as",vpp
1232 os.environ["VBOX_PROGRAM_PATH"] = cwd
1233 sys.path.append(os.path.join(vpp, "sdk", "installer"))
1234
1235 from vboxapi import VirtualBoxManager
1236 g_virtualBoxManager = VirtualBoxManager(style, None)
1237 ctx = {'global':g_virtualBoxManager,
1238 'mgr':g_virtualBoxManager.mgr,
1239 'vb':g_virtualBoxManager.vbox,
1240 'ifaces':g_virtualBoxManager.constants,
1241 'remote':g_virtualBoxManager.remote,
1242 'type':g_virtualBoxManager.type,
1243 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1244 'machById': lambda id: machById(ctx,id),
1245 'progressBar': lambda p: progressBar(ctx,p),
1246 '_machlist':None
1247 }
1248 interpret(ctx)
1249 g_virtualBoxManager.deinit()
1250 del g_virtualBoxManager
1251
1252if __name__ == '__main__':
1253 main(sys.argv)
Note: See TracBrowser for help on using the repository browser.

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