VirtualBox

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

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

VBoxShell: demo recording/playback

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