VirtualBox

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

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

Main/Medium+MediumFormat+GuestOSType+SystemPropertiesImpl+Console+Global: consistently use bytes as size units, forgotten const value in API, MaxVDISize method renamed to InfoVDSize, STDMETHOD macro usage fixes, whitespace cleanup

Frontends/VirtualBox+VBoxManage+VBoxShell: adapt to changed disk size units

Main/StorageControllerImpl: check the storage controller instance limit to avoid creating unusable VM configs, simplify unnecessarily complex code for querying the controller properties

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

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