VirtualBox

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

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

VBoxShell: active mode events test

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

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