VirtualBox

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

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

vboxshell: attribute values can be not only alpha-numeric

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