VirtualBox

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

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

Main, some frontends: removing callbacks

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

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