VirtualBox

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

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

Python: active callbacks with Windows Python

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