VirtualBox

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

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

Python shell: dark COM magick

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.8 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#################################################################################
19# This program is a simple interactive shell for VirtualBox. You can query #
20# information and issue commands from a simple command line. #
21# #
22# It also provides you with examples on how to use VirtualBox's Python API. #
23# This shell is even somewhat documented and supports TAB-completion and #
24# history if you have Python readline installed. #
25# #
26# Enjoy. #
27################################################################################
28
29import os,sys
30import traceback
31import shlex
32import time
33
34# Simple implementation of IConsoleCallback, one can use it as skeleton
35# for custom implementations
36class GuestMonitor:
37 def __init__(self, mach):
38 self.mach = mach
39
40 def onMousePointerShapeChange(self, visible, alpha, xHot, yHot, width, height, shape):
41 print "%s: onMousePointerShapeChange: visible=%d" %(self.mach.name, visible)
42 def onMouseCapabilityChange(self, supportsAbsolute, needsHostCursor):
43 print "%s: onMouseCapabilityChange: needsHostCursor=%d" %(self.mach.name, needsHostCursor)
44
45 def onKeyboardLedsChange(self, numLock, capsLock, scrollLock):
46 print "%s: onKeyboardLedsChange capsLock=%d" %(self.mach.name, capsLock)
47
48 def onStateChange(self, state):
49 print "%s: onStateChange state=%d" %(self.mach.name, state)
50
51 def onAdditionsStateChange(self):
52 print "%s: onAdditionsStateChange" %(self.mach.name)
53
54 def onDVDDriveChange(self):
55 print "%s: onDVDDriveChange" %(self.mach.name)
56
57 def onFloppyDriveChange(self):
58 print "%s: onFloppyDriveChange" %(self.mach.name)
59
60 def onNetworkAdapterChange(self, adapter):
61 print "%s: onNetworkAdapterChange" %(self.mach.name)
62
63 def onSerialPortChange(self, port):
64 print "%s: onSerialPortChange" %(self.mach.name)
65
66 def onParallelPortChange(self, port):
67 print "%s: onParallelPortChange" %(self.mach.name)
68
69 def onStorageControllerChange(self):
70 print "%s: onStorageControllerChange" %(self.mach.name)
71
72 def onVRDPServerChange(self):
73 print "%s: onVRDPServerChange" %(self.mach.name)
74
75 def onUSBControllerChange(self):
76 print "%s: onUSBControllerChange" %(self.mach.name)
77
78 def onUSBDeviceStateChange(self, device, attached, error):
79 print "%s: onUSBDeviceStateChange" %(self.mach.name)
80
81 def onSharedFolderChange(self, scope):
82 print "%s: onSharedFolderChange" %(self.mach.name)
83
84 def onRuntimeError(self, fatal, id, message):
85 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
86
87 def onCanShowWindow(self):
88 print "%s: onCanShowWindow" %(self.mach.name)
89 return True
90
91 def onShowWindow(self, winId):
92 print "%s: onShowWindow: %d" %(self.mach.name, winId)
93
94class VBoxMonitor:
95 def __init__(self, params):
96 self.vbox = params[0]
97 self.isMscom = params[1]
98 pass
99
100 def onMachineStateChange(self, id, state):
101 print "onMachineStateChange: %s %d" %(id, state)
102
103 def onMachineDataChange(self,id):
104 print "onMachineDataChange: %s" %(id)
105
106 def onExtraDataCanChange(self, id, key, value):
107 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
108 # Witty COM bridge thinks if someone wishes to return tuple, hresult
109 # is one of values we want to return
110 if self.isMscom:
111 return "", 0, True
112 else:
113 return True, ""
114
115 def onExtraDataChange(self, id, key, value):
116 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
117
118 def onMediaRegistered(self, id, type, registered):
119 print "onMediaRegistered: %s" %(id)
120
121 def onMachineRegistered(self, id, registred):
122 print "onMachineRegistered: %s" %(id)
123
124 def onSessionStateChange(self, id, state):
125 print "onSessionStateChange: %s %d" %(id, state)
126
127 def onSnapshotTaken(self, mach, id):
128 print "onSnapshotTaken: %s %s" %(mach, id)
129
130 def onSnapshotDiscarded(self, mach, id):
131 print "onSnapshotDiscarded: %s %s" %(mach, id)
132
133 def onSnapshotChange(self, mach, id):
134 print "onSnapshotChange: %s %s" %(mach, id)
135
136 def onGuestPropertyChange(self, id, name, newValue, flags):
137 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
138
139g_hasreadline = 1
140try:
141 import readline
142 import rlcompleter
143except:
144 g_hasreadline = 0
145
146
147if g_hasreadline:
148 class CompleterNG(rlcompleter.Completer):
149 def __init__(self, dic, ctx):
150 self.ctx = ctx
151 return rlcompleter.Completer.__init__(self,dic)
152
153 def complete(self, text, state):
154 """
155 taken from:
156 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
157 """
158 if text == "":
159 return ['\t',None][state]
160 else:
161 return rlcompleter.Completer.complete(self,text,state)
162
163 def global_matches(self, text):
164 """
165 Compute matches when text is a simple name.
166 Return a list of all names currently defined
167 in self.namespace that match.
168 """
169
170 matches = []
171 n = len(text)
172
173 for list in [ self.namespace ]:
174 for word in list:
175 if word[:n] == text:
176 matches.append(word)
177
178
179 try:
180 for m in getMachines(self.ctx):
181 # although it has autoconversion, we need to cast
182 # explicitly for subscripts to work
183 word = str(m.name)
184 if word[:n] == text:
185 matches.append(word)
186 word = str(m.id)
187 if word[0] == '{':
188 word = word[1:-1]
189 if word[:n] == text:
190 matches.append(word)
191 except Exception,e:
192 traceback.print_exc()
193 print e
194
195 return matches
196
197
198def autoCompletion(commands, ctx):
199 if not g_hasreadline:
200 return
201
202 comps = {}
203 for (k,v) in commands.items():
204 comps[k] = None
205 completer = CompleterNG(comps, ctx)
206 readline.set_completer(completer.complete)
207 readline.parse_and_bind("tab: complete")
208
209g_verbose = True
210
211def split_no_quotes(s):
212 return shlex.split(s)
213
214def progressBar(ctx,p,wait=1000):
215 try:
216 while not p.completed:
217 print "%d %%\r" %(p.percent),
218 sys.stdout.flush()
219 p.waitForCompletion(wait)
220 except KeyboardInterrupt:
221 print "Interrupted."
222
223def createVm(ctx,name,kind,base):
224 mgr = ctx['mgr']
225 vb = ctx['vb']
226 mach = vb.createMachine(name, kind, base, "")
227 mach.saveSettings()
228 print "created machine with UUID",mach.id
229 vb.registerMachine(mach)
230 # update cache
231 getMachines(ctx, True)
232
233def removeVm(ctx,mach):
234 mgr = ctx['mgr']
235 vb = ctx['vb']
236 id = mach.id
237 print "removing machine ",mach.name,"with UUID",id
238 session = ctx['global'].openMachineSession(id)
239 try:
240 mach = session.machine
241 for d in ctx['global'].getArray(mach, 'hardDiskAttachments'):
242 mach.detachHardDisk(d.controller, d.port, d.device)
243 except:
244 traceback.print_exc()
245 mach.saveSettings()
246 ctx['global'].closeMachineSession(session)
247 mach = vb.unregisterMachine(id)
248 if mach:
249 mach.deleteSettings()
250 # update cache
251 getMachines(ctx, True)
252
253def startVm(ctx,mach,type):
254 mgr = ctx['mgr']
255 vb = ctx['vb']
256 perf = ctx['perf']
257 session = mgr.getSessionObject(vb)
258 uuid = mach.id
259 progress = vb.openRemoteSession(session, uuid, type, "")
260 progressBar(ctx, progress, 100)
261 completed = progress.completed
262 rc = int(progress.resultCode)
263 print "Completed:", completed, "rc:",hex(rc&0xffffffff)
264 if rc == 0:
265 # we ignore exceptions to allow starting VM even if
266 # perf collector cannot be started
267 if perf:
268 try:
269 perf.setup(['*'], [mach], 10, 15)
270 except Exception,e:
271 print e
272 if g_verbose:
273 traceback.print_exc()
274 pass
275 # if session not opened, close doesn't make sense
276 session.close()
277 else:
278 # Not yet implemented error string query API for remote API
279 if not ctx['remote']:
280 print session.QueryErrorObject(rc)
281
282def getMachines(ctx, invalidate = False):
283 if ctx['vb'] is not None:
284 if ctx['_machlist'] is None or invalidate:
285 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
286 return ctx['_machlist']
287 else:
288 return []
289
290def asState(var):
291 if var:
292 return 'on'
293 else:
294 return 'off'
295
296def guestStats(ctx,mach):
297 if not ctx['perf']:
298 return
299 for metric in ctx['perf'].query(["*"], [mach]):
300 print metric['name'], metric['values_as_string']
301
302def guestExec(ctx, machine, console, cmds):
303 exec cmds
304
305def monitorGuest(ctx, machine, console, dur):
306 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
307 console.registerCallback(cb)
308 if dur == -1:
309 # not infinity, but close enough
310 dur = 100000
311 try:
312 end = time.time() + dur
313 while time.time() < end:
314 ctx['global'].waitForEvents(500)
315 # We need to catch all exceptions here, otherwise callback will never be unregistered
316 except:
317 pass
318 console.unregisterCallback(cb)
319
320
321def monitorVBox(ctx, dur):
322 vbox = ctx['vb']
323 isMscom = (ctx['global'].type == 'MSCOM')
324 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
325 vbox.registerCallback(cb)
326 if dur == -1:
327 # not infinity, but close enough
328 dur = 100000
329 try:
330 end = time.time() + dur
331 while time.time() < end:
332 ctx['global'].waitForEvents(500)
333 # We need to catch all exceptions here, otherwise callback will never be unregistered
334 except:
335 pass
336 vbox.unregisterCallback(cb)
337
338def cmdExistingVm(ctx,mach,cmd,args):
339 mgr=ctx['mgr']
340 vb=ctx['vb']
341 session = mgr.getSessionObject(vb)
342 uuid = mach.id
343 try:
344 progress = vb.openExistingSession(session, uuid)
345 except Exception,e:
346 print "Session to '%s' not open: %s" %(mach.name,e)
347 if g_verbose:
348 traceback.print_exc()
349 return
350 if session.state != ctx['ifaces'].SessionState_Open:
351 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
352 return
353 # unfortunately IGuest is suppressed, thus WebServices knows not about it
354 # this is an example how to handle local only functionality
355 if ctx['remote'] and cmd == 'stats2':
356 print 'Trying to use local only functionality, ignored'
357 return
358 console=session.console
359 ops={'pause': lambda: console.pause(),
360 'resume': lambda: console.resume(),
361 'powerdown': lambda: console.powerDown(),
362 'powerbutton': lambda: console.powerButton(),
363 'stats': lambda: guestStats(ctx, mach),
364 'guest': lambda: guestExec(ctx, mach, console, args),
365 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
366 'save': lambda: progressBar(ctx,console.saveState())
367 }
368 try:
369 ops[cmd]()
370 except Exception, e:
371 print 'failed: ',e
372 if g_verbose:
373 traceback.print_exc()
374
375 session.close()
376
377def machById(ctx,id):
378 mach = None
379 for m in getMachines(ctx):
380 if m.name == id:
381 mach = m
382 break
383 mid = str(m.id)
384 if mid[0] == '{':
385 mid = mid[1:-1]
386 if mid == id:
387 mach = m
388 break
389 return mach
390
391def argsToMach(ctx,args):
392 if len(args) < 2:
393 print "usage: %s [vmname|uuid]" %(args[0])
394 return None
395 id = args[1]
396 m = machById(ctx, id)
397 if m == None:
398 print "Machine '%s' is unknown, use list command to find available machines" %(id)
399 return m
400
401def helpSingleCmd(cmd,h,sp):
402 if sp != 0:
403 spec = " [ext from "+sp+"]"
404 else:
405 spec = ""
406 print " %s: %s%s" %(cmd,h,spec)
407
408def helpCmd(ctx, args):
409 if len(args) == 1:
410 print "Help page:"
411 names = commands.keys()
412 names.sort()
413 for i in names:
414 helpSingleCmd(i, commands[i][0], commands[i][2])
415 else:
416 cmd = args[1]
417 c = commands.get(cmd)
418 if c == None:
419 print "Command '%s' not known" %(cmd)
420 else:
421 helpSingleCmd(cmd, c[0], c[2])
422 return 0
423
424def listCmd(ctx, args):
425 for m in getMachines(ctx, True):
426 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
427 return 0
428
429def getControllerType(type):
430 if type == 0:
431 return "Null"
432 elif type == 1:
433 return "LsiLogic"
434 elif type == 2:
435 return "BusLogic"
436 elif type == 3:
437 return "IntelAhci"
438 elif type == 4:
439 return "PIIX3"
440 elif type == 5:
441 return "PIIX4"
442 elif type == 6:
443 return "ICH6"
444 else:
445 return "Unknown"
446
447def infoCmd(ctx,args):
448 if (len(args) < 2):
449 print "usage: info [vmname|uuid]"
450 return 0
451 mach = argsToMach(ctx,args)
452 if mach == None:
453 return 0
454 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
455 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
456 print " Name [name]: %s" %(mach.name)
457 print " ID [n/a]: %s" %(mach.id)
458 print " OS Type [n/a]: %s" %(os.description)
459 print
460 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
461 print " RAM [memorySize]: %dM" %(mach.memorySize)
462 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
463 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
464 print
465 print " Clipboard mode [clipboardMode]: %d" %(mach.clipboardMode)
466 print " Machine status [n/a]: %d" % (mach.sessionState)
467 print
468 bios = mach.BIOSSettings
469 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
470 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
471 print " PAE [PAEEnabled]: %s" %(asState(int(mach.PAEEnabled)))
472 print " Hardware virtualization [HWVirtExEnabled]: " + asState(mach.HWVirtExEnabled)
473 print " VPID support [HWVirtExVPIDEnabled]: " + asState(mach.HWVirtExVPIDEnabled)
474 print " Hardware 3d acceleration[accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
475 print " Nested paging [HWVirtExNestedPagingEnabled]: " + asState(mach.HWVirtExNestedPagingEnabled)
476 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
477 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
478
479 controllers = ctx['global'].getArray(mach, 'storageControllers')
480 if controllers:
481 print
482 print " Controllers:"
483 for controller in controllers:
484 print " %s %s bus: %d" % (controller.name, getControllerType(controller.controllerType), controller.bus)
485
486 disks = ctx['global'].getArray(mach, 'hardDiskAttachments')
487 if disks:
488 print
489 print " Hard disk(s):"
490 for disk in disks:
491 print " Controller: %s port: %d device: %d:" % (disk.controller, disk.port, disk.device)
492 hd = disk.hardDisk
493 print " id: %s" %(hd.id)
494 print " location: %s" %(hd.location)
495 print " name: %s" %(hd.name)
496 print " format: %s" %(hd.format)
497 print
498
499 dvd = mach.DVDDrive
500 if dvd.getHostDrive():
501 hdvd = dvd.getHostDrive()
502 print " DVD:"
503 print " Host disk: %s" %(hdvd.name)
504 print
505
506 if dvd.getImage():
507 vdvd = dvd.getImage()
508 print " DVD:"
509 print " Image at: %s" %(vdvd.location)
510 print " Size: %s" %(vdvd.size)
511 print " Id: %s" %(vdvd.id)
512 print
513
514 floppy = mach.floppyDrive
515 if floppy.getHostDrive():
516 hfloppy = floppy.getHostDrive()
517 print " Floppy:"
518 print " Host disk: %s" %(hfloppy.name)
519 print
520
521 if floppy.getImage():
522 vfloppy = floppy.getImage()
523 print " Floppy:"
524 print " Image at: %s" %(vfloppy.location)
525 print " Size: %s" %(vfloppy.size)
526 print
527
528 return 0
529
530def startCmd(ctx, args):
531 mach = argsToMach(ctx,args)
532 if mach == None:
533 return 0
534 if len(args) > 2:
535 type = args[2]
536 else:
537 type = "gui"
538 startVm(ctx, mach, type)
539 return 0
540
541def createCmd(ctx, args):
542 if (len(args) < 3 or len(args) > 4):
543 print "usage: create name ostype <basefolder>"
544 return 0
545 name = args[1]
546 oskind = args[2]
547 if len(args) == 4:
548 base = args[3]
549 else:
550 base = ''
551 try:
552 ctx['vb'].getGuestOSType(oskind)
553 except Exception, e:
554 print 'Unknown OS type:',oskind
555 return 0
556 createVm(ctx, name, oskind, base)
557 return 0
558
559def removeCmd(ctx, args):
560 mach = argsToMach(ctx,args)
561 if mach == None:
562 return 0
563 removeVm(ctx, mach)
564 return 0
565
566def pauseCmd(ctx, args):
567 mach = argsToMach(ctx,args)
568 if mach == None:
569 return 0
570 cmdExistingVm(ctx, mach, 'pause', '')
571 return 0
572
573def powerdownCmd(ctx, args):
574 mach = argsToMach(ctx,args)
575 if mach == None:
576 return 0
577 cmdExistingVm(ctx, mach, 'powerdown', '')
578 return 0
579
580def powerbuttonCmd(ctx, args):
581 mach = argsToMach(ctx,args)
582 if mach == None:
583 return 0
584 cmdExistingVm(ctx, mach, 'powerbutton', '')
585 return 0
586
587def resumeCmd(ctx, args):
588 mach = argsToMach(ctx,args)
589 if mach == None:
590 return 0
591 cmdExistingVm(ctx, mach, 'resume', '')
592 return 0
593
594def saveCmd(ctx, args):
595 mach = argsToMach(ctx,args)
596 if mach == None:
597 return 0
598 cmdExistingVm(ctx, mach, 'save', '')
599 return 0
600
601def statsCmd(ctx, args):
602 mach = argsToMach(ctx,args)
603 if mach == None:
604 return 0
605 cmdExistingVm(ctx, mach, 'stats', '')
606 return 0
607
608def guestCmd(ctx, args):
609 if (len(args) < 3):
610 print "usage: guest name commands"
611 return 0
612 mach = argsToMach(ctx,args)
613 if mach == None:
614 return 0
615 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
616 return 0
617
618def setvarCmd(ctx, args):
619 if (len(args) < 4):
620 print "usage: setvar [vmname|uuid] expr value"
621 return 0
622 mach = argsToMach(ctx,args)
623 if mach == None:
624 return 0
625 session = ctx['global'].openMachineSession(mach.id)
626 mach = session.machine
627 expr = 'mach.'+args[2]+' = '+args[3]
628 print "Executing",expr
629 try:
630 exec expr
631 except Exception, e:
632 print 'failed: ',e
633 if g_verbose:
634 traceback.print_exc()
635 mach.saveSettings()
636 session.close()
637 return 0
638
639def quitCmd(ctx, args):
640 return 1
641
642def aliasCmd(ctx, args):
643 if (len(args) == 3):
644 aliases[args[1]] = args[2]
645 return 0
646
647 for (k,v) in aliases.items():
648 print "'%s' is an alias for '%s'" %(k,v)
649 return 0
650
651def verboseCmd(ctx, args):
652 global g_verbose
653 g_verbose = not g_verbose
654 return 0
655
656def getUSBStateString(state):
657 if state == 0:
658 return "NotSupported"
659 elif state == 1:
660 return "Unavailable"
661 elif state == 2:
662 return "Busy"
663 elif state == 3:
664 return "Available"
665 elif state == 4:
666 return "Held"
667 elif state == 5:
668 return "Captured"
669 else:
670 return "Unknown"
671
672def hostCmd(ctx, args):
673 host = ctx['vb'].host
674 cnt = host.processorCount
675 print "Processor count:",cnt
676 for i in range(0,cnt):
677 print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
678
679 print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
680 print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
681 if host.Acceleration3DAvailable:
682 print "3D acceleration available"
683 else:
684 print "3D acceleration NOT available"
685
686 print "Network interfaces:"
687 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
688 print " %s (%s)" %(ni.name, ni.IPAddress)
689
690 print "DVD drives:"
691 for dd in ctx['global'].getArray(host, 'DVDDrives'):
692 print " %s - %s" %(dd.name, dd.description)
693
694 print "USB devices:"
695 for ud in ctx['global'].getArray(host, 'USBDevices'):
696 print " %s (vendorId=%d productId=%d serial=%s) %s" %(ud.product, ud.vendorId, ud.productId, ud.serialNumber, getUSBStateString(ud.state))
697
698 if ctx['perf']:
699 for metric in ctx['perf'].query(["*"], [host]):
700 print metric['name'], metric['values_as_string']
701
702 return 0
703
704def monitorGuestCmd(ctx, args):
705 if (len(args) < 2):
706 print "usage: monitorGuest name (duration)"
707 return 0
708 mach = argsToMach(ctx,args)
709 if mach == None:
710 return 0
711 dur = 5
712 if len(args) > 2:
713 dur = float(args[2])
714 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
715 return 0
716
717def monitorVBoxCmd(ctx, args):
718 if (len(args) > 2):
719 print "usage: monitorVBox (duration)"
720 return 0
721 dur = 5
722 if len(args) > 1:
723 dur = float(args[1])
724 monitorVBox(ctx, dur)
725 return 0
726
727def getAdapterType(ctx, type):
728 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
729 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
730 return "pcnet"
731 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
732 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
733 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
734 return "e1000"
735 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
736 return None
737 else:
738 raise Exception("Unknown adapter type: "+type)
739
740
741def portForwardCmd(ctx, args):
742 if (len(args) != 5):
743 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
744 return 0
745 mach = argsToMach(ctx,args)
746 if mach == None:
747 return 0
748 adapterNum = int(args[2])
749 hostPort = int(args[3])
750 guestPort = int(args[4])
751 proto = "TCP"
752 session = ctx['global'].openMachineSession(mach.id)
753 mach = session.machine
754
755 adapter = mach.getNetworkAdapter(adapterNum)
756 adapterType = getAdapterType(ctx, adapter.adapterType)
757
758 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
759 config = "VBoxInternal/Devices/" + adapterType + "/"
760 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
761
762 mach.setExtraData(config + "/Protocol", proto)
763 mach.setExtraData(config + "/HostPort", str(hostPort))
764 mach.setExtraData(config + "/GuestPort", str(guestPort))
765
766 mach.saveSettings()
767 session.close()
768
769 return 0
770
771
772def showLogCmd(ctx, args):
773 if (len(args) < 2):
774 print "usage: showLog <vm> <num>"
775 return 0
776 mach = argsToMach(ctx,args)
777 if mach == None:
778 return 0
779
780 log = "VBox.log"
781 if (len(args) > 2):
782 log += "."+args[2]
783 fileName = os.path.join(mach.logFolder, log)
784
785 try:
786 lf = open(fileName, 'r')
787 except IOError,e:
788 print "cannot open: ",e
789 return 0
790
791 for line in lf:
792 print line,
793 lf.close()
794
795 return 0
796
797def evalCmd(ctx, args):
798 expr = ' '.join(args[1:])
799 try:
800 exec expr
801 except Exception, e:
802 print 'failed: ',e
803 if g_verbose:
804 traceback.print_exc()
805 return 0
806
807def reloadExtCmd(ctx, args):
808 # maybe will want more args smartness
809 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
810 autoCompletion(commands, ctx)
811 return 0
812
813
814def runScriptCmd(ctx, args):
815 if (len(args) != 2):
816 print "usage: runScript <script>"
817 return 0
818 try:
819 lf = open(args[1], 'r')
820 except IOError,e:
821 print "cannot open:",args[1], ":",e
822 return 0
823
824 try:
825 for line in lf:
826 done = runCommand(ctx, line)
827 if done != 0: break
828 except Exception,e:
829 print "error:",e
830 if g_verbose:
831 traceback.print_exc()
832 lf.close()
833 return 0
834
835def sleepCmd(ctx, args):
836 if (len(args) != 2):
837 print "usage: sleep <secs>"
838 return 0
839
840 try:
841 time.sleep(float(args[1]))
842 except:
843 # to allow sleep interrupt
844 pass
845 return 0
846
847
848def shellCmd(ctx, args):
849 if (len(args) < 2):
850 print "usage: shell <commands>"
851 return 0
852 cmd = ' '.join(args[1:])
853 try:
854 os.system(cmd)
855 except KeyboardInterrupt:
856 # to allow shell command interruption
857 pass
858 return 0
859
860
861def connectCmd(ctx, args):
862 if (len(args) > 4):
863 print "usage: connect [url] [username] [passwd]"
864 return 0
865
866 if ctx['vb'] is not None:
867 print "Already connected, disconnect first..."
868 return 0
869
870 if (len(args) > 1):
871 url = args[1]
872 else:
873 url = None
874
875 if (len(args) > 2):
876 user = args[2]
877 else:
878 user = ""
879
880 if (len(args) > 3):
881 passwd = args[3]
882 else:
883 passwd = ""
884
885 vbox = ctx['global'].platform.connect(url, user, passwd)
886 ctx['vb'] = vbox
887 print "Running VirtualBox version %s" %(vbox.version)
888 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
889 return 0
890
891def disconnectCmd(ctx, args):
892 if (len(args) != 1):
893 print "usage: disconnect"
894 return 0
895
896 if ctx['vb'] is None:
897 print "Not connected yet."
898 return 0
899
900 try:
901 ctx['global'].platform.disconnect()
902 except:
903 ctx['vb'] = None
904 raise
905
906 ctx['vb'] = None
907 return 0
908
909def exportVMCmd(ctx, args):
910 import sys
911
912 if len(args) < 3:
913 print "usage: exportVm <machine> <path> <format> <license>"
914 return 0
915 mach = ctx['machById'](args[1])
916 if mach is None:
917 return 0
918 path = args[2]
919 if (len(args) > 3):
920 format = args[3]
921 else:
922 format = "ovf-1.0"
923 if (len(args) > 4):
924 license = args[4]
925 else:
926 license = "GPL"
927
928 app = ctx['vb'].createAppliance()
929 desc = mach.export(app)
930 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
931 p = app.write(format, path)
932 progressBar(ctx, p)
933 print "Exported to %s in format %s" %(path, format)
934 return 0
935
936aliases = {'s':'start',
937 'i':'info',
938 'l':'list',
939 'h':'help',
940 'a':'alias',
941 'q':'quit', 'exit':'quit',
942 'v':'verbose'}
943
944commands = {'help':['Prints help information', helpCmd, 0],
945 'start':['Start virtual machine by name or uuid', startCmd, 0],
946 'create':['Create virtual machine', createCmd, 0],
947 'remove':['Remove virtual machine', removeCmd, 0],
948 'pause':['Pause virtual machine', pauseCmd, 0],
949 'resume':['Resume virtual machine', resumeCmd, 0],
950 'save':['Save execution state of virtual machine', saveCmd, 0],
951 'stats':['Stats for virtual machine', statsCmd, 0],
952 'powerdown':['Power down virtual machine', powerdownCmd, 0],
953 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
954 'list':['Shows known virtual machines', listCmd, 0],
955 'info':['Shows info on machine', infoCmd, 0],
956 'alias':['Control aliases', aliasCmd, 0],
957 'verbose':['Toggle verbosity', verboseCmd, 0],
958 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
959 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
960 'quit':['Exits', quitCmd, 0],
961 'host':['Show host information', hostCmd, 0],
962 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
963 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
964 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
965 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
966 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
967 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
968 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
969 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
970 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
971 'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0]
972 }
973
974def runCommandArgs(ctx, args):
975 c = args[0]
976 if aliases.get(c, None) != None:
977 c = aliases[c]
978 ci = commands.get(c,None)
979 if ci == None:
980 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
981 return 0
982 return ci[1](ctx, args)
983
984
985def runCommand(ctx, cmd):
986 if len(cmd) == 0: return 0
987 args = split_no_quotes(cmd)
988 if len(args) == 0: return 0
989 return runCommandArgs(ctx, args)
990
991#
992# To write your own custom commands to vboxshell, create
993# file ~/.VirtualBox/shellext.py with content like
994#
995# def runTestCmd(ctx, args):
996# print "Testy test", ctx['vb']
997# return 0
998#
999# commands = {
1000# 'test': ['Test help', runTestCmd]
1001# }
1002# and issue reloadExt shell command.
1003# This file also will be read automatically on startup or 'reloadExt'.
1004#
1005# Also one can put shell extensions into ~/.VirtualBox/shexts and
1006# they will also be picked up, so this way one can exchange
1007# shell extensions easily.
1008def addExtsFromFile(ctx, cmds, file):
1009 if not os.path.isfile(file):
1010 return
1011 d = {}
1012 try:
1013 execfile(file, d, d)
1014 for (k,v) in d['commands'].items():
1015 if g_verbose:
1016 print "customize: adding \"%s\" - %s" %(k, v[0])
1017 cmds[k] = [v[0], v[1], file]
1018 except:
1019 print "Error loading user extensions from %s" %(file)
1020 traceback.print_exc()
1021
1022
1023def checkUserExtensions(ctx, cmds, folder):
1024 folder = str(folder)
1025 name = os.path.join(folder, "shellext.py")
1026 addExtsFromFile(ctx, cmds, name)
1027 # also check 'exts' directory for all files
1028 shextdir = os.path.join(folder, "shexts")
1029 if not os.path.isdir(shextdir):
1030 return
1031 exts = os.listdir(shextdir)
1032 for e in exts:
1033 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
1034
1035def getHomeFolder(ctx):
1036 if ctx['remote'] or ctx['vb'] is None:
1037 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
1038 else:
1039 return ctx['vb'].homeFolder
1040
1041def interpret(ctx):
1042 if ctx['remote']:
1043 commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
1044 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
1045
1046 vbox = ctx['vb']
1047
1048 if vbox is not None:
1049 print "Running VirtualBox version %s" %(vbox.version)
1050 ctx['perf'] = ctx['global'].getPerfCollector(vbox)
1051 else:
1052 ctx['perf'] = None
1053
1054 home = getHomeFolder(ctx)
1055 checkUserExtensions(ctx, commands, home)
1056
1057 autoCompletion(commands, ctx)
1058
1059 # to allow to print actual host information, we collect info for
1060 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
1061 if ctx['perf']:
1062 try:
1063 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
1064 except:
1065 pass
1066
1067 while True:
1068 try:
1069 cmd = raw_input("vbox> ")
1070 done = runCommand(ctx, cmd)
1071 if done != 0: break
1072 except KeyboardInterrupt:
1073 print '====== You can type quit or q to leave'
1074 break
1075 except EOFError:
1076 break;
1077 except Exception,e:
1078 print e
1079 if g_verbose:
1080 traceback.print_exc()
1081
1082 try:
1083 # There is no need to disable metric collection. This is just an example.
1084 if ct['perf']:
1085 ctx['perf'].disable(['*'], [vbox.host])
1086 except:
1087 pass
1088
1089def runCommandCb(ctx, cmd, args):
1090 args.insert(0, cmd)
1091 return runCommandArgs(ctx, args)
1092
1093def main(argv):
1094 style = None
1095 autopath = False
1096 argv.pop(0)
1097 while len(argv) > 0:
1098 if argv[0] == "-w":
1099 style = "WEBSERVICE"
1100 if argv[0] == "-a":
1101 autopath = True
1102 argv.pop(0)
1103
1104 if autopath:
1105 cwd = os.getcwd()
1106 vpp = os.environ.get("VBOX_PROGRAM_PATH")
1107 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
1108 vpp = cwd
1109 print "Autodetected VBOX_PROGRAM_PATH as",vpp
1110 os.environ["VBOX_PROGRAM_PATH"] = cwd
1111 sys.path.append(os.path.join(vpp, "sdk", "installer"))
1112
1113 from vboxapi import VirtualBoxManager
1114 g_virtualBoxManager = VirtualBoxManager(style, None)
1115 ctx = {'global':g_virtualBoxManager,
1116 'mgr':g_virtualBoxManager.mgr,
1117 'vb':g_virtualBoxManager.vbox,
1118 'ifaces':g_virtualBoxManager.constants,
1119 'remote':g_virtualBoxManager.remote,
1120 'type':g_virtualBoxManager.type,
1121 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1122 'machById': lambda id: machById(ctx,id),
1123 'progressBar': lambda p: progressBar(ctx,p),
1124 '_machlist':None
1125 }
1126 interpret(ctx)
1127 g_virtualBoxManager.deinit()
1128 del g_virtualBoxManager
1129
1130if __name__ == '__main__':
1131 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