VirtualBox

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

Last change on this file since 33154 was 33075, checked in by vboxsync, 14 years ago

Main: also support absolute mouse events

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