VirtualBox

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

Last change on this file since 33321 was 33321, checked in by vboxsync, 14 years ago

Main. VBoxShell: demo recorder fully functional

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