VirtualBox

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

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

Events: docs, properly cleanup queue in passive mode

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