VirtualBox

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

Last change on this file since 31890 was 31783, checked in by vboxsync, 14 years ago

vboxshell: typo

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