VirtualBox

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

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

python shell: no longer attempt to print max bandwidth (removed)

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

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