VirtualBox

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

Last change on this file since 30387 was 30387, checked in by vboxsync, 14 years ago

vboxshell: don't display an error message for 'snapshot vm take'

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

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