VirtualBox

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

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

vboxshell: gracefull handling of unavailable VMs, better treatment of closed VM commands

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

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