VirtualBox

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

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

VBoxShell: option parser has been inroduced (from python 2.3) and options disscused in xTracker/#4329.

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