VirtualBox

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

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

vboxshell: lspci command

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

© 2023 Oracle
ContactPrivacy policyTerms of Use