VirtualBox

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

Last change on this file since 38093 was 38093, checked in by vboxsync, 13 years ago

*.kmk,++: Mode fixes to maximize hardlinking potential during staging.

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