VirtualBox

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

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

VBoxShell: get rid of callbacks

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