VirtualBox

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

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

VBoxShell: gcopy command

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

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