VirtualBox

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

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

vboxshell: check for output after wait too

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