VirtualBox

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

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

tweaks

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