VirtualBox

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

Last change on this file since 21640 was 21640, checked in by vboxsync, 16 years ago

Python: WS Python bindings fully usable, extend shell to control remote VMs

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