VirtualBox

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

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

Main: more events

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 98.5 KB
Line 
1#!/usr/bin/python
2#
3# Copyright (C) 2009-2010 Oracle Corporation
4#
5# This file is part of VirtualBox Open Source Edition (OSE), as
6# available from http://www.215389.xyz. This file is free software;
7# you can redistribute it and/or modify it under the terms of the GNU
8# General Public License (GPL) as published by the Free Software
9# Foundation, in version 2 as it comes in the "COPYING" file of the
10# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
11# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
12#
13#################################################################################
14# This program is a simple interactive shell for VirtualBox. You can query #
15# information and issue commands from a simple command line. #
16# #
17# It also provides you with examples on how to use VirtualBox's Python API. #
18# This shell is even somewhat documented, supports TAB-completion and #
19# history if you have Python readline installed. #
20# #
21# Finally, shell allows arbitrary custom extensions, just create #
22# .VirtualBox/shexts/ and drop your extensions there. #
23# Enjoy. #
24################################################################################
25
26import os,sys
27import traceback
28import shlex
29import time
30import re
31import platform
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 shape=%d bytes" %(self.mach.name, visible,len(shape))
41
42 def onMouseCapabilityChange(self, supportsAbsolute, supportsRelative, needsHostCursor):
43 print "%s: onMouseCapabilityChange: supportsAbsolute = %d, supportsRelative = %d, needsHostCursor = %d" %(self.mach.name, supportsAbsolute, supportsRelative, 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 onNetworkAdapterChange(self, adapter):
55 print "%s: onNetworkAdapterChange" %(self.mach.name)
56
57 def onSerialPortChange(self, port):
58 print "%s: onSerialPortChange" %(self.mach.name)
59
60 def onParallelPortChange(self, port):
61 print "%s: onParallelPortChange" %(self.mach.name)
62
63 def onStorageControllerChange(self):
64 print "%s: onStorageControllerChange" %(self.mach.name)
65
66 def onMediumChange(self, attachment):
67 print "%s: onMediumChange" %(self.mach.name)
68
69 def onVRDPServerChange(self):
70 print "%s: onVRDPServerChange" %(self.mach.name)
71
72 def onUSBControllerChange(self):
73 print "%s: onUSBControllerChange" %(self.mach.name)
74
75 def onUSBDeviceStateChange(self, device, attached, error):
76 print "%s: onUSBDeviceStateChange" %(self.mach.name)
77
78 def onSharedFolderChange(self, scope):
79 print "%s: onSharedFolderChange" %(self.mach.name)
80
81 def onRuntimeError(self, fatal, id, message):
82 print "%s: onRuntimeError fatal=%d message=%s" %(self.mach.name, fatal, message)
83
84 def onCanShowWindow(self):
85 print "%s: onCanShowWindow" %(self.mach.name)
86 return True
87
88 def onShowWindow(self, winId):
89 print "%s: onShowWindow: %d" %(self.mach.name, winId)
90
91class VBoxMonitor:
92 def __init__(self, params):
93 self.vbox = params[0]
94 self.isMscom = params[1]
95 pass
96
97 def onMachineStateChange(self, id, state):
98 print "onMachineStateChange: %s %d" %(id, state)
99
100 def onMachineDataChange(self,id):
101 print "onMachineDataChange: %s" %(id)
102
103 def onExtraDataCanChange(self, id, key, value):
104 print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
105 # Witty COM bridge thinks if someone wishes to return tuple, hresult
106 # is one of values we want to return
107 if self.isMscom:
108 return "", 0, True
109 else:
110 return True, ""
111
112 def onExtraDataChange(self, id, key, value):
113 print "onExtraDataChange: %s %s=>%s" %(id, key, value)
114
115 def onMediaRegistered(self, id, type, registered):
116 print "onMediaRegistered: %s" %(id)
117
118 def onMachineRegistered(self, id, registred):
119 print "onMachineRegistered: %s" %(id)
120
121 def onSessionStateChange(self, id, state):
122 print "onSessionStateChange: %s %d" %(id, state)
123
124 def onSnapshotTaken(self, mach, id):
125 print "onSnapshotTaken: %s %s" %(mach, id)
126
127 def onSnapshotDeleted(self, mach, id):
128 print "onSnapshotDeleted: %s %s" %(mach, id)
129
130 def onSnapshotChange(self, mach, id):
131 print "onSnapshotChange: %s %s" %(mach, id)
132
133 def onGuestPropertyChange(self, id, name, newValue, flags):
134 print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
135
136g_hasreadline = True
137try:
138 if g_hasreadline:
139 import readline
140 import rlcompleter
141except:
142 g_hasreadline = False
143
144
145g_prompt = "vbox> "
146
147g_hascolors = True
148term_colors = {
149 'red':'\033[31m',
150 'blue':'\033[94m',
151 'green':'\033[92m',
152 'yellow':'\033[93m',
153 'magenta':'\033[35m'
154 }
155def colored(string,color):
156 if not g_hascolors:
157 return string
158 global term_colors
159 col = term_colors.get(color,None)
160 if col:
161 return col+str(string)+'\033[0m'
162 else:
163 return string
164
165if g_hasreadline:
166 import string
167 class CompleterNG(rlcompleter.Completer):
168 def __init__(self, dic, ctx):
169 self.ctx = ctx
170 return rlcompleter.Completer.__init__(self,dic)
171
172 def complete(self, text, state):
173 """
174 taken from:
175 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
176 """
177 if False and text == "":
178 return ['\t',None][state]
179 else:
180 return rlcompleter.Completer.complete(self,text,state)
181
182 def canBePath(self, phrase,word):
183 return word.startswith('/')
184
185 def canBeCommand(self, phrase, word):
186 spaceIdx = phrase.find(" ")
187 begIdx = readline.get_begidx()
188 firstWord = (spaceIdx == -1 or begIdx < spaceIdx)
189 if firstWord:
190 return True
191 if phrase.startswith('help'):
192 return True
193 return False
194
195 def canBeMachine(self,phrase,word):
196 return not self.canBePath(phrase,word) and not self.canBeCommand(phrase, word)
197
198 def global_matches(self, text):
199 """
200 Compute matches when text is a simple name.
201 Return a list of all names currently defined
202 in self.namespace that match.
203 """
204
205 matches = []
206 phrase = readline.get_line_buffer()
207
208 try:
209 if self.canBePath(phrase,text):
210 (dir,rest) = os.path.split(text)
211 n = len(rest)
212 for word in os.listdir(dir):
213 if n == 0 or word[:n] == rest:
214 matches.append(os.path.join(dir,word))
215
216 if self.canBeCommand(phrase,text):
217 n = len(text)
218 for list in [ self.namespace ]:
219 for word in list:
220 if word[:n] == text:
221 matches.append(word)
222
223 if self.canBeMachine(phrase,text):
224 n = len(text)
225 for m in getMachines(self.ctx, False, True):
226 # although it has autoconversion, we need to cast
227 # explicitly for subscripts to work
228 word = re.sub("(?<!\\\\) ", "\\ ", str(m.name))
229 if word[:n] == text:
230 matches.append(word)
231 word = str(m.id)
232 if word[:n] == text:
233 matches.append(word)
234
235 except Exception,e:
236 printErr(e)
237 if g_verbose:
238 traceback.print_exc()
239
240 return matches
241
242def autoCompletion(commands, ctx):
243 if not g_hasreadline:
244 return
245
246 comps = {}
247 for (k,v) in commands.items():
248 comps[k] = None
249 completer = CompleterNG(comps, ctx)
250 readline.set_completer(completer.complete)
251 delims = readline.get_completer_delims()
252 readline.set_completer_delims(re.sub("[\\./-]", "", delims)) # remove some of the delimiters
253 readline.parse_and_bind("set editing-mode emacs")
254 # OSX need it
255 if platform.system() == 'Darwin':
256 # see http://www.certif.com/spec_help/readline.html
257 readline.parse_and_bind ("bind ^I rl_complete")
258 readline.parse_and_bind ("bind ^W ed-delete-prev-word")
259 # Doesn't work well
260 # readline.parse_and_bind ("bind ^R em-inc-search-prev")
261 readline.parse_and_bind("tab: complete")
262
263
264g_verbose = False
265
266def split_no_quotes(s):
267 return shlex.split(s)
268
269def progressBar(ctx,p,wait=1000):
270 try:
271 while not p.completed:
272 print "%s %%\r" %(colored(str(p.percent),'red')),
273 sys.stdout.flush()
274 p.waitForCompletion(wait)
275 ctx['global'].waitForEvents(0)
276 return 1
277 except KeyboardInterrupt:
278 print "Interrupted."
279 if p.cancelable:
280 print "Canceling task..."
281 p.cancel()
282 return 0
283
284def printErr(ctx,e):
285 print colored(str(e), 'red')
286
287def reportError(ctx,progress):
288 ei = progress.errorInfo
289 if ei:
290 print colored("Error in %s: %s" %(ei.component, ei.text), 'red')
291
292def colCat(ctx,str):
293 return colored(str, 'magenta')
294
295def colVm(ctx,vm):
296 return colored(vm, 'blue')
297
298def colPath(ctx,p):
299 return colored(p, 'green')
300
301def colSize(ctx,m):
302 return colored(m, 'red')
303
304def colSizeM(ctx,m):
305 return colored(str(m)+'M', 'red')
306
307def createVm(ctx,name,kind,base):
308 mgr = ctx['mgr']
309 vb = ctx['vb']
310 mach = vb.createMachine(name, kind, base, "", False)
311 mach.saveSettings()
312 print "created machine with UUID",mach.id
313 vb.registerMachine(mach)
314 # update cache
315 getMachines(ctx, True)
316
317def removeVm(ctx,mach):
318 mgr = ctx['mgr']
319 vb = ctx['vb']
320 id = mach.id
321 print "removing machine ",mach.name,"with UUID",id
322 cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
323 mach = vb.unregisterMachine(id)
324 if mach:
325 mach.deleteSettings()
326 # update cache
327 getMachines(ctx, True)
328
329def startVm(ctx,mach,type):
330 mgr = ctx['mgr']
331 vb = ctx['vb']
332 perf = ctx['perf']
333 session = mgr.getSessionObject(vb)
334 uuid = mach.id
335 progress = vb.openRemoteSession(session, uuid, type, "")
336 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
337 # we ignore exceptions to allow starting VM even if
338 # perf collector cannot be started
339 if perf:
340 try:
341 perf.setup(['*'], [mach], 10, 15)
342 except Exception,e:
343 printErr(ctx, e)
344 if g_verbose:
345 traceback.print_exc()
346 # if session not opened, close doesn't make sense
347 session.close()
348 else:
349 reportError(ctx,progress)
350
351class CachedMach:
352 def __init__(self, mach):
353 self.name = mach.name
354 self.id = mach.id
355
356def cacheMachines(ctx,list):
357 result = []
358 for m in list:
359 elem = CachedMach(m)
360 result.append(elem)
361 return result
362
363def getMachines(ctx, invalidate = False, simple=False):
364 if ctx['vb'] is not None:
365 if ctx['_machlist'] is None or invalidate:
366 ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
367 ctx['_machlistsimple'] = cacheMachines(ctx,ctx['_machlist'])
368 if simple:
369 return ctx['_machlistsimple']
370 else:
371 return ctx['_machlist']
372 else:
373 return []
374
375def asState(var):
376 if var:
377 return colored('on', 'green')
378 else:
379 return colored('off', 'green')
380
381def asFlag(var):
382 if var:
383 return 'yes'
384 else:
385 return 'no'
386
387def perfStats(ctx,mach):
388 if not ctx['perf']:
389 return
390 for metric in ctx['perf'].query(["*"], [mach]):
391 print metric['name'], metric['values_as_string']
392
393def guestExec(ctx, machine, console, cmds):
394 exec cmds
395
396def monitorGuest(ctx, machine, console, dur):
397 cb = ctx['global'].createCallback('IConsoleCallback', GuestMonitor, machine)
398 console.registerCallback(cb)
399 if dur == -1:
400 # not infinity, but close enough
401 dur = 100000
402 try:
403 end = time.time() + dur
404 while time.time() < end:
405 ctx['global'].waitForEvents(500)
406 # We need to catch all exceptions here, otherwise callback will never be unregistered
407 except:
408 pass
409 console.unregisterCallback(cb)
410
411
412def monitorVBox(ctx, dur):
413 vbox = ctx['vb']
414 isMscom = (ctx['global'].type == 'MSCOM')
415 cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
416 vbox.registerCallback(cb)
417 if dur == -1:
418 # not infinity, but close enough
419 dur = 100000
420 try:
421 end = time.time() + dur
422 while time.time() < end:
423 ctx['global'].waitForEvents(500)
424 # We need to catch all exceptions here, otherwise callback will never be unregistered
425 except:
426 pass
427 vbox.unregisterCallback(cb)
428
429def monitorVBox2(ctx, dur):
430 vbox = ctx['vb']
431 print vbox.eventSource
432 listener = vbox.eventSource.createListener()
433 if dur == -1:
434 # not infinity, but close enough
435 dur = 100000
436 try:
437 vbox.eventSource.registerListener(listener, [ctx['global'].constants.VBoxEventType_All], False)
438 end = time.time() + dur
439 while time.time() < end:
440 ev = vbox.eventSource.getEvent(500)
441 if ev:
442 print "got event: %s %s" %(ev, str(ev.type))
443 # We need to catch all exceptions here, otherwise callback will never be unregistered
444 except:
445 traceback.print_exc()
446 pass
447 vbox.eventSource.unregisterListener(listener)
448
449
450def takeScreenshot(ctx,console,args):
451 from PIL import Image
452 display = console.display
453 if len(args) > 0:
454 f = args[0]
455 else:
456 f = "/tmp/screenshot.png"
457 if len(args) > 3:
458 screen = int(args[3])
459 else:
460 screen = 0
461 (fbw, fbh, fbbpp) = display.getScreenResolution(screen)
462 if len(args) > 1:
463 w = int(args[1])
464 else:
465 w = fbw
466 if len(args) > 2:
467 h = int(args[2])
468 else:
469 h = fbh
470
471 print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
472 data = display.takeScreenShotToArray(screen, w,h)
473 size = (w,h)
474 mode = "RGBA"
475 im = Image.frombuffer(mode, size, str(data), "raw", mode, 0, 1)
476 im.save(f, "PNG")
477
478
479def teleport(ctx,session,console,args):
480 if args[0].find(":") == -1:
481 print "Use host:port format for teleport target"
482 return
483 (host,port) = args[0].split(":")
484 if len(args) > 1:
485 passwd = args[1]
486 else:
487 passwd = ""
488
489 if len(args) > 2:
490 maxDowntime = int(args[2])
491 else:
492 maxDowntime = 250
493
494 port = int(port)
495 print "Teleporting to %s:%d..." %(host,port)
496 progress = console.teleport(host, port, passwd, maxDowntime)
497 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
498 print "Success!"
499 else:
500 reportError(ctx,progress)
501
502
503def guestStats(ctx,console,args):
504 guest = console.guest
505 # we need to set up guest statistics
506 if len(args) > 0 :
507 update = args[0]
508 else:
509 update = 1
510 if guest.statisticsUpdateInterval != update:
511 guest.statisticsUpdateInterval = update
512 try:
513 time.sleep(float(update)+0.1)
514 except:
515 # to allow sleep interruption
516 pass
517 all_stats = ctx['const'].all_values('GuestStatisticType')
518 cpu = 0
519 for s in all_stats.keys():
520 try:
521 val = guest.getStatistic( cpu, all_stats[s])
522 print "%s: %d" %(s, val)
523 except:
524 # likely not implemented
525 pass
526
527def plugCpu(ctx,machine,session,args):
528 cpu = int(args[0])
529 print "Adding CPU %d..." %(cpu)
530 machine.hotPlugCPU(cpu)
531
532def unplugCpu(ctx,machine,session,args):
533 cpu = int(args[0])
534 print "Removing CPU %d..." %(cpu)
535 machine.hotUnplugCPU(cpu)
536
537def mountIso(ctx,machine,session,args):
538 machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
539 machine.saveSettings()
540
541def cond(c,v1,v2):
542 if c:
543 return v1
544 else:
545 return v2
546
547def printHostUsbDev(ctx,ud):
548 print " %s: %s (vendorId=%d productId=%d serial=%s) %s" %(ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber,asEnumElem(ctx, 'USBDeviceState', ud.state))
549
550def printUsbDev(ctx,ud):
551 print " %s: %s (vendorId=%d productId=%d serial=%s)" %(ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber)
552
553def printSf(ctx,sf):
554 print " name=%s host=%s %s %s" %(sf.name, colPath(ctx,sf.hostPath), cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))
555
556def ginfo(ctx,console, args):
557 guest = console.guest
558 if guest.additionsActive:
559 vers = int(str(guest.additionsVersion))
560 print "Additions active, version %d.%d" %(vers >> 16, vers & 0xffff)
561 print "Support seamless: %s" %(asFlag(guest.supportsSeamless))
562 print "Support graphics: %s" %(asFlag(guest.supportsGraphics))
563 print "Baloon size: %d" %(guest.memoryBalloonSize)
564 print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
565 else:
566 print "No additions"
567 usbs = ctx['global'].getArray(console, 'USBDevices')
568 print "Attached USB:"
569 for ud in usbs:
570 printUsbDev(ctx,ud)
571 rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
572 print "Remote USB:"
573 for ud in rusbs:
574 printHostUsbDev(ctx,ud)
575 print "Transient shared folders:"
576 sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
577 for sf in sfs:
578 printSf(ctx,sf)
579
580def cmdExistingVm(ctx,mach,cmd,args):
581 session = None
582 try:
583 vb = ctx['vb']
584 session = ctx['mgr'].getSessionObject(vb)
585 vb.openExistingSession(session, mach.id)
586 except Exception,e:
587 printErr(ctx, "Session to '%s' not open: %s" %(mach.name,str(e)))
588 if g_verbose:
589 traceback.print_exc()
590 return
591 if session.state != ctx['const'].SessionState_Open:
592 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
593 session.close()
594 return
595 # this could be an example how to handle local only (i.e. unavailable
596 # in Webservices) functionality
597 if ctx['remote'] and cmd == 'some_local_only_command':
598 print 'Trying to use local only functionality, ignored'
599 session.close()
600 return
601 console=session.console
602 ops={'pause': lambda: console.pause(),
603 'resume': lambda: console.resume(),
604 'powerdown': lambda: console.powerDown(),
605 'powerbutton': lambda: console.powerButton(),
606 'stats': lambda: perfStats(ctx, mach),
607 'guest': lambda: guestExec(ctx, mach, console, args),
608 'ginfo': lambda: ginfo(ctx, console, args),
609 'guestlambda': lambda: args[0](ctx, mach, console, args[1:]),
610 'monitorGuest': lambda: monitorGuest(ctx, mach, console, args),
611 'save': lambda: progressBar(ctx,console.saveState()),
612 'screenshot': lambda: takeScreenshot(ctx,console,args),
613 'teleport': lambda: teleport(ctx,session,console,args),
614 'gueststats': lambda: guestStats(ctx, console, args),
615 'plugcpu': lambda: plugCpu(ctx, session.machine, session, args),
616 'unplugcpu': lambda: unplugCpu(ctx, session.machine, session, args),
617 'mountiso': lambda: mountIso(ctx, session.machine, session, args),
618 }
619 try:
620 ops[cmd]()
621 except Exception, e:
622 printErr(ctx,e)
623 if g_verbose:
624 traceback.print_exc()
625
626 session.close()
627
628
629def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
630 session = ctx['global'].openMachineSession(mach.id)
631 mach = session.machine
632 try:
633 cmd(ctx, mach, args)
634 except Exception, e:
635 save = False
636 printErr(ctx,e)
637 if g_verbose:
638 traceback.print_exc()
639 if save:
640 mach.saveSettings()
641 ctx['global'].closeMachineSession(session)
642
643
644def cmdAnyVm(ctx,mach,cmd, args=[],save=False):
645 session = ctx['global'].openMachineSession(mach.id)
646 mach = session.machine
647 try:
648 cmd(ctx, mach, session.console, args)
649 except Exception, e:
650 save = False;
651 printErr(ctx,e)
652 if g_verbose:
653 traceback.print_exc()
654 if save:
655 mach.saveSettings()
656 ctx['global'].closeMachineSession(session)
657
658def machById(ctx,id):
659 mach = None
660 for m in getMachines(ctx):
661 if m.name == id:
662 mach = m
663 break
664 mid = str(m.id)
665 if mid[0] == '{':
666 mid = mid[1:-1]
667 if mid == id:
668 mach = m
669 break
670 return mach
671
672class XPathNode:
673 def __init__(self, parent, obj, type):
674 self.parent = parent
675 self.obj = obj
676 self.type = type
677 def lookup(self, subpath):
678 children = self.enum()
679 matches = []
680 for e in children:
681 if e.matches(subpath):
682 matches.append(e)
683 return matches
684 def enum(self):
685 return []
686 def matches(self,subexp):
687 if subexp == self.type:
688 return True
689 if not subexp.startswith(self.type):
690 return False
691 m = re.search(r"@(?P<a>\w+)=(?P<v>\w+)", subexp)
692 matches = False
693 try:
694 if m is not None:
695 dict = m.groupdict()
696 attr = dict['a']
697 val = dict['v']
698 matches = (str(getattr(self.obj, attr)) == val)
699 except:
700 pass
701 return matches
702 def apply(self, cmd):
703 exec(cmd, {'obj':self.obj,'node':self,'ctx':self.getCtx()}, {})
704 def getCtx(self):
705 if hasattr(self,'ctx'):
706 return self.ctx
707 return self.parent.getCtx()
708
709class XPathNodeHolder(XPathNode):
710 def __init__(self, parent, obj, attr, heldClass, xpathname):
711 XPathNode.__init__(self, parent, obj, 'hld '+xpathname)
712 self.attr = attr
713 self.heldClass = heldClass
714 self.xpathname = xpathname
715 def enum(self):
716 children = []
717 for n in self.getCtx()['global'].getArray(self.obj, self.attr):
718 node = self.heldClass(self, n)
719 children.append(node)
720 return children
721 def matches(self,subexp):
722 return subexp == self.xpathname
723
724class XPathNodeValue(XPathNode):
725 def __init__(self, parent, obj, xpathname):
726 XPathNode.__init__(self, parent, obj, 'val '+xpathname)
727 self.xpathname = xpathname
728 def matches(self,subexp):
729 return subexp == self.xpathname
730
731class XPathNodeHolderVM(XPathNodeHolder):
732 def __init__(self, parent, vbox):
733 XPathNodeHolder.__init__(self, parent, vbox, 'machines', XPathNodeVM, 'vms')
734
735class XPathNodeVM(XPathNode):
736 def __init__(self, parent, obj):
737 XPathNode.__init__(self, parent, obj, 'vm')
738 #def matches(self,subexp):
739 # return subexp=='vm'
740 def enum(self):
741 return [XPathNodeHolderNIC(self, self.obj),
742 XPathNodeValue(self, self.obj.BIOSSettings, 'bios'),
743 XPathNodeValue(self, self.obj.USBController, 'usb')]
744
745class XPathNodeHolderNIC(XPathNodeHolder):
746 def __init__(self, parent, mach):
747 XPathNodeHolder.__init__(self, parent, mach, 'nics', XPathNodeVM, 'nics')
748 self.maxNic = self.getCtx()['vb'].systemProperties.networkAdapterCount
749 def enum(self):
750 children = []
751 for i in range(0, self.maxNic):
752 node = XPathNodeNIC(self, self.obj.getNetworkAdapter(i))
753 children.append(node)
754 return children
755
756class XPathNodeNIC(XPathNode):
757 def __init__(self, parent, obj):
758 XPathNode.__init__(self, parent, obj, 'nic')
759 def matches(self,subexp):
760 return subexp=='nic'
761
762class XPathNodeRoot(XPathNode):
763 def __init__(self, ctx):
764 XPathNode.__init__(self, None, None, 'root')
765 self.ctx = ctx
766 def enum(self):
767 return [XPathNodeHolderVM(self, self.ctx['vb'])]
768 def matches(self,subexp):
769 return True
770
771def eval_xpath(ctx,scope):
772 pathnames = scope.split("/")[2:]
773 nodes = [XPathNodeRoot(ctx)]
774 for p in pathnames:
775 seen = []
776 while len(nodes) > 0:
777 n = nodes.pop()
778 seen.append(n)
779 for s in seen:
780 matches = s.lookup(p)
781 for m in matches:
782 nodes.append(m)
783 if len(nodes) == 0:
784 break
785 return nodes
786
787def argsToMach(ctx,args):
788 if len(args) < 2:
789 print "usage: %s [vmname|uuid]" %(args[0])
790 return None
791 id = args[1]
792 m = machById(ctx, id)
793 if m == None:
794 print "Machine '%s' is unknown, use list command to find available machines" %(id)
795 return m
796
797def helpSingleCmd(cmd,h,sp):
798 if sp != 0:
799 spec = " [ext from "+sp+"]"
800 else:
801 spec = ""
802 print " %s: %s%s" %(colored(cmd,'blue'),h,spec)
803
804def helpCmd(ctx, args):
805 if len(args) == 1:
806 print "Help page:"
807 names = commands.keys()
808 names.sort()
809 for i in names:
810 helpSingleCmd(i, commands[i][0], commands[i][2])
811 else:
812 cmd = args[1]
813 c = commands.get(cmd)
814 if c == None:
815 print "Command '%s' not known" %(cmd)
816 else:
817 helpSingleCmd(cmd, c[0], c[2])
818 return 0
819
820def asEnumElem(ctx,enum,elem):
821 all = ctx['const'].all_values(enum)
822 for e in all.keys():
823 if str(elem) == str(all[e]):
824 return colored(e, 'green')
825 return colored("<unknown>", 'green')
826
827def enumFromString(ctx,enum,str):
828 all = ctx['const'].all_values(enum)
829 return all.get(str, None)
830
831def listCmd(ctx, args):
832 for m in getMachines(ctx, True):
833 if m.teleporterEnabled:
834 tele = "[T] "
835 else:
836 tele = " "
837 print "%sMachine '%s' [%s], machineState=%s, sessionState=%s" %(tele,colVm(ctx,m.name),m.id,asEnumElem(ctx, "MachineState", m.state), asEnumElem(ctx,"SessionState", m.sessionState))
838 return 0
839
840def infoCmd(ctx,args):
841 if (len(args) < 2):
842 print "usage: info [vmname|uuid]"
843 return 0
844 mach = argsToMach(ctx,args)
845 if mach == None:
846 return 0
847 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
848 print " One can use setvar <mach> <var> <value> to change variable, using name in []."
849 print " Name [name]: %s" %(colVm(ctx,mach.name))
850 print " Description [description]: %s" %(mach.description)
851 print " ID [n/a]: %s" %(mach.id)
852 print " OS Type [via OSTypeId]: %s" %(os.description)
853 print " Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
854 print
855 print " CPUs [CPUCount]: %d" %(mach.CPUCount)
856 print " RAM [memorySize]: %dM" %(mach.memorySize)
857 print " VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
858 print " Monitors [monitorCount]: %d" %(mach.monitorCount)
859 print
860 print " Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
861 print " Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
862 print
863 if mach.teleporterEnabled:
864 print " Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
865 print
866 bios = mach.BIOSSettings
867 print " ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
868 print " APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
869 hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
870 print " Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
871 hwVirtVPID = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID)
872 print " VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
873 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging)
874 print " Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
875
876 print " Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
877 print " Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
878
879 print " Use universal time [RTCUseUTC]: %s" %(asState(mach.RTCUseUTC))
880 print " HPET [hpetEnabled]: %s" %(asState(mach.hpetEnabled))
881 if mach.audioAdapter.enabled:
882 print " Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType", mach.audioAdapter.audioDriver))
883 if mach.USBController.enabled:
884 print " USB [via USBController]: high speed %s" %(asState(mach.USBController.enabledEhci))
885 print " CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
886
887 print " Keyboard [keyboardHidType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHidType", mach.keyboardHidType), mach.keyboardHidType)
888 print " Pointing device [pointingHidType]: %s (%s)" %(asEnumElem(ctx,"PointingHidType", mach.pointingHidType), mach.pointingHidType)
889 print " Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
890 print " VRDP server [VRDPServer.enabled]: %s" %(asState(mach.VRDPServer.enabled))
891
892 print
893 print colCat(ctx," I/O subsystem info:")
894 print " Cache enabled [ioCacheEnabled]: %s" %(asState(mach.ioCacheEnabled))
895 print " Cache size [ioCacheSize]: %dM" %(mach.ioCacheSize)
896 print " Bandwidth limit [ioBandwidthMax]: %dM/s" %(mach.ioBandwidthMax)
897
898 controllers = ctx['global'].getArray(mach, 'storageControllers')
899 if controllers:
900 print
901 print colCat(ctx," Controllers:")
902 for controller in controllers:
903 print " '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
904
905 attaches = ctx['global'].getArray(mach, 'mediumAttachments')
906 if attaches:
907 print
908 print colCat(ctx," Media:")
909 for a in attaches:
910 print " Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
911 m = a.medium
912 if a.type == ctx['global'].constants.DeviceType_HardDisk:
913 print " HDD:"
914 print " Id: %s" %(m.id)
915 print " Location: %s" %(colPath(ctx,m.location))
916 print " Name: %s" %(m.name)
917 print " Format: %s" %(m.format)
918
919 if a.type == ctx['global'].constants.DeviceType_DVD:
920 print " DVD:"
921 if m:
922 print " Id: %s" %(m.id)
923 print " Name: %s" %(m.name)
924 if m.hostDrive:
925 print " Host DVD %s" %(colPath(ctx,m.location))
926 if a.passthrough:
927 print " [passthrough mode]"
928 else:
929 print " Virtual image at %s" %(colPath(ctx,m.location))
930 print " Size: %s" %(m.size)
931
932 if a.type == ctx['global'].constants.DeviceType_Floppy:
933 print " Floppy:"
934 if m:
935 print " Id: %s" %(m.id)
936 print " Name: %s" %(m.name)
937 if m.hostDrive:
938 print " Host floppy %s" %(colPath(ctx,m.location))
939 else:
940 print " Virtual image at %s" %(colPath(ctx,m.location))
941 print " Size: %s" %(m.size)
942
943 print
944 print colCat(ctx," Shared folders:")
945 for sf in ctx['global'].getArray(mach, 'sharedFolders'):
946 printSf(ctx,sf)
947
948 return 0
949
950def startCmd(ctx, args):
951 mach = argsToMach(ctx,args)
952 if mach == None:
953 return 0
954 if len(args) > 2:
955 type = args[2]
956 else:
957 type = "gui"
958 startVm(ctx, mach, type)
959 return 0
960
961def createVmCmd(ctx, args):
962 if (len(args) < 3 or len(args) > 4):
963 print "usage: createvm name ostype <basefolder>"
964 return 0
965 name = args[1]
966 oskind = args[2]
967 if len(args) == 4:
968 base = args[3]
969 else:
970 base = ''
971 try:
972 ctx['vb'].getGuestOSType(oskind)
973 except Exception, e:
974 print 'Unknown OS type:',oskind
975 return 0
976 createVm(ctx, name, oskind, base)
977 return 0
978
979def ginfoCmd(ctx,args):
980 if (len(args) < 2):
981 print "usage: ginfo [vmname|uuid]"
982 return 0
983 mach = argsToMach(ctx,args)
984 if mach == None:
985 return 0
986 cmdExistingVm(ctx, mach, 'ginfo', '')
987 return 0
988
989def execInGuest(ctx,console,args,env,user,passwd,tmo):
990 if len(args) < 1:
991 print "exec in guest needs at least program name"
992 return
993 guest = console.guest
994 # shall contain program name as argv[0]
995 gargs = args
996 print "executing %s with args %s as %s" %(args[0], gargs, user)
997 (progress, pid) = guest.executeProcess(args[0], 0, gargs, env, user, passwd, tmo)
998 print "executed with pid %d" %(pid)
999 if pid != 0:
1000 try:
1001 while True:
1002 data = guest.getProcessOutput(pid, 0, 1000, 4096)
1003 if data and len(data) > 0:
1004 sys.stdout.write(data)
1005 continue
1006 progress.waitForCompletion(100)
1007 ctx['global'].waitForEvents(0)
1008 data = guest.getProcessOutput(pid, 0, 0, 4096)
1009 if data and len(data) > 0:
1010 sys.stdout.write(data)
1011 continue
1012 if progress.completed:
1013 break
1014
1015 except KeyboardInterrupt:
1016 print "Interrupted."
1017 if progress.cancelable:
1018 progress.cancel()
1019 (reason, code, flags) = guest.getProcessStatus(pid)
1020 print "Exit code: %d" %(code)
1021 return 0
1022 else:
1023 reportError(ctx, progress)
1024
1025def nh_raw_input(prompt=""):
1026 stream = sys.stdout
1027 prompt = str(prompt)
1028 if prompt:
1029 stream.write(prompt)
1030 line = sys.stdin.readline()
1031 if not line:
1032 raise EOFError
1033 if line[-1] == '\n':
1034 line = line[:-1]
1035 return line
1036
1037
1038def getCred(ctx):
1039 import getpass
1040 user = getpass.getuser()
1041 user_inp = nh_raw_input("User (%s): " %(user))
1042 if len (user_inp) > 0:
1043 user = user_inp
1044 passwd = getpass.getpass()
1045
1046 return (user,passwd)
1047
1048def gexecCmd(ctx,args):
1049 if (len(args) < 2):
1050 print "usage: gexec [vmname|uuid] command args"
1051 return 0
1052 mach = argsToMach(ctx,args)
1053 if mach == None:
1054 return 0
1055 gargs = args[2:]
1056 env = [] # ["DISPLAY=:0"]
1057 (user,passwd) = getCred(ctx)
1058 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env,user,passwd,10000))
1059 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1060 return 0
1061
1062def gcatCmd(ctx,args):
1063 if (len(args) < 2):
1064 print "usage: gcat [vmname|uuid] local_file | guestProgram, such as gcat linux /home/nike/.bashrc | sh -c 'cat >'"
1065 return 0
1066 mach = argsToMach(ctx,args)
1067 if mach == None:
1068 return 0
1069 gargs = args[2:]
1070 env = []
1071 (user,passwd) = getCred(ctx)
1072 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env, user, passwd, 0))
1073 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1074 return 0
1075
1076
1077def removeVmCmd(ctx, args):
1078 mach = argsToMach(ctx,args)
1079 if mach == None:
1080 return 0
1081 removeVm(ctx, mach)
1082 return 0
1083
1084def pauseCmd(ctx, args):
1085 mach = argsToMach(ctx,args)
1086 if mach == None:
1087 return 0
1088 cmdExistingVm(ctx, mach, 'pause', '')
1089 return 0
1090
1091def powerdownCmd(ctx, args):
1092 mach = argsToMach(ctx,args)
1093 if mach == None:
1094 return 0
1095 cmdExistingVm(ctx, mach, 'powerdown', '')
1096 return 0
1097
1098def powerbuttonCmd(ctx, args):
1099 mach = argsToMach(ctx,args)
1100 if mach == None:
1101 return 0
1102 cmdExistingVm(ctx, mach, 'powerbutton', '')
1103 return 0
1104
1105def resumeCmd(ctx, args):
1106 mach = argsToMach(ctx,args)
1107 if mach == None:
1108 return 0
1109 cmdExistingVm(ctx, mach, 'resume', '')
1110 return 0
1111
1112def saveCmd(ctx, args):
1113 mach = argsToMach(ctx,args)
1114 if mach == None:
1115 return 0
1116 cmdExistingVm(ctx, mach, 'save', '')
1117 return 0
1118
1119def statsCmd(ctx, args):
1120 mach = argsToMach(ctx,args)
1121 if mach == None:
1122 return 0
1123 cmdExistingVm(ctx, mach, 'stats', '')
1124 return 0
1125
1126def guestCmd(ctx, args):
1127 if (len(args) < 3):
1128 print "usage: guest name commands"
1129 return 0
1130 mach = argsToMach(ctx,args)
1131 if mach == None:
1132 return 0
1133 if str(mach.sessionState) != str(ctx['const'].SessionState_Open):
1134 cmdClosedVm(ctx, mach, lambda ctx, mach, a: guestExec (ctx, mach, None, ' '.join(args[2:])))
1135 else:
1136 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
1137 return 0
1138
1139def screenshotCmd(ctx, args):
1140 if (len(args) < 2):
1141 print "usage: screenshot vm <file> <width> <height> <monitor>"
1142 return 0
1143 mach = argsToMach(ctx,args)
1144 if mach == None:
1145 return 0
1146 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
1147 return 0
1148
1149def teleportCmd(ctx, args):
1150 if (len(args) < 3):
1151 print "usage: teleport name host:port <password>"
1152 return 0
1153 mach = argsToMach(ctx,args)
1154 if mach == None:
1155 return 0
1156 cmdExistingVm(ctx, mach, 'teleport', args[2:])
1157 return 0
1158
1159def portalsettings(ctx,mach,args):
1160 enabled = args[0]
1161 mach.teleporterEnabled = enabled
1162 if enabled:
1163 port = args[1]
1164 passwd = args[2]
1165 mach.teleporterPort = port
1166 mach.teleporterPassword = passwd
1167
1168def openportalCmd(ctx, args):
1169 if (len(args) < 3):
1170 print "usage: openportal name port <password>"
1171 return 0
1172 mach = argsToMach(ctx,args)
1173 if mach == None:
1174 return 0
1175 port = int(args[2])
1176 if (len(args) > 3):
1177 passwd = args[3]
1178 else:
1179 passwd = ""
1180 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
1181 cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
1182 startVm(ctx, mach, "gui")
1183 return 0
1184
1185def closeportalCmd(ctx, args):
1186 if (len(args) < 2):
1187 print "usage: closeportal name"
1188 return 0
1189 mach = argsToMach(ctx,args)
1190 if mach == None:
1191 return 0
1192 if mach.teleporterEnabled:
1193 cmdClosedVm(ctx, mach, portalsettings, [False])
1194 return 0
1195
1196def gueststatsCmd(ctx, args):
1197 if (len(args) < 2):
1198 print "usage: gueststats name <check interval>"
1199 return 0
1200 mach = argsToMach(ctx,args)
1201 if mach == None:
1202 return 0
1203 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
1204 return 0
1205
1206def plugcpu(ctx,mach,args):
1207 plug = args[0]
1208 cpu = args[1]
1209 if plug:
1210 print "Adding CPU %d..." %(cpu)
1211 mach.hotPlugCPU(cpu)
1212 else:
1213 print "Removing CPU %d..." %(cpu)
1214 mach.hotUnplugCPU(cpu)
1215
1216def plugcpuCmd(ctx, args):
1217 if (len(args) < 2):
1218 print "usage: plugcpu name cpuid"
1219 return 0
1220 mach = argsToMach(ctx,args)
1221 if mach == None:
1222 return 0
1223 if str(mach.sessionState) != str(ctx['const'].SessionState_Open):
1224 if mach.CPUHotPlugEnabled:
1225 cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
1226 else:
1227 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
1228 return 0
1229
1230def unplugcpuCmd(ctx, args):
1231 if (len(args) < 2):
1232 print "usage: unplugcpu name cpuid"
1233 return 0
1234 mach = argsToMach(ctx,args)
1235 if mach == None:
1236 return 0
1237 if str(mach.sessionState) != str(ctx['const'].SessionState_Open):
1238 if mach.CPUHotPlugEnabled:
1239 cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
1240 else:
1241 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
1242 return 0
1243
1244def setvar(ctx,mach,args):
1245 expr = 'mach.'+args[0]+' = '+args[1]
1246 print "Executing",expr
1247 exec expr
1248
1249def setvarCmd(ctx, args):
1250 if (len(args) < 4):
1251 print "usage: setvar [vmname|uuid] expr value"
1252 return 0
1253 mach = argsToMach(ctx,args)
1254 if mach == None:
1255 return 0
1256 cmdClosedVm(ctx, mach, setvar, args[2:])
1257 return 0
1258
1259def setvmextra(ctx,mach,args):
1260 key = args[0]
1261 value = args[1]
1262 print "%s: setting %s to %s" %(mach.name, key, value)
1263 mach.setExtraData(key, value)
1264
1265def setExtraDataCmd(ctx, args):
1266 if (len(args) < 3):
1267 print "usage: setextra [vmname|uuid|global] key <value>"
1268 return 0
1269 key = args[2]
1270 if len(args) == 4:
1271 value = args[3]
1272 else:
1273 value = None
1274 if args[1] == 'global':
1275 ctx['vb'].setExtraData(key, value)
1276 return 0
1277
1278 mach = argsToMach(ctx,args)
1279 if mach == None:
1280 return 0
1281 cmdClosedVm(ctx, mach, setvmextra, [key, value])
1282 return 0
1283
1284def printExtraKey(obj, key, value):
1285 print "%s: '%s' = '%s'" %(obj, key, value)
1286
1287def getExtraDataCmd(ctx, args):
1288 if (len(args) < 2):
1289 print "usage: getextra [vmname|uuid|global] <key>"
1290 return 0
1291 if len(args) == 3:
1292 key = args[2]
1293 else:
1294 key = None
1295
1296 if args[1] == 'global':
1297 obj = ctx['vb']
1298 else:
1299 obj = argsToMach(ctx,args)
1300 if obj == None:
1301 return 0
1302
1303 if key == None:
1304 keys = obj.getExtraDataKeys()
1305 else:
1306 keys = [ key ]
1307 for k in keys:
1308 printExtraKey(args[1], k, obj.getExtraData(k))
1309
1310 return 0
1311
1312def quitCmd(ctx, args):
1313 return 1
1314
1315def aliasCmd(ctx, args):
1316 if (len(args) == 3):
1317 aliases[args[1]] = args[2]
1318 return 0
1319
1320 for (k,v) in aliases.items():
1321 print "'%s' is an alias for '%s'" %(k,v)
1322 return 0
1323
1324def verboseCmd(ctx, args):
1325 global g_verbose
1326 if (len(args) > 1):
1327 g_verbose = (args[1]=='on')
1328 else:
1329 g_verbose = not g_verbose
1330 return 0
1331
1332def colorsCmd(ctx, args):
1333 global g_hascolors
1334 if (len(args) > 1):
1335 g_hascolors = (args[1]=='on')
1336 else:
1337 g_hascolors = not g_hascolors
1338 return 0
1339
1340def hostCmd(ctx, args):
1341 vb = ctx['vb']
1342 print "VirtualBox version %s" %(colored(vb.version, 'blue'))
1343 props = vb.systemProperties
1344 print "Machines: %s" %(colPath(ctx,props.defaultMachineFolder))
1345 print "HDDs: %s" %(colPath(ctx,props.defaultHardDiskFolder))
1346
1347 #print "Global shared folders:"
1348 #for ud in ctx['global'].getArray(vb, 'sharedFolders'):
1349 # printSf(ctx,sf)
1350 host = vb.host
1351 cnt = host.processorCount
1352 print colCat(ctx,"Processors:")
1353 print " available/online: %d/%d " %(cnt,host.processorOnlineCount)
1354 for i in range(0,cnt):
1355 print " processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
1356
1357 print colCat(ctx, "RAM:")
1358 print " %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
1359 print colCat(ctx,"OS:");
1360 print " %s (%s)" %(host.operatingSystem, host.OSVersion)
1361 if host.Acceleration3DAvailable:
1362 print colCat(ctx,"3D acceleration available")
1363 else:
1364 print colCat(ctx,"3D acceleration NOT available")
1365
1366 print colCat(ctx,"Network interfaces:")
1367 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
1368 print " %s (%s)" %(ni.name, ni.IPAddress)
1369
1370 print colCat(ctx,"DVD drives:")
1371 for dd in ctx['global'].getArray(host, 'DVDDrives'):
1372 print " %s - %s" %(dd.name, dd.description)
1373
1374 print colCat(ctx,"Floppy drives:")
1375 for dd in ctx['global'].getArray(host, 'floppyDrives'):
1376 print " %s - %s" %(dd.name, dd.description)
1377
1378 print colCat(ctx,"USB devices:")
1379 for ud in ctx['global'].getArray(host, 'USBDevices'):
1380 printHostUsbDev(ctx,ud)
1381
1382 if ctx['perf']:
1383 for metric in ctx['perf'].query(["*"], [host]):
1384 print metric['name'], metric['values_as_string']
1385
1386 return 0
1387
1388def monitorGuestCmd(ctx, args):
1389 if (len(args) < 2):
1390 print "usage: monitorGuest name (duration)"
1391 return 0
1392 mach = argsToMach(ctx,args)
1393 if mach == None:
1394 return 0
1395 dur = 5
1396 if len(args) > 2:
1397 dur = float(args[2])
1398 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1399 return 0
1400
1401def monitorVBoxCmd(ctx, args):
1402 if (len(args) > 2):
1403 print "usage: monitorVBox (duration)"
1404 return 0
1405 dur = 5
1406 if len(args) > 1:
1407 dur = float(args[1])
1408 monitorVBox(ctx, dur)
1409 return 0
1410
1411def monitorVBox2Cmd(ctx, args):
1412 if (len(args) > 2):
1413 print "usage: monitorVBox2 (duration)"
1414 return 0
1415 dur = 5
1416 if len(args) > 1:
1417 dur = float(args[1])
1418 monitorVBox2(ctx, dur)
1419 return 0
1420
1421def getAdapterType(ctx, type):
1422 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1423 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1424 return "pcnet"
1425 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1426 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1427 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1428 return "e1000"
1429 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1430 return "virtio"
1431 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1432 return None
1433 else:
1434 raise Exception("Unknown adapter type: "+type)
1435
1436
1437def portForwardCmd(ctx, args):
1438 if (len(args) != 5):
1439 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1440 return 0
1441 mach = argsToMach(ctx,args)
1442 if mach == None:
1443 return 0
1444 adapterNum = int(args[2])
1445 hostPort = int(args[3])
1446 guestPort = int(args[4])
1447 proto = "TCP"
1448 session = ctx['global'].openMachineSession(mach.id)
1449 mach = session.machine
1450
1451 adapter = mach.getNetworkAdapter(adapterNum)
1452 adapterType = getAdapterType(ctx, adapter.adapterType)
1453
1454 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1455 config = "VBoxInternal/Devices/" + adapterType + "/"
1456 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1457
1458 mach.setExtraData(config + "/Protocol", proto)
1459 mach.setExtraData(config + "/HostPort", str(hostPort))
1460 mach.setExtraData(config + "/GuestPort", str(guestPort))
1461
1462 mach.saveSettings()
1463 session.close()
1464
1465 return 0
1466
1467
1468def showLogCmd(ctx, args):
1469 if (len(args) < 2):
1470 print "usage: showLog vm <num>"
1471 return 0
1472 mach = argsToMach(ctx,args)
1473 if mach == None:
1474 return 0
1475
1476 log = 0
1477 if (len(args) > 2):
1478 log = args[2]
1479
1480 uOffset = 0
1481 while True:
1482 data = mach.readLog(log, uOffset, 4096)
1483 if (len(data) == 0):
1484 break
1485 # print adds either NL or space to chunks not ending with a NL
1486 sys.stdout.write(str(data))
1487 uOffset += len(data)
1488
1489 return 0
1490
1491def findLogCmd(ctx, args):
1492 if (len(args) < 3):
1493 print "usage: findLog vm pattern <num>"
1494 return 0
1495 mach = argsToMach(ctx,args)
1496 if mach == None:
1497 return 0
1498
1499 log = 0
1500 if (len(args) > 3):
1501 log = args[3]
1502
1503 pattern = args[2]
1504 uOffset = 0
1505 while True:
1506 # to reduce line splits on buffer boundary
1507 data = mach.readLog(log, uOffset, 512*1024)
1508 if (len(data) == 0):
1509 break
1510 d = str(data).split("\n")
1511 for s in d:
1512 m = re.findall(pattern, s)
1513 if len(m) > 0:
1514 for mt in m:
1515 s = s.replace(mt, colored(mt,'red'))
1516 print s
1517 uOffset += len(data)
1518
1519 return 0
1520
1521def evalCmd(ctx, args):
1522 expr = ' '.join(args[1:])
1523 try:
1524 exec expr
1525 except Exception, e:
1526 printErr(ctx,e)
1527 if g_verbose:
1528 traceback.print_exc()
1529 return 0
1530
1531def reloadExtCmd(ctx, args):
1532 # maybe will want more args smartness
1533 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1534 autoCompletion(commands, ctx)
1535 return 0
1536
1537
1538def runScriptCmd(ctx, args):
1539 if (len(args) != 2):
1540 print "usage: runScript <script>"
1541 return 0
1542 try:
1543 lf = open(args[1], 'r')
1544 except IOError,e:
1545 print "cannot open:",args[1], ":",e
1546 return 0
1547
1548 try:
1549 for line in lf:
1550 done = runCommand(ctx, line)
1551 if done != 0: break
1552 except Exception,e:
1553 printErr(ctx,e)
1554 if g_verbose:
1555 traceback.print_exc()
1556 lf.close()
1557 return 0
1558
1559def sleepCmd(ctx, args):
1560 if (len(args) != 2):
1561 print "usage: sleep <secs>"
1562 return 0
1563
1564 try:
1565 time.sleep(float(args[1]))
1566 except:
1567 # to allow sleep interrupt
1568 pass
1569 return 0
1570
1571
1572def shellCmd(ctx, args):
1573 if (len(args) < 2):
1574 print "usage: shell <commands>"
1575 return 0
1576 cmd = ' '.join(args[1:])
1577
1578 try:
1579 os.system(cmd)
1580 except KeyboardInterrupt:
1581 # to allow shell command interruption
1582 pass
1583 return 0
1584
1585
1586def connectCmd(ctx, args):
1587 if (len(args) > 4):
1588 print "usage: connect url <username> <passwd>"
1589 return 0
1590
1591 if ctx['vb'] is not None:
1592 print "Already connected, disconnect first..."
1593 return 0
1594
1595 if (len(args) > 1):
1596 url = args[1]
1597 else:
1598 url = None
1599
1600 if (len(args) > 2):
1601 user = args[2]
1602 else:
1603 user = ""
1604
1605 if (len(args) > 3):
1606 passwd = args[3]
1607 else:
1608 passwd = ""
1609
1610 ctx['wsinfo'] = [url, user, passwd]
1611 vbox = ctx['global'].platform.connect(url, user, passwd)
1612 ctx['vb'] = vbox
1613 print "Running VirtualBox version %s" %(vbox.version)
1614 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1615 return 0
1616
1617def disconnectCmd(ctx, args):
1618 if (len(args) != 1):
1619 print "usage: disconnect"
1620 return 0
1621
1622 if ctx['vb'] is None:
1623 print "Not connected yet."
1624 return 0
1625
1626 try:
1627 ctx['global'].platform.disconnect()
1628 except:
1629 ctx['vb'] = None
1630 raise
1631
1632 ctx['vb'] = None
1633 return 0
1634
1635def reconnectCmd(ctx, args):
1636 if ctx['wsinfo'] is None:
1637 print "Never connected..."
1638 return 0
1639
1640 try:
1641 ctx['global'].platform.disconnect()
1642 except:
1643 pass
1644
1645 [url,user,passwd] = ctx['wsinfo']
1646 ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
1647 print "Running VirtualBox version %s" %(ctx['vb'].version)
1648 return 0
1649
1650def exportVMCmd(ctx, args):
1651 import sys
1652
1653 if len(args) < 3:
1654 print "usage: exportVm <machine> <path> <format> <license>"
1655 return 0
1656 mach = argsToMach(ctx,args)
1657 if mach is None:
1658 return 0
1659 path = args[2]
1660 if (len(args) > 3):
1661 format = args[3]
1662 else:
1663 format = "ovf-1.0"
1664 if (len(args) > 4):
1665 license = args[4]
1666 else:
1667 license = "GPL"
1668
1669 app = ctx['vb'].createAppliance()
1670 desc = mach.export(app)
1671 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1672 p = app.write(format, path)
1673 if (progressBar(ctx, p) and int(p.resultCode) == 0):
1674 print "Exported to %s in format %s" %(path, format)
1675 else:
1676 reportError(ctx,p)
1677 return 0
1678
1679# PC XT scancodes
1680scancodes = {
1681 'a': 0x1e,
1682 'b': 0x30,
1683 'c': 0x2e,
1684 'd': 0x20,
1685 'e': 0x12,
1686 'f': 0x21,
1687 'g': 0x22,
1688 'h': 0x23,
1689 'i': 0x17,
1690 'j': 0x24,
1691 'k': 0x25,
1692 'l': 0x26,
1693 'm': 0x32,
1694 'n': 0x31,
1695 'o': 0x18,
1696 'p': 0x19,
1697 'q': 0x10,
1698 'r': 0x13,
1699 's': 0x1f,
1700 't': 0x14,
1701 'u': 0x16,
1702 'v': 0x2f,
1703 'w': 0x11,
1704 'x': 0x2d,
1705 'y': 0x15,
1706 'z': 0x2c,
1707 '0': 0x0b,
1708 '1': 0x02,
1709 '2': 0x03,
1710 '3': 0x04,
1711 '4': 0x05,
1712 '5': 0x06,
1713 '6': 0x07,
1714 '7': 0x08,
1715 '8': 0x09,
1716 '9': 0x0a,
1717 ' ': 0x39,
1718 '-': 0xc,
1719 '=': 0xd,
1720 '[': 0x1a,
1721 ']': 0x1b,
1722 ';': 0x27,
1723 '\'': 0x28,
1724 ',': 0x33,
1725 '.': 0x34,
1726 '/': 0x35,
1727 '\t': 0xf,
1728 '\n': 0x1c,
1729 '`': 0x29
1730};
1731
1732extScancodes = {
1733 'ESC' : [0x01],
1734 'BKSP': [0xe],
1735 'SPACE': [0x39],
1736 'TAB': [0x0f],
1737 'CAPS': [0x3a],
1738 'ENTER': [0x1c],
1739 'LSHIFT': [0x2a],
1740 'RSHIFT': [0x36],
1741 'INS': [0xe0, 0x52],
1742 'DEL': [0xe0, 0x53],
1743 'END': [0xe0, 0x4f],
1744 'HOME': [0xe0, 0x47],
1745 'PGUP': [0xe0, 0x49],
1746 'PGDOWN': [0xe0, 0x51],
1747 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
1748 'RGUI': [0xe0, 0x5c],
1749 'LCTR': [0x1d],
1750 'RCTR': [0xe0, 0x1d],
1751 'LALT': [0x38],
1752 'RALT': [0xe0, 0x38],
1753 'APPS': [0xe0, 0x5d],
1754 'F1': [0x3b],
1755 'F2': [0x3c],
1756 'F3': [0x3d],
1757 'F4': [0x3e],
1758 'F5': [0x3f],
1759 'F6': [0x40],
1760 'F7': [0x41],
1761 'F8': [0x42],
1762 'F9': [0x43],
1763 'F10': [0x44 ],
1764 'F11': [0x57],
1765 'F12': [0x58],
1766 'UP': [0xe0, 0x48],
1767 'LEFT': [0xe0, 0x4b],
1768 'DOWN': [0xe0, 0x50],
1769 'RIGHT': [0xe0, 0x4d],
1770};
1771
1772def keyDown(ch):
1773 code = scancodes.get(ch, 0x0)
1774 if code != 0:
1775 return [code]
1776 extCode = extScancodes.get(ch, [])
1777 if len(extCode) == 0:
1778 print "bad ext",ch
1779 return extCode
1780
1781def keyUp(ch):
1782 codes = keyDown(ch)[:] # make a copy
1783 if len(codes) > 0:
1784 codes[len(codes)-1] += 0x80
1785 return codes
1786
1787def typeInGuest(console, text, delay):
1788 import time
1789 pressed = []
1790 group = False
1791 modGroupEnd = True
1792 i = 0
1793 while i < len(text):
1794 ch = text[i]
1795 i = i+1
1796 if ch == '{':
1797 # start group, all keys to be pressed at the same time
1798 group = True
1799 continue
1800 if ch == '}':
1801 # end group, release all keys
1802 for c in pressed:
1803 console.keyboard.putScancodes(keyUp(c))
1804 pressed = []
1805 group = False
1806 continue
1807 if ch == 'W':
1808 # just wait a bit
1809 time.sleep(0.3)
1810 continue
1811 if ch == '^' or ch == '|' or ch == '$' or ch == '_':
1812 if ch == '^':
1813 ch = 'LCTR'
1814 if ch == '|':
1815 ch = 'LSHIFT'
1816 if ch == '_':
1817 ch = 'LALT'
1818 if ch == '$':
1819 ch = 'LGUI'
1820 if not group:
1821 modGroupEnd = False
1822 else:
1823 if ch == '\\':
1824 if i < len(text):
1825 ch = text[i]
1826 i = i+1
1827 if ch == 'n':
1828 ch = '\n'
1829 elif ch == '&':
1830 combo = ""
1831 while i < len(text):
1832 ch = text[i]
1833 i = i+1
1834 if ch == ';':
1835 break
1836 combo += ch
1837 ch = combo
1838 modGroupEnd = True
1839 console.keyboard.putScancodes(keyDown(ch))
1840 pressed.insert(0, ch)
1841 if not group and modGroupEnd:
1842 for c in pressed:
1843 console.keyboard.putScancodes(keyUp(c))
1844 pressed = []
1845 modGroupEnd = True
1846 time.sleep(delay)
1847
1848def typeGuestCmd(ctx, args):
1849 import sys
1850
1851 if len(args) < 3:
1852 print "usage: typeGuest <machine> <text> <charDelay>"
1853 return 0
1854 mach = argsToMach(ctx,args)
1855 if mach is None:
1856 return 0
1857
1858 text = args[2]
1859
1860 if len(args) > 3:
1861 delay = float(args[3])
1862 else:
1863 delay = 0.1
1864
1865 gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
1866 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1867
1868 return 0
1869
1870def optId(verbose,id):
1871 if verbose:
1872 return ": "+id
1873 else:
1874 return ""
1875
1876def asSize(val,inBytes):
1877 if inBytes:
1878 return int(val)/(1024*1024)
1879 else:
1880 return int(val)
1881
1882def listMediaCmd(ctx,args):
1883 if len(args) > 1:
1884 verbose = int(args[1])
1885 else:
1886 verbose = False
1887 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
1888 print colCat(ctx,"Hard disks:")
1889 for hdd in hdds:
1890 if hdd.state != ctx['global'].constants.MediumState_Created:
1891 hdd.refreshState()
1892 print " %s (%s)%s %s [logical %s]" %(colPath(ctx,hdd.location), hdd.format, optId(verbose,hdd.id),colSizeM(ctx,asSize(hdd.size, True)), colSizeM(ctx,asSize(hdd.logicalSize, False)))
1893
1894 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
1895 print colCat(ctx,"CD/DVD disks:")
1896 for dvd in dvds:
1897 if dvd.state != ctx['global'].constants.MediumState_Created:
1898 dvd.refreshState()
1899 print " %s (%s)%s %s" %(colPath(ctx,dvd.location), dvd.format,optId(verbose,dvd.id),colSizeM(ctx,asSize(dvd.size, True)))
1900
1901 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
1902 print colCat(ctx,"Floppy disks:")
1903 for floppy in floppys:
1904 if floppy.state != ctx['global'].constants.MediumState_Created:
1905 floppy.refreshState()
1906 print " %s (%s)%s %s" %(colPath(ctx,floppy.location), floppy.format,optId(verbose,floppy.id), colSizeM(ctx,asSize(floppy.size, True)))
1907
1908 return 0
1909
1910def listUsbCmd(ctx,args):
1911 if (len(args) > 1):
1912 print "usage: listUsb"
1913 return 0
1914
1915 host = ctx['vb'].host
1916 for ud in ctx['global'].getArray(host, 'USBDevices'):
1917 printHostUsbDev(ctx,ud)
1918
1919 return 0
1920
1921def findDevOfType(ctx,mach,type):
1922 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1923 for a in atts:
1924 if a.type == type:
1925 return [a.controller, a.port, a.device]
1926 return [None, 0, 0]
1927
1928def createHddCmd(ctx,args):
1929 if (len(args) < 3):
1930 print "usage: createHdd sizeM location type"
1931 return 0
1932
1933 size = int(args[1])
1934 loc = args[2]
1935 if len(args) > 3:
1936 format = args[3]
1937 else:
1938 format = "vdi"
1939
1940 hdd = ctx['vb'].createHardDisk(format, loc)
1941 progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
1942 if progressBar(ctx,progress) and hdd.id:
1943 print "created HDD at %s as %s" %(colPath(ctx,hdd.location), hdd.id)
1944 else:
1945 print "cannot create disk (file %s exist?)" %(loc)
1946 reportError(ctx,progress)
1947 return 0
1948
1949 return 0
1950
1951def registerHddCmd(ctx,args):
1952 if (len(args) < 2):
1953 print "usage: registerHdd location"
1954 return 0
1955
1956 vb = ctx['vb']
1957 loc = args[1]
1958 setImageId = False
1959 imageId = ""
1960 setParentId = False
1961 parentId = ""
1962 hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
1963 print "registered HDD as %s" %(hdd.id)
1964 return 0
1965
1966def controldevice(ctx,mach,args):
1967 [ctr,port,slot,type,id] = args
1968 mach.attachDevice(ctr, port, slot,type,id)
1969
1970def attachHddCmd(ctx,args):
1971 if (len(args) < 3):
1972 print "usage: attachHdd vm hdd controller port:slot"
1973 return 0
1974
1975 mach = argsToMach(ctx,args)
1976 if mach is None:
1977 return 0
1978 vb = ctx['vb']
1979 loc = args[2]
1980 try:
1981 hdd = vb.findHardDisk(loc)
1982 except:
1983 print "no HDD with path %s registered" %(loc)
1984 return 0
1985 if len(args) > 3:
1986 ctr = args[3]
1987 (port,slot) = args[4].split(":")
1988 else:
1989 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
1990
1991 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
1992 return 0
1993
1994def detachVmDevice(ctx,mach,args):
1995 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1996 hid = args[0]
1997 for a in atts:
1998 if a.medium:
1999 if hid == "ALL" or a.medium.id == hid:
2000 mach.detachDevice(a.controller, a.port, a.device)
2001
2002def detachMedium(ctx,mid,medium):
2003 cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
2004
2005def detachHddCmd(ctx,args):
2006 if (len(args) < 3):
2007 print "usage: detachHdd vm hdd"
2008 return 0
2009
2010 mach = argsToMach(ctx,args)
2011 if mach is None:
2012 return 0
2013 vb = ctx['vb']
2014 loc = args[2]
2015 try:
2016 hdd = vb.findHardDisk(loc)
2017 except:
2018 print "no HDD with path %s registered" %(loc)
2019 return 0
2020
2021 detachMedium(ctx,mach.id,hdd)
2022 return 0
2023
2024def unregisterHddCmd(ctx,args):
2025 if (len(args) < 2):
2026 print "usage: unregisterHdd path <vmunreg>"
2027 return 0
2028
2029 vb = ctx['vb']
2030 loc = args[1]
2031 if (len(args) > 2):
2032 vmunreg = int(args[2])
2033 else:
2034 vmunreg = 0
2035 try:
2036 hdd = vb.findHardDisk(loc)
2037 except:
2038 print "no HDD with path %s registered" %(loc)
2039 return 0
2040
2041 if vmunreg != 0:
2042 machs = ctx['global'].getArray(hdd, 'machineIds')
2043 try:
2044 for m in machs:
2045 print "Trying to detach from %s" %(m)
2046 detachMedium(ctx,m,hdd)
2047 except Exception, e:
2048 print 'failed: ',e
2049 return 0
2050 hdd.close()
2051 return 0
2052
2053def removeHddCmd(ctx,args):
2054 if (len(args) != 2):
2055 print "usage: removeHdd path"
2056 return 0
2057
2058 vb = ctx['vb']
2059 loc = args[1]
2060 try:
2061 hdd = vb.findHardDisk(loc)
2062 except:
2063 print "no HDD with path %s registered" %(loc)
2064 return 0
2065
2066 progress = hdd.deleteStorage()
2067 progressBar(ctx,progress)
2068
2069 return 0
2070
2071def registerIsoCmd(ctx,args):
2072 if (len(args) < 2):
2073 print "usage: registerIso location"
2074 return 0
2075 vb = ctx['vb']
2076 loc = args[1]
2077 id = ""
2078 iso = vb.openDVDImage(loc, id)
2079 print "registered ISO as %s" %(iso.id)
2080 return 0
2081
2082def unregisterIsoCmd(ctx,args):
2083 if (len(args) != 2):
2084 print "usage: unregisterIso path"
2085 return 0
2086
2087 vb = ctx['vb']
2088 loc = args[1]
2089 try:
2090 dvd = vb.findDVDImage(loc)
2091 except:
2092 print "no DVD with path %s registered" %(loc)
2093 return 0
2094
2095 progress = dvd.close()
2096 print "Unregistered ISO at %s" %(colPath(ctx,dvd.location))
2097
2098 return 0
2099
2100def removeIsoCmd(ctx,args):
2101 if (len(args) != 2):
2102 print "usage: removeIso path"
2103 return 0
2104
2105 vb = ctx['vb']
2106 loc = args[1]
2107 try:
2108 dvd = vb.findDVDImage(loc)
2109 except:
2110 print "no DVD with path %s registered" %(loc)
2111 return 0
2112
2113 progress = dvd.deleteStorage()
2114 if progressBar(ctx,progress):
2115 print "Removed ISO at %s" %(colPath(ctx,dvd.location))
2116 else:
2117 reportError(ctx,progress)
2118 return 0
2119
2120def attachIsoCmd(ctx,args):
2121 if (len(args) < 3):
2122 print "usage: attachIso vm iso controller port:slot"
2123 return 0
2124
2125 mach = argsToMach(ctx,args)
2126 if mach is None:
2127 return 0
2128 vb = ctx['vb']
2129 loc = args[2]
2130 try:
2131 dvd = vb.findDVDImage(loc)
2132 except:
2133 print "no DVD with path %s registered" %(loc)
2134 return 0
2135 if len(args) > 3:
2136 ctr = args[3]
2137 (port,slot) = args[4].split(":")
2138 else:
2139 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
2140 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
2141 return 0
2142
2143def detachIsoCmd(ctx,args):
2144 if (len(args) < 3):
2145 print "usage: detachIso vm iso"
2146 return 0
2147
2148 mach = argsToMach(ctx,args)
2149 if mach is None:
2150 return 0
2151 vb = ctx['vb']
2152 loc = args[2]
2153 try:
2154 dvd = vb.findDVDImage(loc)
2155 except:
2156 print "no DVD with path %s registered" %(loc)
2157 return 0
2158
2159 detachMedium(ctx,mach.id,dvd)
2160 return 0
2161
2162def mountIsoCmd(ctx,args):
2163 if (len(args) < 3):
2164 print "usage: mountIso vm iso controller port:slot"
2165 return 0
2166
2167 mach = argsToMach(ctx,args)
2168 if mach is None:
2169 return 0
2170 vb = ctx['vb']
2171 loc = args[2]
2172 try:
2173 dvd = vb.findDVDImage(loc)
2174 except:
2175 print "no DVD with path %s registered" %(loc)
2176 return 0
2177
2178 if len(args) > 3:
2179 ctr = args[3]
2180 (port,slot) = args[4].split(":")
2181 else:
2182 # autodetect controller and location, just find first controller with media == DVD
2183 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
2184
2185 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
2186
2187 return 0
2188
2189def unmountIsoCmd(ctx,args):
2190 if (len(args) < 2):
2191 print "usage: unmountIso vm controller port:slot"
2192 return 0
2193
2194 mach = argsToMach(ctx,args)
2195 if mach is None:
2196 return 0
2197 vb = ctx['vb']
2198
2199 if len(args) > 2:
2200 ctr = args[2]
2201 (port,slot) = args[3].split(":")
2202 else:
2203 # autodetect controller and location, just find first controller with media == DVD
2204 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
2205
2206 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
2207
2208 return 0
2209
2210def attachCtr(ctx,mach,args):
2211 [name, bus, type] = args
2212 ctr = mach.addStorageController(name, bus)
2213 if type != None:
2214 ctr.controllerType = type
2215
2216def attachCtrCmd(ctx,args):
2217 if (len(args) < 4):
2218 print "usage: attachCtr vm cname bus <type>"
2219 return 0
2220
2221 if len(args) > 4:
2222 type = enumFromString(ctx,'StorageControllerType', args[4])
2223 if type == None:
2224 print "Controller type %s unknown" %(args[4])
2225 return 0
2226 else:
2227 type = None
2228
2229 mach = argsToMach(ctx,args)
2230 if mach is None:
2231 return 0
2232 bus = enumFromString(ctx,'StorageBus', args[3])
2233 if bus is None:
2234 print "Bus type %s unknown" %(args[3])
2235 return 0
2236 name = args[2]
2237 cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
2238 return 0
2239
2240def detachCtrCmd(ctx,args):
2241 if (len(args) < 3):
2242 print "usage: detachCtr vm name"
2243 return 0
2244
2245 mach = argsToMach(ctx,args)
2246 if mach is None:
2247 return 0
2248 ctr = args[2]
2249 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
2250 return 0
2251
2252def usbctr(ctx,mach,console,args):
2253 if (args[0]):
2254 console.attachUSBDevice(args[1])
2255 else:
2256 console.detachUSBDevice(args[1])
2257
2258def attachUsbCmd(ctx,args):
2259 if (len(args) < 3):
2260 print "usage: attachUsb vm deviceuid"
2261 return 0
2262
2263 mach = argsToMach(ctx,args)
2264 if mach is None:
2265 return 0
2266 dev = args[2]
2267 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
2268 return 0
2269
2270def detachUsbCmd(ctx,args):
2271 if (len(args) < 3):
2272 print "usage: detachUsb vm deviceuid"
2273 return 0
2274
2275 mach = argsToMach(ctx,args)
2276 if mach is None:
2277 return 0
2278 dev = args[2]
2279 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
2280 return 0
2281
2282
2283def guiCmd(ctx,args):
2284 if (len(args) > 1):
2285 print "usage: gui"
2286 return 0
2287
2288 binDir = ctx['global'].getBinDir()
2289
2290 vbox = os.path.join(binDir, 'VirtualBox')
2291 try:
2292 os.system(vbox)
2293 except KeyboardInterrupt:
2294 # to allow interruption
2295 pass
2296 return 0
2297
2298def shareFolderCmd(ctx,args):
2299 if (len(args) < 4):
2300 print "usage: shareFolder vm path name <writable> <persistent>"
2301 return 0
2302
2303 mach = argsToMach(ctx,args)
2304 if mach is None:
2305 return 0
2306 path = args[2]
2307 name = args[3]
2308 writable = False
2309 persistent = False
2310 if len(args) > 4:
2311 for a in args[4:]:
2312 if a == 'writable':
2313 writable = True
2314 if a == 'persistent':
2315 persistent = True
2316 if persistent:
2317 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.createSharedFolder(name, path, writable), [])
2318 else:
2319 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.createSharedFolder(name, path, writable)])
2320 return 0
2321
2322def unshareFolderCmd(ctx,args):
2323 if (len(args) < 3):
2324 print "usage: unshareFolder vm name"
2325 return 0
2326
2327 mach = argsToMach(ctx,args)
2328 if mach is None:
2329 return 0
2330 name = args[2]
2331 found = False
2332 for sf in ctx['global'].getArray(mach, 'sharedFolders'):
2333 if sf.name == name:
2334 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeSharedFolder(name), [])
2335 found = True
2336 break
2337 if not found:
2338 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.removeSharedFolder(name)])
2339 return 0
2340
2341
2342def snapshotCmd(ctx,args):
2343 if (len(args) < 2 or args[1] == 'help'):
2344 print "Take snapshot: snapshot vm take name <description>"
2345 print "Restore snapshot: snapshot vm restore name"
2346 print "Merge snapshot: snapshot vm merge name"
2347 return 0
2348
2349 mach = argsToMach(ctx,args)
2350 if mach is None:
2351 return 0
2352 cmd = args[2]
2353 if cmd == 'take':
2354 if (len(args) < 4):
2355 print "usage: snapshot vm take name <description>"
2356 return 0
2357 name = args[3]
2358 if (len(args) > 4):
2359 desc = args[4]
2360 else:
2361 desc = ""
2362 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.takeSnapshot(name,desc)))
2363
2364 if cmd == 'restore':
2365 if (len(args) < 4):
2366 print "usage: snapshot vm restore name"
2367 return 0
2368 name = args[3]
2369 snap = mach.findSnapshot(name)
2370 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
2371 return 0
2372
2373 if cmd == 'restorecurrent':
2374 if (len(args) < 4):
2375 print "usage: snapshot vm restorecurrent"
2376 return 0
2377 snap = mach.currentSnapshot()
2378 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
2379 return 0
2380
2381 if cmd == 'delete':
2382 if (len(args) < 4):
2383 print "usage: snapshot vm delete name"
2384 return 0
2385 name = args[3]
2386 snap = mach.findSnapshot(name)
2387 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.deleteSnapshot(snap.id)))
2388 return 0
2389
2390 print "Command '%s' is unknown" %(cmd)
2391
2392 return 0
2393
2394def natAlias(ctx, mach, nicnum, nat, args=[]):
2395 """This command shows/alters NAT's alias settings.
2396 usage: nat <vm> <nicnum> alias [default|[log] [proxyonly] [sameports]]
2397 default - set settings to default values
2398 log - switch on alias loging
2399 proxyonly - switch proxyonly mode on
2400 sameports - enforces NAT using the same ports
2401 """
2402 alias = {
2403 'log': 0x1,
2404 'proxyonly': 0x2,
2405 'sameports': 0x4
2406 }
2407 if len(args) == 1:
2408 first = 0
2409 msg = ''
2410 for aliasmode, aliaskey in alias.iteritems():
2411 if first == 0:
2412 first = 1
2413 else:
2414 msg += ', '
2415 if int(nat.aliasMode) & aliaskey:
2416 msg += '{0}: {1}'.format(aliasmode, 'on')
2417 else:
2418 msg += '{0}: {1}'.format(aliasmode, 'off')
2419 msg += ')'
2420 return (0, [msg])
2421 else:
2422 nat.aliasMode = 0
2423 if 'default' not in args:
2424 for a in range(1, len(args)):
2425 if not alias.has_key(args[a]):
2426 print 'Invalid alias mode: ' + args[a]
2427 print natAlias.__doc__
2428 return (1, None)
2429 nat.aliasMode = int(nat.aliasMode) | alias[args[a]];
2430 return (0, None)
2431
2432def natSettings(ctx, mach, nicnum, nat, args):
2433 """This command shows/alters NAT settings.
2434 usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
2435 mtu - set mtu <= 16000
2436 socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
2437 tcpsndwnd/tcprcvwnd - sets size of initial tcp sending/receiving window
2438 """
2439 if len(args) == 1:
2440 (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings();
2441 if mtu == 0: mtu = 1500
2442 if socksndbuf == 0: socksndbuf = 64
2443 if sockrcvbuf == 0: sockrcvbuf = 64
2444 if tcpsndwnd == 0: tcpsndwnd = 64
2445 if tcprcvwnd == 0: tcprcvwnd = 64
2446 msg = 'mtu:{0} socket(snd:{1}, rcv:{2}) tcpwnd(snd:{3}, rcv:{4})'.format(mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd);
2447 return (0, [msg])
2448 else:
2449 if args[1] < 16000:
2450 print 'invalid mtu value ({0} no in range [65 - 16000])'.format(args[1])
2451 return (1, None)
2452 for i in range(2, len(args)):
2453 if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024:
2454 print 'invalid {0} parameter ({1} not in range [8-1024])'.format(i, args[i])
2455 return (1, None)
2456 a = [args[1]]
2457 if len(args) < 6:
2458 for i in range(2, len(args)): a.append(args[i])
2459 for i in range(len(args), 6): a.append(0)
2460 else:
2461 for i in range(2, len(args)): a.append(args[i])
2462 #print a
2463 nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))
2464 return (0, None)
2465
2466def natDns(ctx, mach, nicnum, nat, args):
2467 """This command shows/alters DNS's NAT settings
2468 usage: nat <vm> <nicnum> dns [passdomain] [proxy] [usehostresolver]
2469 passdomain - enforces builtin DHCP server to pass domain
2470 proxy - switch on builtin NAT DNS proxying mechanism
2471 usehostresolver - proxies all DNS requests to Host Resolver interface
2472 """
2473 yesno = {0: 'off', 1: 'on'}
2474 if len(args) == 1:
2475 msg = 'passdomain:{0}, proxy:{1}, usehostresolver:{2}'.format(yesno[int(nat.dnsPassDomain)], yesno[int(nat.dnsProxy)], yesno[int(nat.dnsUseHostResolver)])
2476 return (0, [msg])
2477 else:
2478 nat.dnsPassDomain = 'passdomain' in args
2479 nat.dnsProxy = 'proxy' in args
2480 nat.dnsUseHostResolver = 'usehostresolver' in args
2481 return (0, None)
2482
2483def natTftp(ctx, mach, nicnum, nat, args):
2484 """This command shows/alters TFTP settings
2485 usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
2486 prefix - alters prefix TFTP settings
2487 bootfile - alters bootfile TFTP settings
2488 server - sets booting server
2489 """
2490 if len(args) == 1:
2491 server = nat.tftpNextServer
2492 if server is None:
2493 server = nat.network
2494 if server is None:
2495 server = '10.0.{0}/24'.format(int(nicnum) + 2)
2496 (server,mask) = server.split('/')
2497 while server.count('.') != 3:
2498 server += '.0'
2499 (a,b,c,d) = server.split('.')
2500 server = '{0}.{1}.{2}.4'.format(a,b,c)
2501 prefix = nat.tftpPrefix
2502 if prefix is None:
2503 prefix = '{0}/TFTP/'.format(ctx['vb'].homeFolder)
2504 bootfile = nat.tftpBootFile
2505 if bootfile is None:
2506 bootfile = '{0}.pxe'.format(mach.name)
2507 msg = 'server:{0}, prefix:{1}, bootfile:{2}'.format(server, prefix, bootfile)
2508 return (0, [msg])
2509 else:
2510
2511 cmd = args[1]
2512 if len(args) != 3:
2513 print 'invalid args:', args
2514 print natTftp.__doc__
2515 return (1, None)
2516 if cmd == 'prefix': nat.tftpPrefix = args[2]
2517 elif cmd == 'bootfile': nat.tftpBootFile = args[2]
2518 elif cmd == 'server': nat.tftpNextServer = args[2]
2519 else:
2520 print "invalid cmd:", cmd
2521 return (1, None)
2522 return (0, None)
2523
2524def natPortForwarding(ctx, mach, nicnum, nat, args):
2525 """This command shows/manages port-forwarding settings
2526 usage:
2527 nat <vm> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
2528 |[no_name tcp|udp <hostip> <hostport> <guestip> <guestport>]
2529 |[ex tcp|udp <pf-name> <hostip> <hostport> <guestip> <guestport>]
2530 |[delete <pf-name>]
2531 """
2532 if len(args) == 1:
2533 # note: keys/values are swapped in defining part of the function
2534 proto = {0: 'udp', 1: 'tcp'}
2535 msg = []
2536 pfs = ctx['global'].getArray(nat, 'redirects')
2537 for pf in pfs:
2538 (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(',')
2539 msg.append('{0}: {1} {2}:{3} => {4}:{5}'.format(pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
2540 return (0, msg) # msg is array
2541 else:
2542 proto = {'udp': 0, 'tcp': 1}
2543 pfcmd = {
2544 'simple': {
2545 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 5,
2546 'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4]))
2547 },
2548 'no_name': {
2549 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 7,
2550 'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6]))
2551 },
2552 'ex': {
2553 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 8,
2554 'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7]))
2555 },
2556 'delete': {
2557 'validate': lambda: len(args) == 3,
2558 'func': lambda: nat.removeRedirect(args[2])
2559 }
2560 }
2561
2562 if not pfcmd[args[1]]['validate']():
2563 print 'invalid port-forwarding or args of sub command ', args[1]
2564 print natPortForwarding.__doc__
2565 return (1, None)
2566
2567 a = pfcmd[args[1]]['func']()
2568 return (0, None)
2569
2570def natNetwork(ctx, mach, nicnum, nat, args):
2571 """This command shows/alters NAT network settings
2572 usage: nat <vm> <nicnum> network [<network>]
2573 """
2574 if len(args) == 1:
2575 if nat.network is not None and len(str(nat.network)) != 0:
2576 msg = '\'%s\'' % (nat.network)
2577 else:
2578 msg = '10.0.{0}.0/24'.format(int(nicnum) + 2)
2579 return (0, [msg])
2580 else:
2581 (addr, mask) = args[1].split('/')
2582 if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
2583 print 'Invalid arguments'
2584 return (1, None)
2585 nat.network = args[1]
2586 return (0, None)
2587def natCmd(ctx, args):
2588 """This command is entry point to NAT settins management
2589 usage: nat <vm> <nicnum> <cmd> <cmd-args>
2590 cmd - [alias|settings|tftp|dns|pf|network]
2591 for more information about commands:
2592 nat help <cmd>
2593 """
2594
2595 natcommands = {
2596 'alias' : natAlias,
2597 'settings' : natSettings,
2598 'tftp': natTftp,
2599 'dns': natDns,
2600 'pf': natPortForwarding,
2601 'network': natNetwork
2602 }
2603
2604 if len(args) < 2 or args[1] == 'help':
2605 if len(args) > 2:
2606 print natcommands[args[2]].__doc__
2607 else:
2608 print natCmd.__doc__
2609 return 0
2610 if len(args) == 1 or len(args) < 4 or args[3] not in natcommands:
2611 print natCmd.__doc__
2612 return 0
2613 mach = ctx['argsToMach'](args)
2614 if mach == None:
2615 print "please specify vm"
2616 return 0
2617 if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
2618 print 'please specify adapter num {0} isn\'t in range [0-{1}]'.format(args[2], ctx['vb'].systemProperties.networkAdapterCount)
2619 return 0
2620 nicnum = int(args[2])
2621 cmdargs = []
2622 for i in range(3, len(args)):
2623 cmdargs.append(args[i])
2624
2625 # @todo vvl if nicnum is missed but command is entered
2626 # use NAT func for every adapter on machine.
2627 func = args[3]
2628 rosession = 1
2629 session = None
2630 if len(cmdargs) > 1:
2631 rosession = 0
2632 session = ctx['global'].openMachineSession(mach.id);
2633 mach = session.machine;
2634
2635 adapter = mach.getNetworkAdapter(nicnum)
2636 natEngine = adapter.natDriver
2637 (rc, report) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
2638 if rosession == 0:
2639 if rc == 0:
2640 mach.saveSettings()
2641 session.close()
2642 elif report is not None:
2643 for r in report:
2644 msg ='{0} nic{1} {2}: {3}'.format(mach.name, nicnum, func, r)
2645 print msg
2646 return 0
2647
2648def nicSwitchOnOff(adapter, attr, args):
2649 if len(args) == 1:
2650 yesno = {0: 'off', 1: 'on'}
2651 r = yesno[int(adapter.__getattr__(attr))]
2652 return (0, r)
2653 else:
2654 yesno = {'off' : 0, 'on' : 1}
2655 if args[1] not in yesno:
2656 print '%s isn\'t acceptable, please choose %s' % (args[1], yesno.keys())
2657 return (1, None)
2658 adapter.__setattr__(attr, yesno[args[1]])
2659 return (0, None)
2660
2661def nicTraceSubCmd(ctx, vm, nicnum, adapter, args):
2662 '''
2663 usage: nic <vm> <nicnum> trace [on|off [file]]
2664 '''
2665 (rc, r) = nicSwitchOnOff(adapter, 'traceEnabled', args)
2666 if len(args) == 1 and rc == 0:
2667 r = '%s file:%s' % (r, adapter.traceFile)
2668 return (0, r)
2669 elif len(args) == 3 and rc == 0:
2670 adapter.traceFile = args[2]
2671 return (0, None)
2672
2673def nicLineSpeedSubCmd(ctx, vm, nicnum, adapter, args):
2674 if len(args) == 1:
2675 r = '%d kbps'%(adapter.lineSpeed)
2676 return (0, r)
2677 else:
2678 if not args[1].isdigit():
2679 print '%s isn\'t a number'.format(args[1])
2680 print (1, None)
2681 adapter.lineSpeed = int(args[1])
2682 return (0, None)
2683
2684def nicCableSubCmd(ctx, vm, nicnum, adapter, args):
2685 '''
2686 usage: nic <vm> <nicnum> cable [on|off]
2687 '''
2688 return nicSwitchOnOff(adapter, 'cableConnected', args)
2689
2690def nicEnableSubCmd(ctx, vm, nicnum, adapter, args):
2691 '''
2692 usage: nic <vm> <nicnum> enable [on|off]
2693 '''
2694 return nicSwitchOnOff(adapter, 'enabled', args)
2695
2696def nicTypeSubCmd(ctx, vm, nicnum, adapter, args):
2697 '''
2698 usage: nic <vm> <nicnum> type [Am79c970A|Am79c970A|I82540EM|I82545EM|I82543GC|Virtio]
2699 '''
2700 if len(args) == 1:
2701 nictypes = ctx['const'].all_values('NetworkAdapterType')
2702 for n in nictypes.keys():
2703 if str(adapter.adapterType) == str(nictypes[n]):
2704 return (0, str(n))
2705 return (1, None)
2706 else:
2707 nictypes = ctx['const'].all_values('NetworkAdapterType')
2708 if args[1] not in nictypes.keys():
2709 print '%s not in acceptable values (%s)' % (args[1], nictypes.keys())
2710 return (1, None)
2711 adapter.adapterType = nictypes[args[1]]
2712 return (0, None)
2713
2714def nicAttachmentSubCmd(ctx, vm, nicnum, adapter, args):
2715 '''
2716 usage: nic <vm> <nicnum> attachment [Null|NAT|Bridged <interface>|Internal <name>|HostOnly <interface>]
2717 '''
2718 if len(args) == 1:
2719 nicAttachmentType = {
2720 ctx['global'].constants.NetworkAttachmentType_Null: ('Null', ''),
2721 ctx['global'].constants.NetworkAttachmentType_NAT: ('NAT', ''),
2722 ctx['global'].constants.NetworkAttachmentType_Bridged: ('Bridged', adapter.hostInterface),
2723 ctx['global'].constants.NetworkAttachmentType_Internal: ('Internal', adapter.internalNetwork),
2724 ctx['global'].constants.NetworkAttachmentType_HostOnly: ('HostOnly', adapter.hostInterface),
2725 #ctx['global'].constants.NetworkAttachmentType_VDE: ('VDE', adapter.VDENetwork)
2726 }
2727 import types
2728 if type(adapter.attachmentType) != types.IntType:
2729 t = str(adapter.attachmentType)
2730 else:
2731 t = adapter.attachmentType
2732 (r, p) = nicAttachmentType[t]
2733 return (0, 'attachment:{0}, name:{1}'.format(r, p))
2734 else:
2735 nicAttachmentType = {
2736 'Null': {
2737 'v': lambda: len(args) == 2,
2738 'p': lambda: 'do nothing',
2739 'f': lambda: adapter.detach()},
2740 'NAT': {
2741 'v': lambda: len(args) == 2,
2742 'p': lambda: 'do nothing',
2743 'f': lambda: adapter.attachToNAT()},
2744 'Bridged': {
2745 'v': lambda: len(args) == 3,
2746 'p': lambda: adapter.__setattr__('hostInterface', args[2]),
2747 'f': lambda: adapter.attachToBridgedInterface()},
2748 'Internal': {
2749 'v': lambda: len(args) == 3,
2750 'p': lambda: adapter.__setattr__('internalNetwork', args[2]),
2751 'f': lambda: adapter.attachToInternalNetwork()},
2752 'HostOnly': {
2753 'v': lambda: len(args) == 2,
2754 'p': lambda: adapter.__setattr__('hostInterface', args[2]),
2755 'f': lambda: adapter.attachToHostOnlyInterface()},
2756 'VDE': {
2757 'v': lambda: len(args) == 3,
2758 'p': lambda: adapter.__setattr__('VDENetwork', args[2]),
2759 'f': lambda: adapter.attachToVDE()}
2760 }
2761 if args[1] not in nicAttachmentType.keys():
2762 print '{0} not in acceptable values ({1})'.format(args[1], nicAttachmentType.keys())
2763 return (1, None)
2764 if not nicAttachmentType[args[1]]['v']():
2765 print nicAttachmentType.__doc__
2766 return (1, None)
2767 nicAttachmentType[args[1]]['p']()
2768 nicAttachmentType[args[1]]['f']()
2769 return (0, None)
2770
2771def nicCmd(ctx, args):
2772 '''
2773 This command to manage network adapters
2774 usage: nic <vm> <nicnum> <cmd> <cmd-args>
2775 where cmd : attachment, trace, linespeed, cable, enable, type
2776 '''
2777 # 'command name':{'runtime': is_callable_at_runtime, 'op': function_name}
2778 niccomand = {
2779 'attachment': nicAttachmentSubCmd,
2780 'trace': nicTraceSubCmd,
2781 'linespeed': nicLineSpeedSubCmd,
2782 'cable': nicCableSubCmd,
2783 'enable': nicEnableSubCmd,
2784 'type': nicTypeSubCmd
2785 }
2786 if len(args) < 2 \
2787 or args[1] == 'help' \
2788 or (len(args) > 2 and args[3] not in niccomand):
2789 if len(args) == 3 \
2790 and args[2] in niccomand:
2791 print niccomand[args[2]].__doc__
2792 else:
2793 print nicCmd.__doc__
2794 return 0
2795
2796 vm = ctx['argsToMach'](args)
2797 if vm is None:
2798 print 'please specify vm'
2799 return 0
2800
2801 if len(args) < 3 \
2802 or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
2803 print 'please specify adapter num %d isn\'t in range [0-%d]'%(args[2], ctx['vb'].systemProperties.networkAdapterCount)
2804 return 0
2805 nicnum = int(args[2])
2806 cmdargs = args[3:]
2807 func = args[3]
2808 session = None
2809 session = ctx['global'].openMachineSession(vm.id)
2810 vm = session.machine
2811 adapter = vm.getNetworkAdapter(nicnum)
2812 (rc, report) = niccomand[func](ctx, vm, nicnum, adapter, cmdargs)
2813 if rc == 0:
2814 vm.saveSettings()
2815 if report is not None:
2816 print '%s nic %d %s: %s' % (vm.name, nicnum, args[3], report)
2817 session.close()
2818 return 0
2819
2820
2821def promptCmd(ctx, args):
2822 if len(args) < 2:
2823 print "Current prompt: '%s'" %(ctx['prompt'])
2824 return 0
2825
2826 ctx['prompt'] = args[1]
2827 return 0
2828
2829def foreachCmd(ctx, args):
2830 if len(args) < 3:
2831 print "usage: foreach scope command, where scope is XPath-like expression //vms/vm[@CPUCount='2']"
2832 return 0
2833
2834 scope = args[1]
2835 cmd = args[2]
2836 elems = eval_xpath(ctx,scope)
2837 try:
2838 for e in elems:
2839 e.apply(cmd)
2840 except:
2841 print "Error executing"
2842 traceback.print_exc()
2843 return 0
2844
2845def foreachvmCmd(ctx, args):
2846 if len(args) < 2:
2847 print "foreachvm command <args>"
2848 return 0
2849 cmdargs = args[1:]
2850 cmdargs.insert(1, '')
2851 for m in getMachines(ctx):
2852 cmdargs[1] = m.id
2853 runCommandArgs(ctx, cmdargs)
2854 return 0
2855
2856aliases = {'s':'start',
2857 'i':'info',
2858 'l':'list',
2859 'h':'help',
2860 'a':'alias',
2861 'q':'quit', 'exit':'quit',
2862 'tg': 'typeGuest',
2863 'v':'verbose'}
2864
2865commands = {'help':['Prints help information', helpCmd, 0],
2866 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
2867 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
2868 'removeVm':['Remove virtual machine', removeVmCmd, 0],
2869 'pause':['Pause virtual machine', pauseCmd, 0],
2870 'resume':['Resume virtual machine', resumeCmd, 0],
2871 'save':['Save execution state of virtual machine', saveCmd, 0],
2872 'stats':['Stats for virtual machine', statsCmd, 0],
2873 'powerdown':['Power down virtual machine', powerdownCmd, 0],
2874 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
2875 'list':['Shows known virtual machines', listCmd, 0],
2876 'info':['Shows info on machine', infoCmd, 0],
2877 'ginfo':['Shows info on guest', ginfoCmd, 0],
2878 'gexec':['Executes program in the guest', gexecCmd, 0],
2879 'alias':['Control aliases', aliasCmd, 0],
2880 'verbose':['Toggle verbosity', verboseCmd, 0],
2881 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
2882 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
2883 'quit':['Exits', quitCmd, 0],
2884 'host':['Show host information', hostCmd, 0],
2885 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
2886 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
2887 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
2888 'monitorVBox2':['(temp)Monitor what happens with Virtual Box for some time: monitorVBox2 10', monitorVBox2Cmd, 0],
2889 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
2890 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
2891 'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
2892 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
2893 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
2894 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
2895 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
2896 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
2897 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
2898 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
2899 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
2900 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
2901 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
2902 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
2903 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
2904 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
2905 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
2906 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
2907 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
2908 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
2909 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
2910 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
2911 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
2912 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
2913 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
2914 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
2915 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
2916 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
2917 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
2918 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
2919 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
2920 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
2921 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
2922 'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
2923 'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
2924 'listMedia': ['List media known to this VBox instance', listMediaCmd, 0],
2925 'listUsb': ['List known USB devices', listUsbCmd, 0],
2926 'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
2927 'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
2928 'gui': ['Start GUI frontend', guiCmd, 0],
2929 'colors':['Toggle colors', colorsCmd, 0],
2930 'snapshot':['VM snapshot manipulation, snapshot help for more info', snapshotCmd, 0],
2931 'nat':['NAT (network address trasnlation engine) manipulation, nat help for more info', natCmd, 0],
2932 'nic' : ['Network adapter management', nicCmd, 0],
2933 'prompt' : ['Control prompt', promptCmd, 0],
2934 'foreachvm' : ['Perform command for each VM', foreachvmCmd, 0],
2935 'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print obj.name"', foreachCmd, 0],
2936 }
2937
2938def runCommandArgs(ctx, args):
2939 c = args[0]
2940 if aliases.get(c, None) != None:
2941 c = aliases[c]
2942 ci = commands.get(c,None)
2943 if ci == None:
2944 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
2945 return 0
2946 if ctx['remote'] and ctx['vb'] is None:
2947 if c not in ['connect', 'reconnect', 'help', 'quit']:
2948 print "First connect to remote server with %s command." %(colored('connect', 'blue'))
2949 return 0
2950 return ci[1](ctx, args)
2951
2952
2953def runCommand(ctx, cmd):
2954 if len(cmd) == 0: return 0
2955 args = split_no_quotes(cmd)
2956 if len(args) == 0: return 0
2957 return runCommandArgs(ctx, args)
2958
2959#
2960# To write your own custom commands to vboxshell, create
2961# file ~/.VirtualBox/shellext.py with content like
2962#
2963# def runTestCmd(ctx, args):
2964# print "Testy test", ctx['vb']
2965# return 0
2966#
2967# commands = {
2968# 'test': ['Test help', runTestCmd]
2969# }
2970# and issue reloadExt shell command.
2971# This file also will be read automatically on startup or 'reloadExt'.
2972#
2973# Also one can put shell extensions into ~/.VirtualBox/shexts and
2974# they will also be picked up, so this way one can exchange
2975# shell extensions easily.
2976def addExtsFromFile(ctx, cmds, file):
2977 if not os.path.isfile(file):
2978 return
2979 d = {}
2980 try:
2981 execfile(file, d, d)
2982 for (k,v) in d['commands'].items():
2983 if g_verbose:
2984 print "customize: adding \"%s\" - %s" %(k, v[0])
2985 cmds[k] = [v[0], v[1], file]
2986 except:
2987 print "Error loading user extensions from %s" %(file)
2988 traceback.print_exc()
2989
2990
2991def checkUserExtensions(ctx, cmds, folder):
2992 folder = str(folder)
2993 name = os.path.join(folder, "shellext.py")
2994 addExtsFromFile(ctx, cmds, name)
2995 # also check 'exts' directory for all files
2996 shextdir = os.path.join(folder, "shexts")
2997 if not os.path.isdir(shextdir):
2998 return
2999 exts = os.listdir(shextdir)
3000 for e in exts:
3001 # not editor temporary files, please.
3002 if e.endswith('.py'):
3003 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
3004
3005def getHomeFolder(ctx):
3006 if ctx['remote'] or ctx['vb'] is None:
3007 if 'VBOX_USER_HOME' in os.environ:
3008 return os.path.join(os.environ['VBOX_USER_HOME'])
3009 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
3010 else:
3011 return ctx['vb'].homeFolder
3012
3013def interpret(ctx):
3014 if ctx['remote']:
3015 commands['connect'] = ["Connect to remote VBox instance: connect http://server:18083 user password", connectCmd, 0]
3016 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
3017 commands['reconnect'] = ["Reconnect to remote VBox instance", reconnectCmd, 0]
3018 ctx['wsinfo'] = ["http://localhost:18083", "", ""]
3019
3020 vbox = ctx['vb']
3021 if vbox is not None:
3022 print "Running VirtualBox version %s" %(vbox.version)
3023 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
3024 else:
3025 ctx['perf'] = None
3026
3027 home = getHomeFolder(ctx)
3028 checkUserExtensions(ctx, commands, home)
3029 if platform.system() == 'Windows':
3030 global g_hascolors
3031 g_hascolors = False
3032 hist_file=os.path.join(home, ".vboxshellhistory")
3033 autoCompletion(commands, ctx)
3034
3035 if g_hasreadline and os.path.exists(hist_file):
3036 readline.read_history_file(hist_file)
3037
3038 # to allow to print actual host information, we collect info for
3039 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
3040 if ctx['perf']:
3041 try:
3042 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
3043 except:
3044 pass
3045
3046 while True:
3047 try:
3048 cmd = raw_input(ctx['prompt'])
3049 done = runCommand(ctx, cmd)
3050 if done != 0: break
3051 except KeyboardInterrupt:
3052 print '====== You can type quit or q to leave'
3053 except EOFError:
3054 break
3055 except Exception,e:
3056 printErr(ctx,e)
3057 if g_verbose:
3058 traceback.print_exc()
3059 ctx['global'].waitForEvents(0)
3060 try:
3061 # There is no need to disable metric collection. This is just an example.
3062 if ct['perf']:
3063 ctx['perf'].disable(['*'], [vbox.host])
3064 except:
3065 pass
3066 if g_hasreadline:
3067 readline.write_history_file(hist_file)
3068
3069def runCommandCb(ctx, cmd, args):
3070 args.insert(0, cmd)
3071 return runCommandArgs(ctx, args)
3072
3073def runGuestCommandCb(ctx, id, guestLambda, args):
3074 mach = machById(ctx,id)
3075 if mach == None:
3076 return 0
3077 args.insert(0, guestLambda)
3078 cmdExistingVm(ctx, mach, 'guestlambda', args)
3079 return 0
3080
3081def main(argv):
3082 style = None
3083 autopath = False
3084 argv.pop(0)
3085 while len(argv) > 0:
3086 if argv[0] == "-w":
3087 style = "WEBSERVICE"
3088 if argv[0] == "-a":
3089 autopath = True
3090 argv.pop(0)
3091
3092 if autopath:
3093 cwd = os.getcwd()
3094 vpp = os.environ.get("VBOX_PROGRAM_PATH")
3095 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
3096 vpp = cwd
3097 print "Autodetected VBOX_PROGRAM_PATH as",vpp
3098 os.environ["VBOX_PROGRAM_PATH"] = cwd
3099 sys.path.append(os.path.join(vpp, "sdk", "installer"))
3100
3101 from vboxapi import VirtualBoxManager
3102 g_virtualBoxManager = VirtualBoxManager(style, None)
3103 ctx = {'global':g_virtualBoxManager,
3104 'mgr':g_virtualBoxManager.mgr,
3105 'vb':g_virtualBoxManager.vbox,
3106 'const':g_virtualBoxManager.constants,
3107 'remote':g_virtualBoxManager.remote,
3108 'type':g_virtualBoxManager.type,
3109 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
3110 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
3111 'machById': lambda id: machById(ctx,id),
3112 'argsToMach': lambda args: argsToMach(ctx,args),
3113 'progressBar': lambda p: progressBar(ctx,p),
3114 'typeInGuest': typeInGuest,
3115 '_machlist': None,
3116 'prompt': g_prompt
3117 }
3118 interpret(ctx)
3119 g_virtualBoxManager.deinit()
3120 del g_virtualBoxManager
3121
3122if __name__ == '__main__':
3123 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