VirtualBox

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

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

VBoxShell: adds nic commands.

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

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