VirtualBox

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

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

VBoxShell: check progress result code

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