VirtualBox

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

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

vboxshell: confurm event processing

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