VirtualBox

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

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

VBoxShell: typo.

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