VirtualBox

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

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

python: bridge code for active listeners, sample using it in shell

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