VirtualBox

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

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

Main: PNG screenshoting API

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

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