VirtualBox

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

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

vboxshell: prompts

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 92.3 KB
Line 
1#!/usr/bin/python
2#
3# Copyright (C) 2009-2010 Oracle Corporation
4#
5# This file is part of VirtualBox Open Source Edition (OSE), as
6# available from http://www.215389.xyz. This file is free software;
7# you can redistribute it and/or modify it under the terms of the GNU
8# General Public License (GPL) as published by the Free Software
9# Foundation, in version 2 as it comes in the "COPYING" file of the
10# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
11# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
12#
13#################################################################################
14# This program is a simple interactive shell for VirtualBox. You can query #
15# information and issue commands from a simple command line. #
16# #
17# It also provides you with examples on how to use VirtualBox's Python API. #
18# This shell is even somewhat documented, supports TAB-completion and #
19# history if you have Python readline installed. #
20# #
21# Finally, shell allows arbitrary custom extensions, just create #
22# .VirtualBox/shexts/ and drop your extensions there. #
23# Enjoy. #
24################################################################################
25
26import os,sys
27import traceback
28import shlex
29import time
30import re
31import platform
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['ifaces'].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, 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['ifaces'].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['ifaces'].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['ifaces'].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 [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
736 hwVirtVPID = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID)
737 print " VPID support [mach.setHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
738 hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_NestedPaging)
739 print " Nested paging [mach.setHWVirtExProperty(ctx['global'].constants.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" %(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" %(m.location)
791 if a.passthrough:
792 print " [passthrough mode]"
793 else:
794 print " Virtual image at %s" %(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" %(m.location)
804 else:
805 print " Virtual image at %s" %(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 if progress.completed:
874 break
875
876 except KeyboardInterrupt:
877 print "Interrupted."
878 if progress.cancelable:
879 progress.cancel()
880 (reason, code, flags) = guest.getProcessStatus(pid)
881 print "Exit code: %d" %(code)
882 return 0
883 else:
884 reportError(ctx, progress)
885
886def nh_raw_input(prompt=""):
887 stream = sys.stdout
888 prompt = str(prompt)
889 if prompt:
890 stream.write(prompt)
891 line = sys.stdin.readline()
892 if not line:
893 raise EOFError
894 if line[-1] == '\n':
895 line = line[:-1]
896 return line
897
898
899def getCred(ctx):
900 import getpass
901 user = getpass.getuser()
902 user_inp = nh_raw_input("User (%s): " %(user))
903 if len (user_inp) > 0:
904 user = user_inp
905 passwd = getpass.getpass()
906
907 return (user,passwd)
908
909def gexecCmd(ctx,args):
910 if (len(args) < 2):
911 print "usage: gexec [vmname|uuid] command args"
912 return 0
913 mach = argsToMach(ctx,args)
914 if mach == None:
915 return 0
916 gargs = args[2:]
917 env = [] # ["DISPLAY=:0"]
918 (user,passwd) = getCred(ctx)
919 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env,user,passwd,10000))
920 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
921 return 0
922
923def gcatCmd(ctx,args):
924 if (len(args) < 2):
925 print "usage: gcat [vmname|uuid] local_file | guestProgram, such as gcat linux /home/nike/.bashrc | sh -c 'cat >'"
926 return 0
927 mach = argsToMach(ctx,args)
928 if mach == None:
929 return 0
930 gargs = args[2:]
931 env = []
932 (user,passwd) = getCred(ctx)
933 gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env, user, passwd, 0))
934 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
935 return 0
936
937
938def removeVmCmd(ctx, args):
939 mach = argsToMach(ctx,args)
940 if mach == None:
941 return 0
942 removeVm(ctx, mach)
943 return 0
944
945def pauseCmd(ctx, args):
946 mach = argsToMach(ctx,args)
947 if mach == None:
948 return 0
949 cmdExistingVm(ctx, mach, 'pause', '')
950 return 0
951
952def powerdownCmd(ctx, args):
953 mach = argsToMach(ctx,args)
954 if mach == None:
955 return 0
956 cmdExistingVm(ctx, mach, 'powerdown', '')
957 return 0
958
959def powerbuttonCmd(ctx, args):
960 mach = argsToMach(ctx,args)
961 if mach == None:
962 return 0
963 cmdExistingVm(ctx, mach, 'powerbutton', '')
964 return 0
965
966def resumeCmd(ctx, args):
967 mach = argsToMach(ctx,args)
968 if mach == None:
969 return 0
970 cmdExistingVm(ctx, mach, 'resume', '')
971 return 0
972
973def saveCmd(ctx, args):
974 mach = argsToMach(ctx,args)
975 if mach == None:
976 return 0
977 cmdExistingVm(ctx, mach, 'save', '')
978 return 0
979
980def statsCmd(ctx, args):
981 mach = argsToMach(ctx,args)
982 if mach == None:
983 return 0
984 cmdExistingVm(ctx, mach, 'stats', '')
985 return 0
986
987def guestCmd(ctx, args):
988 if (len(args) < 3):
989 print "usage: guest name commands"
990 return 0
991 mach = argsToMach(ctx,args)
992 if mach == None:
993 return 0
994 cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
995 return 0
996
997def screenshotCmd(ctx, args):
998 if (len(args) < 2):
999 print "usage: screenshot vm <file> <width> <height> <monitor>"
1000 return 0
1001 mach = argsToMach(ctx,args)
1002 if mach == None:
1003 return 0
1004 cmdExistingVm(ctx, mach, 'screenshot', args[2:])
1005 return 0
1006
1007def teleportCmd(ctx, args):
1008 if (len(args) < 3):
1009 print "usage: teleport name host:port <password>"
1010 return 0
1011 mach = argsToMach(ctx,args)
1012 if mach == None:
1013 return 0
1014 cmdExistingVm(ctx, mach, 'teleport', args[2:])
1015 return 0
1016
1017def portalsettings(ctx,mach,args):
1018 enabled = args[0]
1019 mach.teleporterEnabled = enabled
1020 if enabled:
1021 port = args[1]
1022 passwd = args[2]
1023 mach.teleporterPort = port
1024 mach.teleporterPassword = passwd
1025
1026def openportalCmd(ctx, args):
1027 if (len(args) < 3):
1028 print "usage: openportal name port <password>"
1029 return 0
1030 mach = argsToMach(ctx,args)
1031 if mach == None:
1032 return 0
1033 port = int(args[2])
1034 if (len(args) > 3):
1035 passwd = args[3]
1036 else:
1037 passwd = ""
1038 if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
1039 cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
1040 startVm(ctx, mach, "gui")
1041 return 0
1042
1043def closeportalCmd(ctx, args):
1044 if (len(args) < 2):
1045 print "usage: closeportal name"
1046 return 0
1047 mach = argsToMach(ctx,args)
1048 if mach == None:
1049 return 0
1050 if mach.teleporterEnabled:
1051 cmdClosedVm(ctx, mach, portalsettings, [False])
1052 return 0
1053
1054def gueststatsCmd(ctx, args):
1055 if (len(args) < 2):
1056 print "usage: gueststats name <check interval>"
1057 return 0
1058 mach = argsToMach(ctx,args)
1059 if mach == None:
1060 return 0
1061 cmdExistingVm(ctx, mach, 'gueststats', args[2:])
1062 return 0
1063
1064def plugcpu(ctx,mach,args):
1065 plug = args[0]
1066 cpu = args[1]
1067 if plug:
1068 print "Adding CPU %d..." %(cpu)
1069 mach.hotPlugCPU(cpu)
1070 else:
1071 print "Removing CPU %d..." %(cpu)
1072 mach.hotUnplugCPU(cpu)
1073
1074def plugcpuCmd(ctx, args):
1075 if (len(args) < 2):
1076 print "usage: plugcpu name cpuid"
1077 return 0
1078 mach = argsToMach(ctx,args)
1079 if mach == None:
1080 return 0
1081 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
1082 if mach.CPUHotPlugEnabled:
1083 cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
1084 else:
1085 cmdExistingVm(ctx, mach, 'plugcpu', args[2])
1086 return 0
1087
1088def unplugcpuCmd(ctx, args):
1089 if (len(args) < 2):
1090 print "usage: unplugcpu name cpuid"
1091 return 0
1092 mach = argsToMach(ctx,args)
1093 if mach == None:
1094 return 0
1095 if str(mach.sessionState) != str(ctx['ifaces'].SessionState_Open):
1096 if mach.CPUHotPlugEnabled:
1097 cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
1098 else:
1099 cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
1100 return 0
1101
1102def setvar(ctx,mach,args):
1103 expr = 'mach.'+args[0]+' = '+args[1]
1104 print "Executing",expr
1105 exec expr
1106
1107def setvarCmd(ctx, args):
1108 if (len(args) < 4):
1109 print "usage: setvar [vmname|uuid] expr value"
1110 return 0
1111 mach = argsToMach(ctx,args)
1112 if mach == None:
1113 return 0
1114 cmdClosedVm(ctx, mach, setvar, args[2:])
1115 return 0
1116
1117def setvmextra(ctx,mach,args):
1118 key = args[0]
1119 value = args[1]
1120 print "%s: setting %s to %s" %(mach.name, key, value)
1121 mach.setExtraData(key, value)
1122
1123def setExtraDataCmd(ctx, args):
1124 if (len(args) < 3):
1125 print "usage: setextra [vmname|uuid|global] key <value>"
1126 return 0
1127 key = args[2]
1128 if len(args) == 4:
1129 value = args[3]
1130 else:
1131 value = None
1132 if args[1] == 'global':
1133 ctx['vb'].setExtraData(key, value)
1134 return 0
1135
1136 mach = argsToMach(ctx,args)
1137 if mach == None:
1138 return 0
1139 cmdClosedVm(ctx, mach, setvmextra, [key, value])
1140 return 0
1141
1142def printExtraKey(obj, key, value):
1143 print "%s: '%s' = '%s'" %(obj, key, value)
1144
1145def getExtraDataCmd(ctx, args):
1146 if (len(args) < 2):
1147 print "usage: getextra [vmname|uuid|global] <key>"
1148 return 0
1149 if len(args) == 3:
1150 key = args[2]
1151 else:
1152 key = None
1153
1154 if args[1] == 'global':
1155 obj = ctx['vb']
1156 else:
1157 obj = argsToMach(ctx,args)
1158 if obj == None:
1159 return 0
1160
1161 if key == None:
1162 keys = obj.getExtraDataKeys()
1163 else:
1164 keys = [ key ]
1165 for k in keys:
1166 printExtraKey(args[1], k, obj.getExtraData(k))
1167
1168 return 0
1169
1170def quitCmd(ctx, args):
1171 return 1
1172
1173def aliasCmd(ctx, args):
1174 if (len(args) == 3):
1175 aliases[args[1]] = args[2]
1176 return 0
1177
1178 for (k,v) in aliases.items():
1179 print "'%s' is an alias for '%s'" %(k,v)
1180 return 0
1181
1182def verboseCmd(ctx, args):
1183 global g_verbose
1184 g_verbose = not g_verbose
1185 return 0
1186
1187def colorsCmd(ctx, args):
1188 global g_hascolors
1189 g_hascolors = not g_hascolors
1190 return 0
1191
1192def hostCmd(ctx, args):
1193 vb = ctx['vb']
1194 print "VirtualBox version %s" %(colored(vb.version, 'blue'))
1195 props = vb.systemProperties
1196 print "Machines: %s" %(colPath(ctx,props.defaultMachineFolder))
1197 print "HDDs: %s" %(colPath(ctx,props.defaultHardDiskFolder))
1198
1199 #print "Global shared folders:"
1200 #for ud in ctx['global'].getArray(vb, 'sharedFolders'):
1201 # printSf(ctx,sf)
1202 host = vb.host
1203 cnt = host.processorCount
1204 print colCat(ctx,"Processors:")
1205 print " available/online: %d/%d " %(cnt,host.processorOnlineCount)
1206 for i in range(0,cnt):
1207 print " processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
1208
1209 print colCat(ctx, "RAM:")
1210 print " %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
1211 print colCat(ctx,"OS:");
1212 print " %s (%s)" %(host.operatingSystem, host.OSVersion)
1213 if host.Acceleration3DAvailable:
1214 print colCat(ctx,"3D acceleration available")
1215 else:
1216 print colCat(ctx,"3D acceleration NOT available")
1217
1218 print colCat(ctx,"Network interfaces:")
1219 for ni in ctx['global'].getArray(host, 'networkInterfaces'):
1220 print " %s (%s)" %(ni.name, ni.IPAddress)
1221
1222 print colCat(ctx,"DVD drives:")
1223 for dd in ctx['global'].getArray(host, 'DVDDrives'):
1224 print " %s - %s" %(dd.name, dd.description)
1225
1226 print colCat(ctx,"Floppy drives:")
1227 for dd in ctx['global'].getArray(host, 'floppyDrives'):
1228 print " %s - %s" %(dd.name, dd.description)
1229
1230 print colCat(ctx,"USB devices:")
1231 for ud in ctx['global'].getArray(host, 'USBDevices'):
1232 printHostUsbDev(ctx,ud)
1233
1234 if ctx['perf']:
1235 for metric in ctx['perf'].query(["*"], [host]):
1236 print metric['name'], metric['values_as_string']
1237
1238 return 0
1239
1240def monitorGuestCmd(ctx, args):
1241 if (len(args) < 2):
1242 print "usage: monitorGuest name (duration)"
1243 return 0
1244 mach = argsToMach(ctx,args)
1245 if mach == None:
1246 return 0
1247 dur = 5
1248 if len(args) > 2:
1249 dur = float(args[2])
1250 cmdExistingVm(ctx, mach, 'monitorGuest', dur)
1251 return 0
1252
1253def monitorVBoxCmd(ctx, args):
1254 if (len(args) > 2):
1255 print "usage: monitorVBox (duration)"
1256 return 0
1257 dur = 5
1258 if len(args) > 1:
1259 dur = float(args[1])
1260 monitorVBox(ctx, dur)
1261 return 0
1262
1263def getAdapterType(ctx, type):
1264 if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
1265 type == ctx['global'].constants.NetworkAdapterType_Am79C973):
1266 return "pcnet"
1267 elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
1268 type == ctx['global'].constants.NetworkAdapterType_I82545EM or
1269 type == ctx['global'].constants.NetworkAdapterType_I82543GC):
1270 return "e1000"
1271 elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
1272 return "virtio"
1273 elif (type == ctx['global'].constants.NetworkAdapterType_Null):
1274 return None
1275 else:
1276 raise Exception("Unknown adapter type: "+type)
1277
1278
1279def portForwardCmd(ctx, args):
1280 if (len(args) != 5):
1281 print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
1282 return 0
1283 mach = argsToMach(ctx,args)
1284 if mach == None:
1285 return 0
1286 adapterNum = int(args[2])
1287 hostPort = int(args[3])
1288 guestPort = int(args[4])
1289 proto = "TCP"
1290 session = ctx['global'].openMachineSession(mach.id)
1291 mach = session.machine
1292
1293 adapter = mach.getNetworkAdapter(adapterNum)
1294 adapterType = getAdapterType(ctx, adapter.adapterType)
1295
1296 profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
1297 config = "VBoxInternal/Devices/" + adapterType + "/"
1298 config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name
1299
1300 mach.setExtraData(config + "/Protocol", proto)
1301 mach.setExtraData(config + "/HostPort", str(hostPort))
1302 mach.setExtraData(config + "/GuestPort", str(guestPort))
1303
1304 mach.saveSettings()
1305 session.close()
1306
1307 return 0
1308
1309
1310def showLogCmd(ctx, args):
1311 if (len(args) < 2):
1312 print "usage: showLog vm <num>"
1313 return 0
1314 mach = argsToMach(ctx,args)
1315 if mach == None:
1316 return 0
1317
1318 log = 0
1319 if (len(args) > 2):
1320 log = args[2]
1321
1322 uOffset = 0
1323 while True:
1324 data = mach.readLog(log, uOffset, 4096)
1325 if (len(data) == 0):
1326 break
1327 # print adds either NL or space to chunks not ending with a NL
1328 sys.stdout.write(str(data))
1329 uOffset += len(data)
1330
1331 return 0
1332
1333def findLogCmd(ctx, args):
1334 if (len(args) < 3):
1335 print "usage: findLog vm pattern <num>"
1336 return 0
1337 mach = argsToMach(ctx,args)
1338 if mach == None:
1339 return 0
1340
1341 log = 0
1342 if (len(args) > 3):
1343 log = args[3]
1344
1345 pattern = args[2]
1346 uOffset = 0
1347 while True:
1348 # to reduce line splits on buffer boundary
1349 data = mach.readLog(log, uOffset, 512*1024)
1350 if (len(data) == 0):
1351 break
1352 d = str(data).split("\n")
1353 for s in d:
1354 m = re.findall(pattern, s)
1355 if len(m) > 0:
1356 for mt in m:
1357 s = s.replace(mt, colored(mt,'red'))
1358 print s
1359 uOffset += len(data)
1360
1361 return 0
1362
1363def evalCmd(ctx, args):
1364 expr = ' '.join(args[1:])
1365 try:
1366 exec expr
1367 except Exception, e:
1368 printErr(ctx,e)
1369 if g_verbose:
1370 traceback.print_exc()
1371 return 0
1372
1373def reloadExtCmd(ctx, args):
1374 # maybe will want more args smartness
1375 checkUserExtensions(ctx, commands, getHomeFolder(ctx))
1376 autoCompletion(commands, ctx)
1377 return 0
1378
1379
1380def runScriptCmd(ctx, args):
1381 if (len(args) != 2):
1382 print "usage: runScript <script>"
1383 return 0
1384 try:
1385 lf = open(args[1], 'r')
1386 except IOError,e:
1387 print "cannot open:",args[1], ":",e
1388 return 0
1389
1390 try:
1391 for line in lf:
1392 done = runCommand(ctx, line)
1393 if done != 0: break
1394 except Exception,e:
1395 printErr(ctx,e)
1396 if g_verbose:
1397 traceback.print_exc()
1398 lf.close()
1399 return 0
1400
1401def sleepCmd(ctx, args):
1402 if (len(args) != 2):
1403 print "usage: sleep <secs>"
1404 return 0
1405
1406 try:
1407 time.sleep(float(args[1]))
1408 except:
1409 # to allow sleep interrupt
1410 pass
1411 return 0
1412
1413
1414def shellCmd(ctx, args):
1415 if (len(args) < 2):
1416 print "usage: shell <commands>"
1417 return 0
1418 cmd = ' '.join(args[1:])
1419
1420 try:
1421 os.system(cmd)
1422 except KeyboardInterrupt:
1423 # to allow shell command interruption
1424 pass
1425 return 0
1426
1427
1428def connectCmd(ctx, args):
1429 if (len(args) > 4):
1430 print "usage: connect url <username> <passwd>"
1431 return 0
1432
1433 if ctx['vb'] is not None:
1434 print "Already connected, disconnect first..."
1435 return 0
1436
1437 if (len(args) > 1):
1438 url = args[1]
1439 else:
1440 url = None
1441
1442 if (len(args) > 2):
1443 user = args[2]
1444 else:
1445 user = ""
1446
1447 if (len(args) > 3):
1448 passwd = args[3]
1449 else:
1450 passwd = ""
1451
1452 ctx['wsinfo'] = [url, user, passwd]
1453 vbox = ctx['global'].platform.connect(url, user, passwd)
1454 ctx['vb'] = vbox
1455 print "Running VirtualBox version %s" %(vbox.version)
1456 ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
1457 return 0
1458
1459def disconnectCmd(ctx, args):
1460 if (len(args) != 1):
1461 print "usage: disconnect"
1462 return 0
1463
1464 if ctx['vb'] is None:
1465 print "Not connected yet."
1466 return 0
1467
1468 try:
1469 ctx['global'].platform.disconnect()
1470 except:
1471 ctx['vb'] = None
1472 raise
1473
1474 ctx['vb'] = None
1475 return 0
1476
1477def reconnectCmd(ctx, args):
1478 if ctx['wsinfo'] is None:
1479 print "Never connected..."
1480 return 0
1481
1482 try:
1483 ctx['global'].platform.disconnect()
1484 except:
1485 pass
1486
1487 [url,user,passwd] = ctx['wsinfo']
1488 ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
1489 print "Running VirtualBox version %s" %(ctx['vb'].version)
1490 return 0
1491
1492def exportVMCmd(ctx, args):
1493 import sys
1494
1495 if len(args) < 3:
1496 print "usage: exportVm <machine> <path> <format> <license>"
1497 return 0
1498 mach = argsToMach(ctx,args)
1499 if mach is None:
1500 return 0
1501 path = args[2]
1502 if (len(args) > 3):
1503 format = args[3]
1504 else:
1505 format = "ovf-1.0"
1506 if (len(args) > 4):
1507 license = args[4]
1508 else:
1509 license = "GPL"
1510
1511 app = ctx['vb'].createAppliance()
1512 desc = mach.export(app)
1513 desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
1514 p = app.write(format, path)
1515 if (progressBar(ctx, p) and int(p.resultCode) == 0):
1516 print "Exported to %s in format %s" %(path, format)
1517 else:
1518 reportError(ctx,p)
1519 return 0
1520
1521# PC XT scancodes
1522scancodes = {
1523 'a': 0x1e,
1524 'b': 0x30,
1525 'c': 0x2e,
1526 'd': 0x20,
1527 'e': 0x12,
1528 'f': 0x21,
1529 'g': 0x22,
1530 'h': 0x23,
1531 'i': 0x17,
1532 'j': 0x24,
1533 'k': 0x25,
1534 'l': 0x26,
1535 'm': 0x32,
1536 'n': 0x31,
1537 'o': 0x18,
1538 'p': 0x19,
1539 'q': 0x10,
1540 'r': 0x13,
1541 's': 0x1f,
1542 't': 0x14,
1543 'u': 0x16,
1544 'v': 0x2f,
1545 'w': 0x11,
1546 'x': 0x2d,
1547 'y': 0x15,
1548 'z': 0x2c,
1549 '0': 0x0b,
1550 '1': 0x02,
1551 '2': 0x03,
1552 '3': 0x04,
1553 '4': 0x05,
1554 '5': 0x06,
1555 '6': 0x07,
1556 '7': 0x08,
1557 '8': 0x09,
1558 '9': 0x0a,
1559 ' ': 0x39,
1560 '-': 0xc,
1561 '=': 0xd,
1562 '[': 0x1a,
1563 ']': 0x1b,
1564 ';': 0x27,
1565 '\'': 0x28,
1566 ',': 0x33,
1567 '.': 0x34,
1568 '/': 0x35,
1569 '\t': 0xf,
1570 '\n': 0x1c,
1571 '`': 0x29
1572};
1573
1574extScancodes = {
1575 'ESC' : [0x01],
1576 'BKSP': [0xe],
1577 'SPACE': [0x39],
1578 'TAB': [0x0f],
1579 'CAPS': [0x3a],
1580 'ENTER': [0x1c],
1581 'LSHIFT': [0x2a],
1582 'RSHIFT': [0x36],
1583 'INS': [0xe0, 0x52],
1584 'DEL': [0xe0, 0x53],
1585 'END': [0xe0, 0x4f],
1586 'HOME': [0xe0, 0x47],
1587 'PGUP': [0xe0, 0x49],
1588 'PGDOWN': [0xe0, 0x51],
1589 'LGUI': [0xe0, 0x5b], # GUI, aka Win, aka Apple key
1590 'RGUI': [0xe0, 0x5c],
1591 'LCTR': [0x1d],
1592 'RCTR': [0xe0, 0x1d],
1593 'LALT': [0x38],
1594 'RALT': [0xe0, 0x38],
1595 'APPS': [0xe0, 0x5d],
1596 'F1': [0x3b],
1597 'F2': [0x3c],
1598 'F3': [0x3d],
1599 'F4': [0x3e],
1600 'F5': [0x3f],
1601 'F6': [0x40],
1602 'F7': [0x41],
1603 'F8': [0x42],
1604 'F9': [0x43],
1605 'F10': [0x44 ],
1606 'F11': [0x57],
1607 'F12': [0x58],
1608 'UP': [0xe0, 0x48],
1609 'LEFT': [0xe0, 0x4b],
1610 'DOWN': [0xe0, 0x50],
1611 'RIGHT': [0xe0, 0x4d],
1612};
1613
1614def keyDown(ch):
1615 code = scancodes.get(ch, 0x0)
1616 if code != 0:
1617 return [code]
1618 extCode = extScancodes.get(ch, [])
1619 if len(extCode) == 0:
1620 print "bad ext",ch
1621 return extCode
1622
1623def keyUp(ch):
1624 codes = keyDown(ch)[:] # make a copy
1625 if len(codes) > 0:
1626 codes[len(codes)-1] += 0x80
1627 return codes
1628
1629def typeInGuest(console, text, delay):
1630 import time
1631 pressed = []
1632 group = False
1633 modGroupEnd = True
1634 i = 0
1635 while i < len(text):
1636 ch = text[i]
1637 i = i+1
1638 if ch == '{':
1639 # start group, all keys to be pressed at the same time
1640 group = True
1641 continue
1642 if ch == '}':
1643 # end group, release all keys
1644 for c in pressed:
1645 console.keyboard.putScancodes(keyUp(c))
1646 pressed = []
1647 group = False
1648 continue
1649 if ch == 'W':
1650 # just wait a bit
1651 time.sleep(0.3)
1652 continue
1653 if ch == '^' or ch == '|' or ch == '$' or ch == '_':
1654 if ch == '^':
1655 ch = 'LCTR'
1656 if ch == '|':
1657 ch = 'LSHIFT'
1658 if ch == '_':
1659 ch = 'LALT'
1660 if ch == '$':
1661 ch = 'LGUI'
1662 if not group:
1663 modGroupEnd = False
1664 else:
1665 if ch == '\\':
1666 if i < len(text):
1667 ch = text[i]
1668 i = i+1
1669 if ch == 'n':
1670 ch = '\n'
1671 elif ch == '&':
1672 combo = ""
1673 while i < len(text):
1674 ch = text[i]
1675 i = i+1
1676 if ch == ';':
1677 break
1678 combo += ch
1679 ch = combo
1680 modGroupEnd = True
1681 console.keyboard.putScancodes(keyDown(ch))
1682 pressed.insert(0, ch)
1683 if not group and modGroupEnd:
1684 for c in pressed:
1685 console.keyboard.putScancodes(keyUp(c))
1686 pressed = []
1687 modGroupEnd = True
1688 time.sleep(delay)
1689
1690def typeGuestCmd(ctx, args):
1691 import sys
1692
1693 if len(args) < 3:
1694 print "usage: typeGuest <machine> <text> <charDelay>"
1695 return 0
1696 mach = argsToMach(ctx,args)
1697 if mach is None:
1698 return 0
1699
1700 text = args[2]
1701
1702 if len(args) > 3:
1703 delay = float(args[3])
1704 else:
1705 delay = 0.1
1706
1707 gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
1708 cmdExistingVm(ctx, mach, 'guestlambda', gargs)
1709
1710 return 0
1711
1712def optId(verbose,id):
1713 if verbose:
1714 return ": "+id
1715 else:
1716 return ""
1717
1718def asSize(val,inBytes):
1719 if inBytes:
1720 return int(val)/(1024*1024)
1721 else:
1722 return int(val)
1723
1724def listMediaCmd(ctx,args):
1725 if len(args) > 1:
1726 verbose = int(args[1])
1727 else:
1728 verbose = False
1729 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
1730 print colCat(ctx,"Hard disks:")
1731 for hdd in hdds:
1732 if hdd.state != ctx['global'].constants.MediumState_Created:
1733 hdd.refreshState()
1734 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)))
1735
1736 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
1737 print colCat(ctx,"CD/DVD disks:")
1738 for dvd in dvds:
1739 if dvd.state != ctx['global'].constants.MediumState_Created:
1740 dvd.refreshState()
1741 print " %s (%s)%s %s" %(colPath(ctx,dvd.location), dvd.format,optId(verbose,dvd.id),colSizeM(ctx,asSize(dvd.size, True)))
1742
1743 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
1744 print colCat(ctx,"Floppy disks:")
1745 for floppy in floppys:
1746 if floppy.state != ctx['global'].constants.MediumState_Created:
1747 floppy.refreshState()
1748 print " %s (%s)%s %s" %(colPath(ctx,floppy.location), floppy.format,optId(verbose,floppy.id), colSizeM(ctx,asSize(floppy.size, True)))
1749
1750 return 0
1751
1752def listUsbCmd(ctx,args):
1753 if (len(args) > 1):
1754 print "usage: listUsb"
1755 return 0
1756
1757 host = ctx['vb'].host
1758 for ud in ctx['global'].getArray(host, 'USBDevices'):
1759 printHostUsbDev(ctx,ud)
1760
1761 return 0
1762
1763def findDevOfType(ctx,mach,type):
1764 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1765 for a in atts:
1766 if a.type == type:
1767 return [a.controller, a.port, a.device]
1768 return [None, 0, 0]
1769
1770def createHddCmd(ctx,args):
1771 if (len(args) < 3):
1772 print "usage: createHdd sizeM location type"
1773 return 0
1774
1775 size = int(args[1])
1776 loc = args[2]
1777 if len(args) > 3:
1778 format = args[3]
1779 else:
1780 format = "vdi"
1781
1782 hdd = ctx['vb'].createHardDisk(format, loc)
1783 progress = hdd.createBaseStorage(size, ctx['global'].constants.MediumVariant_Standard)
1784 if progressBar(ctx,progress) and hdd.id:
1785 print "created HDD at %s as %s" %(hdd.location, hdd.id)
1786 else:
1787 print "cannot create disk (file %s exist?)" %(loc)
1788 reportError(ctx,progress)
1789 return 0
1790
1791 return 0
1792
1793def registerHddCmd(ctx,args):
1794 if (len(args) < 2):
1795 print "usage: registerHdd location"
1796 return 0
1797
1798 vb = ctx['vb']
1799 loc = args[1]
1800 setImageId = False
1801 imageId = ""
1802 setParentId = False
1803 parentId = ""
1804 hdd = vb.openHardDisk(loc, ctx['global'].constants.AccessMode_ReadWrite, setImageId, imageId, setParentId, parentId)
1805 print "registered HDD as %s" %(hdd.id)
1806 return 0
1807
1808def controldevice(ctx,mach,args):
1809 [ctr,port,slot,type,id] = args
1810 mach.attachDevice(ctr, port, slot,type,id)
1811
1812def attachHddCmd(ctx,args):
1813 if (len(args) < 3):
1814 print "usage: attachHdd vm hdd controller port:slot"
1815 return 0
1816
1817 mach = argsToMach(ctx,args)
1818 if mach is None:
1819 return 0
1820 vb = ctx['vb']
1821 loc = args[2]
1822 try:
1823 hdd = vb.findHardDisk(loc)
1824 except:
1825 print "no HDD with path %s registered" %(loc)
1826 return 0
1827 if len(args) > 3:
1828 ctr = args[3]
1829 (port,slot) = args[4].split(":")
1830 else:
1831 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
1832
1833 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
1834 return 0
1835
1836def detachVmDevice(ctx,mach,args):
1837 atts = ctx['global'].getArray(mach, 'mediumAttachments')
1838 hid = args[0]
1839 for a in atts:
1840 if a.medium:
1841 if hid == "ALL" or a.medium.id == hid:
1842 mach.detachDevice(a.controller, a.port, a.device)
1843
1844def detachMedium(ctx,mid,medium):
1845 cmdClosedVm(ctx, mach, detachVmDevice, [medium.id])
1846
1847def detachHddCmd(ctx,args):
1848 if (len(args) < 3):
1849 print "usage: detachHdd vm hdd"
1850 return 0
1851
1852 mach = argsToMach(ctx,args)
1853 if mach is None:
1854 return 0
1855 vb = ctx['vb']
1856 loc = args[2]
1857 try:
1858 hdd = vb.findHardDisk(loc)
1859 except:
1860 print "no HDD with path %s registered" %(loc)
1861 return 0
1862
1863 detachMedium(ctx,mach.id,hdd)
1864 return 0
1865
1866def unregisterHddCmd(ctx,args):
1867 if (len(args) < 2):
1868 print "usage: unregisterHdd path <vmunreg>"
1869 return 0
1870
1871 vb = ctx['vb']
1872 loc = args[1]
1873 if (len(args) > 2):
1874 vmunreg = int(args[2])
1875 else:
1876 vmunreg = 0
1877 try:
1878 hdd = vb.findHardDisk(loc)
1879 except:
1880 print "no HDD with path %s registered" %(loc)
1881 return 0
1882
1883 if vmunreg != 0:
1884 machs = ctx['global'].getArray(hdd, 'machineIds')
1885 try:
1886 for m in machs:
1887 print "Trying to detach from %s" %(m)
1888 detachMedium(ctx,m,hdd)
1889 except Exception, e:
1890 print 'failed: ',e
1891 return 0
1892 hdd.close()
1893 return 0
1894
1895def removeHddCmd(ctx,args):
1896 if (len(args) != 2):
1897 print "usage: removeHdd path"
1898 return 0
1899
1900 vb = ctx['vb']
1901 loc = args[1]
1902 try:
1903 hdd = vb.findHardDisk(loc)
1904 except:
1905 print "no HDD with path %s registered" %(loc)
1906 return 0
1907
1908 progress = hdd.deleteStorage()
1909 progressBar(ctx,progress)
1910
1911 return 0
1912
1913def registerIsoCmd(ctx,args):
1914 if (len(args) < 2):
1915 print "usage: registerIso location"
1916 return 0
1917 vb = ctx['vb']
1918 loc = args[1]
1919 id = ""
1920 iso = vb.openDVDImage(loc, id)
1921 print "registered ISO as %s" %(iso.id)
1922 return 0
1923
1924def unregisterIsoCmd(ctx,args):
1925 if (len(args) != 2):
1926 print "usage: unregisterIso path"
1927 return 0
1928
1929 vb = ctx['vb']
1930 loc = args[1]
1931 try:
1932 dvd = vb.findDVDImage(loc)
1933 except:
1934 print "no DVD with path %s registered" %(loc)
1935 return 0
1936
1937 progress = dvd.close()
1938 print "Unregistered ISO at %s" %(dvd.location)
1939
1940 return 0
1941
1942def removeIsoCmd(ctx,args):
1943 if (len(args) != 2):
1944 print "usage: removeIso path"
1945 return 0
1946
1947 vb = ctx['vb']
1948 loc = args[1]
1949 try:
1950 dvd = vb.findDVDImage(loc)
1951 except:
1952 print "no DVD with path %s registered" %(loc)
1953 return 0
1954
1955 progress = dvd.deleteStorage()
1956 if progressBar(ctx,progress):
1957 print "Removed ISO at %s" %(dvd.location)
1958 else:
1959 reportError(ctx,progress)
1960 return 0
1961
1962def attachIsoCmd(ctx,args):
1963 if (len(args) < 3):
1964 print "usage: attachIso vm iso controller port:slot"
1965 return 0
1966
1967 mach = argsToMach(ctx,args)
1968 if mach is None:
1969 return 0
1970 vb = ctx['vb']
1971 loc = args[2]
1972 try:
1973 dvd = vb.findDVDImage(loc)
1974 except:
1975 print "no DVD with path %s registered" %(loc)
1976 return 0
1977 if len(args) > 3:
1978 ctr = args[3]
1979 (port,slot) = args[4].split(":")
1980 else:
1981 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
1982 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD,dvd.id))
1983 return 0
1984
1985def detachIsoCmd(ctx,args):
1986 if (len(args) < 3):
1987 print "usage: detachIso vm iso"
1988 return 0
1989
1990 mach = argsToMach(ctx,args)
1991 if mach is None:
1992 return 0
1993 vb = ctx['vb']
1994 loc = args[2]
1995 try:
1996 dvd = vb.findDVDImage(loc)
1997 except:
1998 print "no DVD with path %s registered" %(loc)
1999 return 0
2000
2001 detachMedium(ctx,mach.id,dvd)
2002 return 0
2003
2004def mountIsoCmd(ctx,args):
2005 if (len(args) < 3):
2006 print "usage: mountIso vm iso controller port:slot"
2007 return 0
2008
2009 mach = argsToMach(ctx,args)
2010 if mach is None:
2011 return 0
2012 vb = ctx['vb']
2013 loc = args[2]
2014 try:
2015 dvd = vb.findDVDImage(loc)
2016 except:
2017 print "no DVD with path %s registered" %(loc)
2018 return 0
2019
2020 if len(args) > 3:
2021 ctr = args[3]
2022 (port,slot) = args[4].split(":")
2023 else:
2024 # autodetect controller and location, just find first controller with media == DVD
2025 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
2026
2027 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd.id, True])
2028
2029 return 0
2030
2031def unmountIsoCmd(ctx,args):
2032 if (len(args) < 2):
2033 print "usage: unmountIso vm controller port:slot"
2034 return 0
2035
2036 mach = argsToMach(ctx,args)
2037 if mach is None:
2038 return 0
2039 vb = ctx['vb']
2040
2041 if len(args) > 2:
2042 ctr = args[2]
2043 (port,slot) = args[3].split(":")
2044 else:
2045 # autodetect controller and location, just find first controller with media == DVD
2046 [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
2047
2048 cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, "", True])
2049
2050 return 0
2051
2052def attachCtr(ctx,mach,args):
2053 [name, bus, type] = args
2054 ctr = mach.addStorageController(name, bus)
2055 if type != None:
2056 ctr.controllerType = type
2057
2058def attachCtrCmd(ctx,args):
2059 if (len(args) < 4):
2060 print "usage: attachCtr vm cname bus <type>"
2061 return 0
2062
2063 if len(args) > 4:
2064 type = enumFromString(ctx,'StorageControllerType', args[4])
2065 if type == None:
2066 print "Controller type %s unknown" %(args[4])
2067 return 0
2068 else:
2069 type = None
2070
2071 mach = argsToMach(ctx,args)
2072 if mach is None:
2073 return 0
2074 bus = enumFromString(ctx,'StorageBus', args[3])
2075 if bus is None:
2076 print "Bus type %s unknown" %(args[3])
2077 return 0
2078 name = args[2]
2079 cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
2080 return 0
2081
2082def detachCtrCmd(ctx,args):
2083 if (len(args) < 3):
2084 print "usage: detachCtr vm name"
2085 return 0
2086
2087 mach = argsToMach(ctx,args)
2088 if mach is None:
2089 return 0
2090 ctr = args[2]
2091 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
2092 return 0
2093
2094def usbctr(ctx,mach,console,args):
2095 if (args[0]):
2096 console.attachUSBDevice(args[1])
2097 else:
2098 console.detachUSBDevice(args[1])
2099
2100def attachUsbCmd(ctx,args):
2101 if (len(args) < 3):
2102 print "usage: attachUsb vm deviceuid"
2103 return 0
2104
2105 mach = argsToMach(ctx,args)
2106 if mach is None:
2107 return 0
2108 dev = args[2]
2109 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
2110 return 0
2111
2112def detachUsbCmd(ctx,args):
2113 if (len(args) < 3):
2114 print "usage: detachUsb vm deviceuid"
2115 return 0
2116
2117 mach = argsToMach(ctx,args)
2118 if mach is None:
2119 return 0
2120 dev = args[2]
2121 cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
2122 return 0
2123
2124
2125def guiCmd(ctx,args):
2126 if (len(args) > 1):
2127 print "usage: gui"
2128 return 0
2129
2130 binDir = ctx['global'].getBinDir()
2131
2132 vbox = os.path.join(binDir, 'VirtualBox')
2133 try:
2134 os.system(vbox)
2135 except KeyboardInterrupt:
2136 # to allow interruption
2137 pass
2138 return 0
2139
2140def shareFolderCmd(ctx,args):
2141 if (len(args) < 4):
2142 print "usage: shareFolder vm path name <writable> <persistent>"
2143 return 0
2144
2145 mach = argsToMach(ctx,args)
2146 if mach is None:
2147 return 0
2148 path = args[2]
2149 name = args[3]
2150 writable = False
2151 persistent = False
2152 if len(args) > 4:
2153 for a in args[4:]:
2154 if a == 'writable':
2155 writable = True
2156 if a == 'persistent':
2157 persistent = True
2158 if persistent:
2159 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.createSharedFolder(name, path, writable), [])
2160 else:
2161 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.createSharedFolder(name, path, writable)])
2162 return 0
2163
2164def unshareFolderCmd(ctx,args):
2165 if (len(args) < 3):
2166 print "usage: unshareFolder vm name"
2167 return 0
2168
2169 mach = argsToMach(ctx,args)
2170 if mach is None:
2171 return 0
2172 name = args[2]
2173 found = False
2174 for sf in ctx['global'].getArray(mach, 'sharedFolders'):
2175 if sf.name == name:
2176 cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeSharedFolder(name), [])
2177 found = True
2178 break
2179 if not found:
2180 cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.removeSharedFolder(name)])
2181 return 0
2182
2183
2184def snapshotCmd(ctx,args):
2185 if (len(args) < 2 or args[1] == 'help'):
2186 print "Take snapshot: snapshot vm take name <description>"
2187 print "Restore snapshot: snapshot vm restore name"
2188 print "Merge snapshot: snapshot vm merge name"
2189 return 0
2190
2191 mach = argsToMach(ctx,args)
2192 if mach is None:
2193 return 0
2194 cmd = args[2]
2195 if cmd == 'take':
2196 if (len(args) < 4):
2197 print "usage: snapshot vm take name <description>"
2198 return 0
2199 name = args[3]
2200 if (len(args) > 4):
2201 desc = args[4]
2202 else:
2203 desc = ""
2204 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.takeSnapshot(name,desc)))
2205
2206 if cmd == 'restore':
2207 if (len(args) < 4):
2208 print "usage: snapshot vm restore name"
2209 return 0
2210 name = args[3]
2211 snap = mach.findSnapshot(name)
2212 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
2213 return 0
2214
2215 if cmd == 'restorecurrent':
2216 if (len(args) < 4):
2217 print "usage: snapshot vm restorecurrent"
2218 return 0
2219 snap = mach.currentSnapshot()
2220 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
2221 return 0
2222
2223 if cmd == 'delete':
2224 if (len(args) < 4):
2225 print "usage: snapshot vm delete name"
2226 return 0
2227 name = args[3]
2228 snap = mach.findSnapshot(name)
2229 cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.deleteSnapshot(snap.id)))
2230 return 0
2231
2232 print "Command '%s' is unknown" %(cmd)
2233
2234 return 0
2235
2236def natAlias(ctx, mach, nicnum, nat, args=[]):
2237 """This command shows/alters NAT's alias settings.
2238 usage: nat <vm> <nicnum> alias [default|[log] [proxyonly] [sameports]]
2239 default - set settings to default values
2240 log - switch on alias loging
2241 proxyonly - switch proxyonly mode on
2242 sameports - enforces NAT using the same ports
2243 """
2244 alias = {
2245 'log': 0x1,
2246 'proxyonly': 0x2,
2247 'sameports': 0x4
2248 }
2249 if len(args) == 1:
2250 first = 0
2251 msg = ''
2252 for aliasmode, aliaskey in alias.iteritems():
2253 if first == 0:
2254 first = 1
2255 else:
2256 msg += ', '
2257 if int(nat.aliasMode) & aliaskey:
2258 msg += '{0}: {1}'.format(aliasmode, 'on')
2259 else:
2260 msg += '{0}: {1}'.format(aliasmode, 'off')
2261 msg += ')'
2262 return (0, [msg])
2263 else:
2264 nat.aliasMode = 0
2265 if 'default' not in args:
2266 for a in range(1, len(args)):
2267 if not alias.has_key(args[a]):
2268 print 'Invalid alias mode: ' + args[a]
2269 print natAlias.__doc__
2270 return (1, None)
2271 nat.aliasMode = int(nat.aliasMode) | alias[args[a]];
2272 return (0, None)
2273
2274def natSettings(ctx, mach, nicnum, nat, args):
2275 """This command shows/alters NAT settings.
2276 usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
2277 mtu - set mtu <= 16000
2278 socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
2279 tcpsndwnd/tcprcvwnd - sets size of initial tcp sending/receiving window
2280 """
2281 if len(args) == 1:
2282 (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings();
2283 if mtu == 0: mtu = 1500
2284 if socksndbuf == 0: socksndbuf = 64
2285 if sockrcvbuf == 0: sockrcvbuf = 64
2286 if tcpsndwnd == 0: tcpsndwnd = 64
2287 if tcprcvwnd == 0: tcprcvwnd = 64
2288 msg = 'mtu:{0} socket(snd:{1}, rcv:{2}) tcpwnd(snd:{3}, rcv:{4})'.format(mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd);
2289 return (0, [msg])
2290 else:
2291 if args[1] < 16000:
2292 print 'invalid mtu value ({0} no in range [65 - 16000])'.format(args[1])
2293 return (1, None)
2294 for i in range(2, len(args)):
2295 if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024:
2296 print 'invalid {0} parameter ({1} not in range [8-1024])'.format(i, args[i])
2297 return (1, None)
2298 a = [args[1]]
2299 if len(args) < 6:
2300 for i in range(2, len(args)): a.append(args[i])
2301 for i in range(len(args), 6): a.append(0)
2302 else:
2303 for i in range(2, len(args)): a.append(args[i])
2304 #print a
2305 nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))
2306 return (0, None)
2307
2308def natDns(ctx, mach, nicnum, nat, args):
2309 """This command shows/alters DNS's NAT settings
2310 usage: nat <vm> <nicnum> dns [passdomain] [proxy] [usehostresolver]
2311 passdomain - enforces builtin DHCP server to pass domain
2312 proxy - switch on builtin NAT DNS proxying mechanism
2313 usehostresolver - proxies all DNS requests to Host Resolver interface
2314 """
2315 yesno = {0: 'off', 1: 'on'}
2316 if len(args) == 1:
2317 msg = 'passdomain:{0}, proxy:{1}, usehostresolver:{2}'.format(yesno[int(nat.dnsPassDomain)], yesno[int(nat.dnsProxy)], yesno[int(nat.dnsUseHostResolver)])
2318 return (0, [msg])
2319 else:
2320 nat.dnsPassDomain = 'passdomain' in args
2321 nat.dnsProxy = 'proxy' in args
2322 nat.dnsUseHostResolver = 'usehostresolver' in args
2323 return (0, None)
2324
2325def natTftp(ctx, mach, nicnum, nat, args):
2326 """This command shows/alters TFTP settings
2327 usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
2328 prefix - alters prefix TFTP settings
2329 bootfile - alters bootfile TFTP settings
2330 server - sets booting server
2331 """
2332 if len(args) == 1:
2333 server = nat.tftpNextServer
2334 if server is None:
2335 server = nat.network
2336 if server is None:
2337 server = '10.0.{0}/24'.format(int(nicnum) + 2)
2338 (server,mask) = server.split('/')
2339 while server.count('.') != 3:
2340 server += '.0'
2341 (a,b,c,d) = server.split('.')
2342 server = '{0}.{1}.{2}.4'.format(a,b,c)
2343 prefix = nat.tftpPrefix
2344 if prefix is None:
2345 prefix = '{0}/TFTP/'.format(ctx['vb'].homeFolder)
2346 bootfile = nat.tftpBootFile
2347 if bootfile is None:
2348 bootfile = '{0}.pxe'.format(mach.name)
2349 msg = 'server:{0}, prefix:{1}, bootfile:{2}'.format(server, prefix, bootfile)
2350 return (0, [msg])
2351 else:
2352
2353 cmd = args[1]
2354 if len(args) != 3:
2355 print 'invalid args:', args
2356 print natTftp.__doc__
2357 return (1, None)
2358 if cmd == 'prefix': nat.tftpPrefix = args[2]
2359 elif cmd == 'bootfile': nat.tftpBootFile = args[2]
2360 elif cmd == 'server': nat.tftpNextServer = args[2]
2361 else:
2362 print "invalid cmd:", cmd
2363 return (1, None)
2364 return (0, None)
2365
2366def natPortForwarding(ctx, mach, nicnum, nat, args):
2367 """This command shows/manages port-forwarding settings
2368 usage:
2369 nat <vm> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
2370 |[no_name tcp|udp <hostip> <hostport> <guestip> <guestport>]
2371 |[ex tcp|udp <pf-name> <hostip> <hostport> <guestip> <guestport>]
2372 |[delete <pf-name>]
2373 """
2374 if len(args) == 1:
2375 # note: keys/values are swapped in defining part of the function
2376 proto = {0: 'udp', 1: 'tcp'}
2377 msg = []
2378 pfs = ctx['global'].getArray(nat, 'redirects')
2379 for pf in pfs:
2380 (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(',')
2381 msg.append('{0}: {1} {2}:{3} => {4}:{5}'.format(pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
2382 return (0, msg) # msg is array
2383 else:
2384 proto = {'udp': 0, 'tcp': 1}
2385 pfcmd = {
2386 'simple': {
2387 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 5,
2388 'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4]))
2389 },
2390 'no_name': {
2391 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 7,
2392 'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6]))
2393 },
2394 'ex': {
2395 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 8,
2396 'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7]))
2397 },
2398 'delete': {
2399 'validate': lambda: len(args) == 3,
2400 'func': lambda: nat.removeRedirect(args[2])
2401 }
2402 }
2403
2404 if not pfcmd[args[1]]['validate']():
2405 print 'invalid port-forwarding or args of sub command ', args[1]
2406 print natPortForwarding.__doc__
2407 return (1, None)
2408
2409 a = pfcmd[args[1]]['func']()
2410 return (0, None)
2411
2412def natNetwork(ctx, mach, nicnum, nat, args):
2413 """This command shows/alters NAT network settings
2414 usage: nat <vm> <nicnum> network [<network>]
2415 """
2416 if len(args) == 1:
2417 if nat.network is not None and len(str(nat.network)) != 0:
2418 msg = '\'%s\'' % (nat.network)
2419 else:
2420 msg = '10.0.{0}.0/24'.format(int(nicnum) + 2)
2421 return (0, [msg])
2422 else:
2423 (addr, mask) = args[1].split('/')
2424 if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
2425 print 'Invalid arguments'
2426 return (1, None)
2427 nat.network = args[1]
2428 return (0, None)
2429def natCmd(ctx, args):
2430 """This command is entry point to NAT settins management
2431 usage: nat <vm> <nicnum> <cmd> <cmd-args>
2432 cmd - [alias|settings|tftp|dns|pf|network]
2433 for more information about commands:
2434 nat help <cmd>
2435 """
2436
2437 natcommands = {
2438 'alias' : natAlias,
2439 'settings' : natSettings,
2440 'tftp': natTftp,
2441 'dns': natDns,
2442 'pf': natPortForwarding,
2443 'network': natNetwork
2444 }
2445
2446 if len(args) < 2 or args[1] == 'help':
2447 if len(args) > 2:
2448 print natcommands[args[2]].__doc__
2449 else:
2450 print natCmd.__doc__
2451 return 0
2452 if len(args) == 1 or len(args) < 4 or args[3] not in natcommands:
2453 print natCmd.__doc__
2454 return 0
2455 mach = ctx['argsToMach'](args)
2456 if mach == None:
2457 print "please specify vm"
2458 return 0
2459 if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
2460 print 'please specify adapter num {0} isn\'t in range [0-{1}]'.format(args[2], ctx['vb'].systemProperties.networkAdapterCount)
2461 return 0
2462 nicnum = int(args[2])
2463 cmdargs = []
2464 for i in range(3, len(args)):
2465 cmdargs.append(args[i])
2466
2467 # @todo vvl if nicnum is missed but command is entered
2468 # use NAT func for every adapter on machine.
2469 func = args[3]
2470 rosession = 1
2471 session = None
2472 if len(cmdargs) > 1:
2473 rosession = 0
2474 session = ctx['global'].openMachineSession(mach.id);
2475 mach = session.machine;
2476
2477 adapter = mach.getNetworkAdapter(nicnum)
2478 natEngine = adapter.natDriver
2479 (rc, report) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
2480 if rosession == 0:
2481 if rc == 0:
2482 mach.saveSettings()
2483 session.close()
2484 elif report is not None:
2485 for r in report:
2486 msg ='{0} nic{1} {2}: {3}'.format(mach.name, nicnum, func, r)
2487 print msg
2488 return 0
2489
2490def nicSwitchOnOff(adapter, attr, args):
2491 if len(args) == 1:
2492 yesno = {0: 'off', 1: 'on'}
2493 r = yesno[int(adapter.__getattr__(attr))]
2494 return (0, r)
2495 else:
2496 yesno = {'off' : 0, 'on' : 1}
2497 if args[1] not in yesno:
2498 print '%s isn\'t acceptable, please choose %s' % (args[1], yesno.keys())
2499 return (1, None)
2500 adapter.__setattr__(attr, yesno[args[1]])
2501 return (0, None)
2502
2503def nicTraceSubCmd(ctx, vm, nicnum, adapter, args):
2504 '''
2505 usage: nic <vm> <nicnum> trace [on|off [file]]
2506 '''
2507 (rc, r) = nicSwitchOnOff(adapter, 'traceEnabled', args)
2508 if len(args) == 1 and rc == 0:
2509 r = '%s file:%s' % (r, adapter.traceFile)
2510 return (0, r)
2511 elif len(args) == 3 and rc == 0:
2512 adapter.traceFile = args[2]
2513 return (0, None)
2514
2515def nicLineSpeedSubCmd(ctx, vm, nicnum, adapter, args):
2516 if len(args) == 1:
2517 r = '%d kbps'%(adapter.lineSpeed)
2518 return (0, r)
2519 else:
2520 if not args[1].isdigit():
2521 print '%s isn\'t a number'.format(args[1])
2522 print (1, None)
2523 adapter.lineSpeed = int(args[1])
2524 return (0, None)
2525
2526def nicCableSubCmd(ctx, vm, nicnum, adapter, args):
2527 '''
2528 usage: nic <vm> <nicnum> cable [on|off]
2529 '''
2530 return nicSwitchOnOff(adapter, 'cableConnected', args)
2531
2532def nicEnableSubCmd(ctx, vm, nicnum, adapter, args):
2533 '''
2534 usage: nic <vm> <nicnum> enable [on|off]
2535 '''
2536 return nicSwitchOnOff(adapter, 'enabled', args)
2537
2538def nicTypeSubCmd(ctx, vm, nicnum, adapter, args):
2539 '''
2540 usage: nic <vm> <nicnum> type [Am79c970A|Am79c970A|I82540EM|I82545EM|I82543GC|Virtio]
2541 '''
2542 if len(args) == 1:
2543 nictypes = ctx['ifaces'].all_values('NetworkAdapterType')
2544 for n in nictypes.keys():
2545 if str(adapter.adapterType) == str(nictypes[n]):
2546 return (0, str(n))
2547 return (1, None)
2548 else:
2549 nictypes = ctx['ifaces'].all_values('NetworkAdapterType')
2550 if args[1] not in nictypes.keys():
2551 print '%s not in acceptable values (%s)' % (args[1], nictypes.keys())
2552 return (1, None)
2553 adapter.adapterType = nictypes[args[1]]
2554 return (0, None)
2555
2556def nicAttachmentSubCmd(ctx, vm, nicnum, adapter, args):
2557 '''
2558 usage: nic <vm> <nicnum> attachment [Null|NAT|Bridged <interface>|Internal <name>|HostOnly <interface>]
2559 '''
2560 if len(args) == 1:
2561 nicAttachmentType = {
2562 ctx['global'].constants.NetworkAttachmentType_Null: ('Null', ''),
2563 ctx['global'].constants.NetworkAttachmentType_NAT: ('NAT', ''),
2564 ctx['global'].constants.NetworkAttachmentType_Bridged: ('Bridged', adapter.hostInterface),
2565 ctx['global'].constants.NetworkAttachmentType_Internal: ('Internal', adapter.internalNetwork),
2566 ctx['global'].constants.NetworkAttachmentType_HostOnly: ('HostOnly', adapter.hostInterface),
2567 #ctx['global'].constants.NetworkAttachmentType_VDE: ('VDE', adapter.VDENetwork)
2568 }
2569 import types
2570 if type(adapter.attachmentType) != types.IntType:
2571 t = str(adapter.attachmentType)
2572 else:
2573 t = adapter.attachmentType
2574 (r, p) = nicAttachmentType[t]
2575 return (0, 'attachment:{0}, name:{1}'.format(r, p))
2576 else:
2577 nicAttachmentType = {
2578 'Null': {
2579 'v': lambda: len(args) == 2,
2580 'p': lambda: 'do nothing',
2581 'f': lambda: adapter.detach()},
2582 'NAT': {
2583 'v': lambda: len(args) == 2,
2584 'p': lambda: 'do nothing',
2585 'f': lambda: adapter.attachToNAT()},
2586 'Bridged': {
2587 'v': lambda: len(args) == 3,
2588 'p': lambda: adapter.__setattr__('hostInterface', args[2]),
2589 'f': lambda: adapter.attachToBridgedInterface()},
2590 'Internal': {
2591 'v': lambda: len(args) == 3,
2592 'p': lambda: adapter.__setattr__('internalNetwork', args[2]),
2593 'f': lambda: adapter.attachToInternalNetwork()},
2594 'HostOnly': {
2595 'v': lambda: len(args) == 2,
2596 'p': lambda: adapter.__setattr__('hostInterface', args[2]),
2597 'f': lambda: adapter.attachToHostOnlyInterface()},
2598 'VDE': {
2599 'v': lambda: len(args) == 3,
2600 'p': lambda: adapter.__setattr__('VDENetwork', args[2]),
2601 'f': lambda: adapter.attachToVDE()}
2602 }
2603 if args[1] not in nicAttachmentType.keys():
2604 print '{0} not in acceptable values ({1})'.format(args[1], nicAttachmentType.keys())
2605 return (1, None)
2606 if not nicAttachmentType[args[1]]['v']():
2607 print nicAttachmentType.__doc__
2608 return (1, None)
2609 nicAttachmentType[args[1]]['p']()
2610 nicAttachmentType[args[1]]['f']()
2611 return (0, None)
2612
2613def nicCmd(ctx, args):
2614 '''
2615 This command to manage network adapters
2616 usage: nic <vm> <nicnum> <cmd> <cmd-args>
2617 where cmd : attachment, trace, linespeed, cable, enable, type
2618 '''
2619 # 'command name':{'runtime': is_callable_at_runtime, 'op': function_name}
2620 niccomand = {
2621 'attachment': nicAttachmentSubCmd,
2622 'trace': nicTraceSubCmd,
2623 'linespeed': nicLineSpeedSubCmd,
2624 'cable': nicCableSubCmd,
2625 'enable': nicEnableSubCmd,
2626 'type': nicTypeSubCmd
2627 }
2628 if len(args) < 2 \
2629 or args[1] == 'help' \
2630 or (len(args) > 2 and args[3] not in niccomand):
2631 if len(args) == 3 \
2632 and args[2] in niccomand:
2633 print niccomand[args[2]].__doc__
2634 else:
2635 print nicCmd.__doc__
2636 return 0
2637
2638 vm = ctx['argsToMach'](args)
2639 if vm is None:
2640 print 'please specify vm'
2641 return 0
2642
2643 if len(args) < 3 \
2644 or not args[2].isdigit() \
2645 or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
2646 print 'please specify adapter num %d isn\'t in range [0-%d]'%(args[2], ctx['vb'].systemProperties.networkAdapterCount)
2647 return 0
2648 nicnum = int(args[2])
2649 cmdargs = args[3:]
2650 func = args[3]
2651 session = None
2652 session = ctx['global'].openMachineSession(vm.id)
2653 vm = session.machine
2654 adapter = vm.getNetworkAdapter(nicnum)
2655 (rc, report) = niccomand[func](ctx, vm, nicnum, adapter, cmdargs)
2656 if rc == 0:
2657 vm.saveSettings()
2658 if report is not None:
2659 print '%s nic %d %s: %s' % (vm.name, nicnum, args[3], report)
2660 session.close()
2661 return 0
2662
2663
2664def promptCmd(ctx, args):
2665 if len(args) < 2:
2666 print "Current prompt: '%s'" %(ctx['prompt'])
2667 return 0
2668
2669 ctx['prompt'] = args[1]
2670 return 0
2671
2672
2673aliases = {'s':'start',
2674 'i':'info',
2675 'l':'list',
2676 'h':'help',
2677 'a':'alias',
2678 'q':'quit', 'exit':'quit',
2679 'tg': 'typeGuest',
2680 'v':'verbose'}
2681
2682commands = {'help':['Prints help information', helpCmd, 0],
2683 'start':['Start virtual machine by name or uuid: start Linux', startCmd, 0],
2684 'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
2685 'removeVm':['Remove virtual machine', removeVmCmd, 0],
2686 'pause':['Pause virtual machine', pauseCmd, 0],
2687 'resume':['Resume virtual machine', resumeCmd, 0],
2688 'save':['Save execution state of virtual machine', saveCmd, 0],
2689 'stats':['Stats for virtual machine', statsCmd, 0],
2690 'powerdown':['Power down virtual machine', powerdownCmd, 0],
2691 'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
2692 'list':['Shows known virtual machines', listCmd, 0],
2693 'info':['Shows info on machine', infoCmd, 0],
2694 'ginfo':['Shows info on guest', ginfoCmd, 0],
2695 'gexec':['Executes program in the guest', gexecCmd, 0],
2696 'alias':['Control aliases', aliasCmd, 0],
2697 'verbose':['Toggle verbosity', verboseCmd, 0],
2698 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
2699 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
2700 'quit':['Exits', quitCmd, 0],
2701 'host':['Show host information', hostCmd, 0],
2702 'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
2703 'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
2704 'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
2705 'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
2706 'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
2707 'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
2708 'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
2709 'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
2710 'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
2711 'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
2712 'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
2713 'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768', screenshotCmd, 0],
2714 'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
2715 'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
2716 'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
2717 'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
2718 'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
2719 'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
2720 'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
2721 'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
2722 'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
2723 'createHdd': ['Create virtual HDD: createHdd 1000 /disk.vdi ', createHddCmd, 0],
2724 'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
2725 'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
2726 'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
2727 'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
2728 'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
2729 'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
2730 'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
2731 'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
2732 'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
2733 'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
2734 'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
2735 'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
2736 'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
2737 'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
2738 'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
2739 'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
2740 'listMedia': ['List media known to this VBox instance', listMediaCmd, 0],
2741 'listUsb': ['List known USB devices', listUsbCmd, 0],
2742 'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
2743 'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
2744 'gui': ['Start GUI frontend', guiCmd, 0],
2745 'colors':['Toggle colors', colorsCmd, 0],
2746 'snapshot':['VM snapshot manipulation, snapshot help for more info', snapshotCmd, 0],
2747 'nat':['NAT (network address trasnlation engine) manipulation, nat help for more info', natCmd, 0],
2748 'nic' : ['Network adapter management', nicCmd, 0],
2749 'prompt' : ['Control prompt', promptCmd, 0],
2750 }
2751
2752def runCommandArgs(ctx, args):
2753 c = args[0]
2754 if aliases.get(c, None) != None:
2755 c = aliases[c]
2756 ci = commands.get(c,None)
2757 if ci == None:
2758 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
2759 return 0
2760 if ctx['remote'] and ctx['vb'] is None:
2761 if c not in ['connect', 'reconnect', 'help', 'quit']:
2762 print "First connect to remote server with %s command." %(colored('connect', 'blue'))
2763 return 0
2764 return ci[1](ctx, args)
2765
2766
2767def runCommand(ctx, cmd):
2768 if len(cmd) == 0: return 0
2769 args = split_no_quotes(cmd)
2770 if len(args) == 0: return 0
2771 return runCommandArgs(ctx, args)
2772
2773#
2774# To write your own custom commands to vboxshell, create
2775# file ~/.VirtualBox/shellext.py with content like
2776#
2777# def runTestCmd(ctx, args):
2778# print "Testy test", ctx['vb']
2779# return 0
2780#
2781# commands = {
2782# 'test': ['Test help', runTestCmd]
2783# }
2784# and issue reloadExt shell command.
2785# This file also will be read automatically on startup or 'reloadExt'.
2786#
2787# Also one can put shell extensions into ~/.VirtualBox/shexts and
2788# they will also be picked up, so this way one can exchange
2789# shell extensions easily.
2790def addExtsFromFile(ctx, cmds, file):
2791 if not os.path.isfile(file):
2792 return
2793 d = {}
2794 try:
2795 execfile(file, d, d)
2796 for (k,v) in d['commands'].items():
2797 if g_verbose:
2798 print "customize: adding \"%s\" - %s" %(k, v[0])
2799 cmds[k] = [v[0], v[1], file]
2800 except:
2801 print "Error loading user extensions from %s" %(file)
2802 traceback.print_exc()
2803
2804
2805def checkUserExtensions(ctx, cmds, folder):
2806 folder = str(folder)
2807 name = os.path.join(folder, "shellext.py")
2808 addExtsFromFile(ctx, cmds, name)
2809 # also check 'exts' directory for all files
2810 shextdir = os.path.join(folder, "shexts")
2811 if not os.path.isdir(shextdir):
2812 return
2813 exts = os.listdir(shextdir)
2814 for e in exts:
2815 # not editor temporary files, please.
2816 if e.endswith('.py'):
2817 addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
2818
2819def getHomeFolder(ctx):
2820 if ctx['remote'] or ctx['vb'] is None:
2821 if 'VBOX_USER_HOME' is os.environ:
2822 return os.path.join(os.environ['VBOX_USER_HOME'])
2823 return os.path.join(os.path.expanduser("~"), ".VirtualBox")
2824 else:
2825 return ctx['vb'].homeFolder
2826
2827def interpret(ctx):
2828 if ctx['remote']:
2829 commands['connect'] = ["Connect to remote VBox instance: connect http://server:18083 user password", connectCmd, 0]
2830 commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
2831 commands['reconnect'] = ["Reconnect to remote VBox instance", reconnectCmd, 0]
2832 ctx['wsinfo'] = ["http://localhost:18083", "", ""]
2833
2834 vbox = ctx['vb']
2835 if vbox is not None:
2836 print "Running VirtualBox version %s" %(vbox.version)
2837 ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
2838 else:
2839 ctx['perf'] = None
2840
2841 home = getHomeFolder(ctx)
2842 checkUserExtensions(ctx, commands, home)
2843 if platform.system() == 'Windows':
2844 global g_hascolors
2845 g_hascolors = False
2846 hist_file=os.path.join(home, ".vboxshellhistory")
2847 autoCompletion(commands, ctx)
2848
2849 if g_hasreadline and os.path.exists(hist_file):
2850 readline.read_history_file(hist_file)
2851
2852 # to allow to print actual host information, we collect info for
2853 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
2854 if ctx['perf']:
2855 try:
2856 ctx['perf'].setup(['*'], [vbox.host], 10, 15)
2857 except:
2858 pass
2859
2860 while True:
2861 try:
2862 cmd = raw_input(ctx['prompt'])
2863 done = runCommand(ctx, cmd)
2864 if done != 0: break
2865 except KeyboardInterrupt:
2866 print '====== You can type quit or q to leave'
2867 except EOFError:
2868 break
2869 except Exception,e:
2870 printErr(ctx,e)
2871 if g_verbose:
2872 traceback.print_exc()
2873 ctx['global'].waitForEvents(0)
2874 try:
2875 # There is no need to disable metric collection. This is just an example.
2876 if ct['perf']:
2877 ctx['perf'].disable(['*'], [vbox.host])
2878 except:
2879 pass
2880 if g_hasreadline:
2881 readline.write_history_file(hist_file)
2882
2883def runCommandCb(ctx, cmd, args):
2884 args.insert(0, cmd)
2885 return runCommandArgs(ctx, args)
2886
2887def runGuestCommandCb(ctx, id, guestLambda, args):
2888 mach = machById(ctx,id)
2889 if mach == None:
2890 return 0
2891 args.insert(0, guestLambda)
2892 cmdExistingVm(ctx, mach, 'guestlambda', args)
2893 return 0
2894
2895def main(argv):
2896 style = None
2897 autopath = False
2898 argv.pop(0)
2899 while len(argv) > 0:
2900 if argv[0] == "-w":
2901 style = "WEBSERVICE"
2902 if argv[0] == "-a":
2903 autopath = True
2904 argv.pop(0)
2905
2906 if autopath:
2907 cwd = os.getcwd()
2908 vpp = os.environ.get("VBOX_PROGRAM_PATH")
2909 if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
2910 vpp = cwd
2911 print "Autodetected VBOX_PROGRAM_PATH as",vpp
2912 os.environ["VBOX_PROGRAM_PATH"] = cwd
2913 sys.path.append(os.path.join(vpp, "sdk", "installer"))
2914
2915 from vboxapi import VirtualBoxManager
2916 g_virtualBoxManager = VirtualBoxManager(style, None)
2917 ctx = {'global':g_virtualBoxManager,
2918 'mgr':g_virtualBoxManager.mgr,
2919 'vb':g_virtualBoxManager.vbox,
2920 'ifaces':g_virtualBoxManager.constants,
2921 'remote':g_virtualBoxManager.remote,
2922 'type':g_virtualBoxManager.type,
2923 'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
2924 'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
2925 'machById': lambda id: machById(ctx,id),
2926 'argsToMach': lambda args: argsToMach(ctx,args),
2927 'progressBar': lambda p: progressBar(ctx,p),
2928 'typeInGuest': typeInGuest,
2929 '_machlist': None,
2930 'prompt': g_prompt
2931 }
2932 interpret(ctx)
2933 g_virtualBoxManager.deinit()
2934 del g_virtualBoxManager
2935
2936if __name__ == '__main__':
2937 main(sys.argv)
Note: See TracBrowser for help on using the repository browser.

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