VirtualBox

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

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

typo

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