Changeset 102912 in vbox
- Timestamp:
- Jan 17, 2024 10:18:24 AM (12 months ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/VBox/Frontends/VBoxShell/vboxshell.py
r102890 r102912 1 1 #!/bin/sh 2 2 # -*- coding: utf-8 -*- 3 # pylint: disable=too-many-lines 3 # pylint: disable=line-too-long 4 # pylint: disable=too-many-statements 5 # pylint: disable=deprecated-module 4 6 # $Id$ 5 7 … … 25 27 from __future__ import print_function 26 28 27 """ 28 VirtualBox Python Shell. 29 30 This program is a simple interactive shell for VirtualBox. You can query 31 information and issue commands from a simple command line. 32 33 It also provides you with examples on how to use VirtualBox's Python API. 34 This shell is even somewhat documented, supports TAB-completion and 35 history if you have Python readline installed. 36 37 Finally, shell allows arbitrary custom extensions, just create 38 .VirtualBox/shexts/ and drop your extensions there. 39 Enjoy. 40 41 P.S. Our apologies for the code quality. 42 """ 29 # VirtualBox Python Shell. 30 # 31 # This program is a simple interactive shell for VirtualBox. You can query 32 # information and issue commands from a simple command line. 33 # 34 # It also provides you with examples on how to use VirtualBox's Python API. 35 # This shell is even somewhat documented, supports TAB-completion and 36 # history if you have Python readline installed. 37 # 38 # Finally, shell allows arbitrary custom extensions, just create 39 # .VirtualBox/shexts/ and drop your extensions there. 40 # Enjoy. 41 # 42 # P.S. Our apologies for the code quality. 43 43 44 44 __copyright__ = \ … … 128 128 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812 129 129 """ 130 if False andtext == "":130 if text == "": 131 131 return ['\t', None][state] 132 else: 133 return rlcompleter.Completer.complete(self, text, state) 132 return rlcompleter.Completer.complete(self, text, state) 134 133 135 134 def canBePath(self, _phrase, word): … … 272 271 273 272 def platformArchFromString(ctx, arch): 274 if arch == 'x86' \ 275 or arch == 'x86_64' \ 276 or arch == 'x64': 273 if arch in [ 'x86', 'x86_64', 'x64' ]: 277 274 return ctx['global'].constants.PlatformArchitecture_x86 278 elif arch == 'arm' \ 279 or arch == 'aarch32' \ 280 or arch == 'aarch64': 275 if arch in ['arm', 'aarch32', 'aarch64' ]: 281 276 return ctx['global'].constants.PlatformArchitecture_ARM 282 277 return ctx['global'].constants.PlatformArchitecture_None … … 336 331 else: 337 332 self.name = '<inaccessible>' 338 self.id = mach.id 333 self.id = mach.id # pylint: disable=invalid-name 339 334 340 335 def cacheMachines(_ctx, lst): … … 352 347 if simple: 353 348 return ctx['_machlistsimple'] 354 else: 355 return ctx['_machlist'] 356 else: 357 return [] 349 return ctx['_machlist'] 350 return [] 358 351 359 352 def asState(var): 360 353 if var: 361 354 return colored('on', 'green') 362 else: 363 return colored('off', 'green') 355 return colored('off', 'green') 364 356 365 357 def asFlag(var): 366 358 if var: 367 359 return 'yes' 368 else: 369 return 'no' 360 return 'no' 370 361 371 362 def getFacilityStatus(ctx, guest, facilityType): … … 482 473 g_tsLast = 0 483 474 def recordDemo(ctx, console, filename, dur): 484 demo = open(filename, 'w')485 header = "VM=" + console.machine.name + "\n"486 demo.write(header)487 488 475 global g_tsLast 489 476 g_tsLast = time.time() … … 514 501 # we create an aggregated event source to listen for multiple event sources (keyboard and mouse in our case) 515 502 agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource]) 516 demo = open(filename, 'w', encoding='utf-8') 517 header = "VM=" + console.machine.name + "\n" 518 demo.write(header) 503 with open(filename, 'w', encoding='utf-8') as demo: 504 header = "VM=" + console.machine.name + "\n" 505 demo.write(header) 506 if dur == -1: 507 # not infinity, but close enough 508 dur = 100000 509 try: 510 agg.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], False) 511 registered = True 512 end = time.time() + dur 513 while time.time() < end: 514 event = agg.getEvent(listener, 1000) 515 if event: 516 handleEventImpl(event) 517 # keyboard/mouse events aren't waitable, so no need for eventProcessed 518 # We need to catch all exceptions here, otherwise listener will never be unregistered 519 except: 520 traceback.print_exc() 521 522 demo.close() 523 if listener and registered: 524 agg.unregisterListener(listener) 525 526 527 def playbackDemo(ctx, console, filename, dur): 519 528 if dur == -1: 520 529 # not infinity, but close enough 521 530 dur = 100000 522 try: 523 agg.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], False) 524 registered = True 525 end = time.time() + dur 526 while time.time() < end: 527 event = agg.getEvent(listener, 1000) 528 if event: 529 handleEventImpl(event) 530 # keyboard/mouse events aren't waitable, so no need for eventProcessed 531 # We need to catch all exceptions here, otherwise listener will never be unregistered 532 except: 533 traceback.print_exc() 534 535 demo.close() 536 if listener and registered: 537 agg.unregisterListener(listener) 538 539 540 def playbackDemo(ctx, console, filename, dur): 541 demo = open(filename, 'r', encoding='utf-8') 542 543 if dur == -1: 544 # not infinity, but close enough 545 dur = 100000 546 547 header = demo.readline() 548 print("Header is", header) 549 basere = re.compile(r'(?P<s>\d+): (?P<t>[km]) (?P<p>.*)') 550 mre = re.compile(r'(?P<a>\d+) (?P<x>-*\d+) (?P<y>-*\d+) (?P<z>-*\d+) (?P<w>-*\d+) (?P<b>-*\d+)') 551 kre = re.compile(r'\d+') 552 553 kbd = console.keyboard 554 mouse = console.mouse 555 556 try: 557 end = time.time() + dur 558 for line in demo: 559 if time.time() > end: 560 break 561 match = basere.search(line) 562 if match is None: 563 continue 564 565 rdict = match.groupdict() 566 stamp = rdict['s'] 567 params = rdict['p'] 568 rtype = rdict['t'] 569 570 time.sleep(float(stamp)/1000) 571 572 if rtype == 'k': 573 codes = kre.findall(params) 574 #print("KBD:", codes) 575 kbd.putScancodes(codes) 576 elif rtype == 'm': 577 mm = mre.search(params) 578 if mm is not None: 579 mdict = mm.groupdict() 580 if mdict['a'] == '1': 581 # absolute 582 #print("MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b']) 583 mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 584 else: 585 #print("MR: ", mdict['x'], mdict['y'], mdict['b']) 586 mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 587 588 # We need to catch all exceptions here, to close file 589 except KeyboardInterrupt: 590 ctx['interrupt'] = True 591 except: 592 traceback.print_exc() 593 594 demo.close() 531 with open(filename, 'r', encoding='utf-8') as demo: 532 header = demo.readline() 533 if g_fVerbose: 534 print("Header is", header) 535 basere = re.compile(r'(?P<s>\d+): (?P<t>[km]) (?P<p>.*)') 536 mre = re.compile(r'(?P<a>\d+) (?P<x>-*\d+) (?P<y>-*\d+) (?P<z>-*\d+) (?P<w>-*\d+) (?P<b>-*\d+)') 537 kre = re.compile(r'\d+') 538 539 kbd = console.keyboard 540 mouse = console.mouse 541 542 try: 543 end = time.time() + dur 544 for line in demo: 545 if time.time() > end: 546 break 547 match = basere.search(line) 548 if match is None: 549 continue 550 551 rdict = match.groupdict() 552 stamp = rdict['s'] 553 params = rdict['p'] 554 rtype = rdict['t'] 555 556 time.sleep(float(stamp)/1000) 557 558 if rtype == 'k': 559 codes = kre.findall(params) 560 if g_fVerbose: 561 print("KBD:", codes) 562 kbd.putScancodes(codes) 563 elif rtype == 'm': 564 mouseEvent = mre.search(params) 565 if mouseEvent is not None: 566 mdict = mouseEvent.groupdict() 567 if mdict['a'] == '1': 568 if g_fVerbose: 569 print("MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b']) 570 mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 571 else: 572 if g_fVerbose: 573 print("MR: ", mdict['x'], mdict['y'], mdict['b']) 574 mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 575 576 # We need to catch all exceptions here, to close file 577 except KeyboardInterrupt: 578 ctx['interrupt'] = True 579 except: 580 traceback.print_exc() 581 582 demo.close() 595 583 596 584 def takeScreenshot(ctx, console, args): 597 585 display = console.display 598 586 if len(args) > 0: 599 f = args[0]600 else: 601 f = os.path.join(tempfile.gettempdir(), "screenshot.png")587 filename = args[0] 588 else: 589 filename = os.path.join(tempfile.gettempdir(), "screenshot.png") 602 590 if len(args) > 3: 603 591 screen = int(args[3]) … … 606 594 (fbw, fbh, _fbbpp, _fbx, _fby, _) = display.getScreenResolution(screen) 607 595 if len(args) > 1: 608 w = int(args[1])609 else: 610 w = fbw596 width = int(args[1]) 597 else: 598 width = fbw 611 599 if len(args) > 2: 612 h = int(args[2])613 else: 614 h = fbh615 616 print("Saving screenshot (%d x %d) screen %d in %s..." % (w , h, screen, f))617 data = display.takeScreenShotToArray(screen, w , h, ctx['const'].BitmapFormat_PNG)618 pngfile = open(f, 'wb')619 pngfile.write(data)620 pngfile.close()600 height = int(args[2]) 601 else: 602 height = fbh 603 604 print("Saving screenshot (%d x %d) screen %d in %s..." % (width, height, screen, filename)) 605 data = display.takeScreenShotToArray(screen, width, height, ctx['const'].BitmapFormat_PNG) 606 with open(filename, 'wb') as pngfile: 607 pngfile.write(data) 608 pngfile.close() 621 609 622 610 def teleport(ctx, _session, console, args): … … 685 673 machine.saveSettings() 686 674 687 def cond(c, v1, v2): 688 if c: 689 return v1 690 else: 691 return v2 692 693 def printHostUsbDev(ctx, ud): 694 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))) 695 696 def printUsbDev(_ctx, ud): 697 print(" %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber)) 698 699 def printSf(ctx, sf): 700 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"))) 675 def cond(condToCheck, resTrue, resFalse): 676 if condToCheck: 677 return resTrue 678 return resFalse 679 680 def printHostUsbDev(ctx, usbdev): 681 print(" %s: %s (vendorId=%d productId=%d serial=%s) %s" \ 682 % (usbdev.id, colored(usbdev.product, 'blue'), usbdev.vendorId, usbdev.productId, usbdev.serialNumber, asEnumElem(ctx, 'USBDeviceState', usbdev.state))) 683 684 def printUsbDev(_ctx, usbdev): 685 print(" %s: %s (vendorId=%d productId=%d serial=%s)" \ 686 % (usbdev.id, colored(usbdev.product, 'blue'), usbdev.vendorId, usbdev.productId, usbdev.serialNumber)) 687 688 def printSf(ctx, sharedfolder): 689 print(" name=%s host=%s %s %s" \ 690 % (sharedfolder.name, colPath(ctx, sharedfolder.hostPath), cond(sharedfolder.accessible, "accessible", "not accessible"), cond(sharedfolder.writable, "writable", "read-only"))) 701 691 702 692 def ginfo(ctx, console, _args): … … 715 705 usbs = ctx['global'].getArray(console, 'USBDevices') 716 706 print("Attached USB:") 717 for u din usbs:718 printUsbDev(ctx, u d)707 for usbdev in usbs: 708 printUsbDev(ctx, usbdev) 719 709 rusbs = ctx['global'].getArray(console, 'remoteUSBDevices') 720 710 print("Remote USB:") 721 for u din rusbs:722 printHostUsbDev(ctx, u d)711 for usbdev in rusbs: 712 printHostUsbDev(ctx, usbdev) 723 713 print("Transient shared folders:") 724 714 sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders') 725 for s fin sfs:726 printSf(ctx, s f)715 for sharedfolder in sfs: 716 printSf(ctx, sharedfolder) 727 717 728 718 def cmdExistingVm(ctx, mach, cmd, args): … … 746 736 return 747 737 console = session.console 748 ops = {'pause': lambda:console.pause(),749 'resume': lambda:console.resume(),750 'powerdown': lambda:console.powerDown(),751 'powerbutton': lambda:console.powerButton(),738 ops = {'pause': console.pause(), 739 'resume': console.resume(), 740 'powerdown': console.powerDown(), 741 'powerbutton': console.powerButton(), 752 742 'stats': lambda: perfStats(ctx, mach), 753 743 'guest': lambda: guestExec(ctx, mach, console, args), … … 774 764 775 765 776 def cmdClosedVm(ctx, mach, cmd, args= [], save=True):766 def cmdClosedVm(ctx, mach, cmd, args=None, save=True): 777 767 session = ctx['global'].openMachineSession(mach, fPermitSharing=True) 778 768 mach = session.machine … … 794 784 795 785 796 def cmdAnyVm(ctx, mach, cmd, args= [], save=False):786 def cmdAnyVm(ctx, mach, cmd, args=None, save=False): 797 787 session = ctx['global'].openMachineSession(mach, fPermitSharing=True) 798 788 mach = session.machine … … 838 828 attr = xdict['a'] 839 829 val = xdict['v'] 840 matches = (str(getattr(self.obj, attr)) == val)830 matches = str(getattr(self.obj, attr)) == val 841 831 except: 842 832 pass … … 936 926 return mach 937 927 938 def helpSingleCmd(cmd, h , sp):939 if sp!= 0:940 spec = " [ext from "+ sp+"]"928 def helpSingleCmd(cmd, help_text, from_ext): 929 if from_ext != 0: 930 spec = " [ext from "+from_ext+"]" 941 931 else: 942 932 spec = "" 943 print(" %s: %s%s" % (colored(cmd, 'blue'), h , spec))933 print(" %s: %s%s" % (colored(cmd, 'blue'), help_text, spec)) 944 934 945 935 def helpCmd(_ctx, args): … … 953 943 cmd = args[1] 954 944 c = commands.get(cmd) 955 if c == None:945 if not c: 956 946 print("Command '%s' not known" % (cmd)) 957 947 else: … … 1064 1054 print() 1065 1055 print(colCat(ctx, " Media:")) 1066 for a in attaches:1067 print(" Controller: '%s' port/device: %d:%d type: %s (%s):" % (a .controller, a.port, a.device, asEnumElem(ctx, "DeviceType", a.type), a.type))1068 medium = a .medium1069 if a .type == ctx['global'].constants.DeviceType_HardDisk:1056 for att in attaches: 1057 print(" Controller: '%s' port/device: %d:%d type: %s (%s):" % (att.controller, att.port, att.device, asEnumElem(ctx, "DeviceType", att.type), att.type)) 1058 medium = att.medium 1059 if att.type == ctx['global'].constants.DeviceType_HardDisk: 1070 1060 print(" HDD:") 1071 1061 print(" Id: %s" % (medium.id)) … … 1074 1064 print(" Format: %s" % (medium.format)) 1075 1065 1076 if a .type == ctx['global'].constants.DeviceType_DVD:1066 if att.type == ctx['global'].constants.DeviceType_DVD: 1077 1067 print(" DVD:") 1078 1068 if medium: … … 1081 1071 if medium.hostDrive: 1082 1072 print(" Host DVD %s" % (colPath(ctx, medium.location))) 1083 if a .passthrough:1073 if att.passthrough: 1084 1074 print(" [passthrough mode]") 1085 1075 else: … … 1087 1077 print(" Size: %s" % (medium.size)) 1088 1078 1089 if a .type == ctx['global'].constants.DeviceType_Floppy:1079 if att.type == ctx['global'].constants.DeviceType_Floppy: 1090 1080 print(" Floppy:") 1091 1081 if medium: … … 1100 1090 print() 1101 1091 print(colCat(ctx, " Shared folders:")) 1102 for s fin ctx['global'].getArray(mach, 'sharedFolders'):1103 printSf(ctx, s f)1092 for sharedfolder in ctx['global'].getArray(mach, 'sharedFolders'): 1093 printSf(ctx, sharedfolder) 1104 1094 1105 1095 return 0 … … 1153 1143 if len(args) < 1: 1154 1144 print("exec in guest needs at least program name") 1155 return 1145 return 1 1156 1146 guest = console.guest 1157 1147 # shall contain program name as argv[0] … … 1220 1210 off = 0 1221 1211 while write > 0: 1222 w = process.write(0, 10*1000, indata[off:])1223 off = off + w 1224 write = write - w 1212 written = process.write(0, 10*1000, indata[off:]) 1213 off = off + written 1214 write = write - written 1225 1215 else: 1226 1216 # EOF … … 1342 1332 (user, passwd) = getCred(ctx) 1343 1333 import subprocess 1344 ctx['process'] = subprocess.Popen(split_no_quotes(hcmd), stdout=subprocess.PIPE)1345 gargs = split_no_quotes(gcmd)1346 env = []1347 gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000, lambda ctx:readCmdPipe(ctx, hcmd)))1348 cmdExistingVm(ctx, mach, 'guestlambda', gargs)1349 try:1350 ctx['process'].terminate()1351 except:1352 pass1353 ctx['process'] = None1334 with subprocess.Popen(split_no_quotes(hcmd), stdout=subprocess.PIPE) as ctx['process']: 1335 gargs = split_no_quotes(gcmd) 1336 env = [] 1337 gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000, lambda ctx:readCmdPipe(ctx, hcmd))) 1338 cmdExistingVm(ctx, mach, 'guestlambda', gargs) 1339 try: 1340 ctx['process'].terminate() 1341 except: 1342 pass 1343 ctx['process'] = None 1354 1344 return 0 1355 1345 … … 1578 1568 else: 1579 1569 obj = argsToMach(ctx, args) 1580 if obj == None:1570 if not obj: 1581 1571 return 0 1582 1572 1583 if key == None:1573 if not key: 1584 1574 keys = obj.getExtraDataKeys() 1585 1575 else: … … 1605 1595 global g_fVerbose 1606 1596 if len(args) > 1: 1607 g_fVerbose = (args[1]=='on')1597 g_fVerbose = args[1]=='on' 1608 1598 else: 1609 1599 g_fVerbose = not g_fVerbose … … 1613 1603 global g_fHasColors 1614 1604 if len(args) > 1: 1615 g_fHasColors = (args[1] == 'on')1605 g_fHasColors = args[1] == 'on' 1616 1606 else: 1617 1607 g_fHasColors = not g_fHasColors … … 1649 1639 1650 1640 print(colCat(ctx, "Network interfaces:")) 1651 for niin ctx['global'].getArray(host, 'networkInterfaces'):1652 print(" %s (%s)" % ( ni.name, ni.IPAddress))1641 for iface in ctx['global'].getArray(host, 'networkInterfaces'): 1642 print(" %s (%s)" % (iface.name, iface.IPAddress)) 1653 1643 1654 1644 print(colCat(ctx, "DVD drives:")) 1655 for d din ctx['global'].getArray(host, 'DVDDrives'):1656 print(" %s - %s" % (d d.name, dd.description))1645 for drive in ctx['global'].getArray(host, 'DVDDrives'): 1646 print(" %s - %s" % (drive.name, drive.description)) 1657 1647 1658 1648 print(colCat(ctx, "Floppy drives:")) 1659 for d din ctx['global'].getArray(host, 'floppyDrives'):1660 print(" %s - %s" % (d d.name, dd.description))1649 for drive in ctx['global'].getArray(host, 'floppyDrives'): 1650 print(" %s - %s" % (drive.name, drive.description)) 1661 1651 1662 1652 print(colCat(ctx, "USB devices:")) 1663 for u din ctx['global'].getArray(host, 'USBDevices'):1664 printHostUsbDev(ctx, u d)1653 for usbdev in ctx['global'].getArray(host, 'USBDevices'): 1654 printHostUsbDev(ctx, usbdev) 1665 1655 1666 1656 if ctx['perf']: … … 1739 1729 1740 1730 def getAdapterType(ctx, natype): 1741 if (natype == ctx['global'].constants.NetworkAdapterType_Am79C970A or1742 natype == ctx['global'].constants.NetworkAdapterType_Am79C973 or1743 natype == ctx['global'].constants.NetworkAdapterType_Am79C960):1731 if (natype in ( ctx['global'].constants.NetworkAdapterType_Am79C970A 1732 , ctx['global'].constants.NetworkAdapterType_Am79C973 1733 , ctx['global'].constants.NetworkAdapterType_Am79C960)): 1744 1734 return "pcnet" 1745 elif (natype == ctx['global'].constants.NetworkAdapterType_I82540EM or1746 natype == ctx['global'].constants.NetworkAdapterType_I82545EM or1747 natype == ctx['global'].constants.NetworkAdapterType_I82543GC):1735 if (natype in ( ctx['global'].constants.NetworkAdapterType_I82540EM 1736 , ctx['global'].constants.NetworkAdapterType_I82545EM 1737 , ctx['global'].constants.NetworkAdapterType_I82543GC)): 1748 1738 return "e1000" 1749 elif (natype == ctx['global'].constants.NetworkAdapterType_Virtio):1739 if natype == ctx['global'].constants.NetworkAdapterType_Virtio: 1750 1740 return "virtio" 1751 elif (natype == ctx['global'].constants.NetworkAdapterType_Null):1741 if natype == ctx['global'].constants.NetworkAdapterType_Null: 1752 1742 return None 1753 else: 1754 raise Exception("Unknown adapter type: "+natype) 1755 1743 raise Exception("Unknown adapter type: "+natype) 1756 1744 1757 1745 def portForwardCmd(ctx, args): … … 1828 1816 if len(data) == 0: 1829 1817 break 1830 d= str(data).split("\n")1831 for s in d:1832 match = re.findall(pattern, s)1818 buf = str(data).split("\n") 1819 for line in buf: 1820 match = re.findall(pattern, line) 1833 1821 if len(match) > 0: 1834 for mtin match:1835 s = s.replace(mt, colored(mt, 'red'))1836 print( s)1822 for cur_match in match: 1823 line = line.replace(cur_match, colored(cur_match, 'red')) 1824 print(line) 1837 1825 uOffset += len(data) 1838 1826 … … 1861 1849 if len(data) == 0: 1862 1850 break 1863 d= str(data).split("\n")1864 for s in d:1851 buf = str(data).split("\n") 1852 for line in buf: 1865 1853 if active: 1866 print( s)1854 print(line) 1867 1855 if context == 0: 1868 1856 active = False … … 1870 1858 context = context - 1 1871 1859 continue 1872 match = ere.findall( s)1860 match = ere.findall(line) 1873 1861 if len(match) > 0: 1874 1862 active = True 1875 1863 context = 50 1876 print( s)1864 print(line) 1877 1865 uOffset += len(data) 1878 1866 … … 1899 1887 print("usage: runScript <script>") 1900 1888 return 0 1889 1901 1890 try: 1902 lf = open(args[1], 'r', encoding='utf-8') 1891 with open(args[1], 'r', encoding='utf-8') as file: 1892 try: 1893 lines = file.readlines() 1894 ctx['scriptLine'] = 0 1895 ctx['interrupt'] = False 1896 while ctx['scriptLine'] < len(lines): 1897 line = lines[ctx['scriptLine']] 1898 ctx['scriptLine'] = ctx['scriptLine'] + 1 1899 done = runCommand(ctx, line) 1900 if done != 0 or ctx['interrupt']: 1901 break 1902 1903 except Exception as e: 1904 printErr(ctx, e) 1905 if g_fVerbose: 1906 traceback.print_exc() 1907 file.close() 1903 1908 except IOError as e: 1904 1909 print("cannot open:", args[1], ":", e) 1905 return 0 1906 1907 try: 1908 lines = lf.readlines() 1909 ctx['scriptLine'] = 0 1910 ctx['interrupt'] = False 1911 while ctx['scriptLine'] < len(lines): 1912 line = lines[ctx['scriptLine']] 1913 ctx['scriptLine'] = ctx['scriptLine'] + 1 1914 done = runCommand(ctx, line) 1915 if done != 0 or ctx['interrupt']: 1916 break 1917 1918 except Exception as e: 1919 printErr(ctx, e) 1920 if g_fVerbose: 1921 traceback.print_exc() 1922 lf.close() 1910 return 1 1923 1911 return 0 1924 1912 … … 2183 2171 time.sleep(0.3) 2184 2172 continue 2185 if ch == '^' or ch == '|' or ch == '$' or ch == '_':2173 if ch in ('^', '|', '$', '_'): 2186 2174 if ch == '^': 2187 2175 ch = 'LCTR' … … 2243 2231 if verbose: 2244 2232 return ": "+uuid 2245 else: 2246 return "" 2233 return "" 2247 2234 2248 2235 def asSize(val, inBytes): 2249 2236 if inBytes: 2250 2237 return int(val)/(1024*1024) 2251 else: 2252 return int(val) 2238 return int(val) 2253 2239 2254 2240 def listMediaCmd(ctx, args): … … 2286 2272 2287 2273 host = ctx['vb'].host 2288 for u din ctx['global'].getArray(host, 'USBDevices'):2289 printHostUsbDev(ctx, u d)2274 for usbdev in ctx['global'].getArray(host, 'USBDevices'): 2275 printHostUsbDev(ctx, usbdev) 2290 2276 2291 2277 return 0 2292 2278 2293 2279 def findDevOfType(ctx, mach, devtype): 2294 att s = ctx['global'].getArray(mach, 'mediumAttachments')2295 for a in atts:2296 if a .type == devtype:2297 return [a .controller, a.port, a.device]2280 attachments = ctx['global'].getArray(mach, 'mediumAttachments') 2281 for att in attachments: 2282 if att.type == devtype: 2283 return [att.controller, att.port, att.device] 2298 2284 return [None, 0, 0] 2299 2285 … … 2361 2347 2362 2348 def detachVmDevice(ctx, mach, args): 2363 att s = ctx['global'].getArray(mach, 'mediumAttachments')2349 attachments = ctx['global'].getArray(mach, 'mediumAttachments') 2364 2350 hid = args[0] 2365 for a in atts:2366 if a .medium:2367 if hid == "ALL" or a.medium.id == hid:2368 mach.detachDevice(a .controller, a.port, a.device)2351 for att in attachments: 2352 if att.medium: 2353 if hid in ('ALL', att.medium.id): 2354 mach.detachDevice(att.controller, att.port, att.device) 2369 2355 2370 2356 def detachMedium(ctx, mid, medium): … … 2576 2562 [name, bus, ctrltype] = args 2577 2563 ctr = mach.addStorageController(name, bus) 2578 if ctrltype != None:2564 if ctrltype: 2579 2565 ctr.controllerType = ctrltype 2580 2566 … … 2586 2572 if len(args) > 4: 2587 2573 ctrltype = enumFromString(ctx, 'StorageControllerType', args[4]) 2588 if ctrltype == None:2574 if not ctrltype: 2589 2575 print("Controller type %s unknown" % (args[4])) 2590 2576 return 0 … … 2674 2660 persistent = False 2675 2661 if len(args) > 4: 2676 for ain args[4:]:2677 if a== 'writable':2662 for cur_arg in args[4:]: 2663 if cur_arg == 'writable': 2678 2664 writable = True 2679 if a== 'persistent':2665 if cur_arg == 'persistent': 2680 2666 persistent = True 2681 2667 if persistent: … … 2695 2681 name = args[2] 2696 2682 found = False 2697 for s fin ctx['global'].getArray(mach, 'sharedFolders'):2698 if s f.name == name:2683 for sharedfolder in ctx['global'].getArray(mach, 'sharedFolders'): 2684 if sharedfolder.name == name: 2699 2685 cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeSharedFolder(name), []) 2700 2686 found = True … … 2757 2743 return 0 2758 2744 2759 def natAlias(_ctx, _mach, _nicnum, nat, args= []):2745 def natAlias(_ctx, _mach, _nicnum, nat, args=None): 2760 2746 """This command shows/alters NAT's alias settings. 2761 2747 usage: nat <vmname|uuid> <nicnum> alias [default|[log] [proxyonly] [sameports]] … … 2783 2769 msg += '%s: %s' % (aliasmode, 'off') 2784 2770 return (0, [msg]) 2785 else: 2786 2787 2788 for ain range(1, len(args)):2789 if args[a] not in alias:2790 print('Invalid alias mode: ' + args[a])2791 2792 2793 nat.aliasMode = int(nat.aliasMode) | alias[args[a]]2771 2772 nat.aliasMode = 0 2773 if 'default' not in args: 2774 for idx in range(1, len(args)): 2775 if args[idx] not in alias: 2776 print('Invalid alias mode: ' + args[idx]) 2777 print(natAlias.__doc__) 2778 return (1, None) 2779 nat.aliasMode = int(nat.aliasMode) | alias[args[idx]] 2794 2780 return (0, None) 2795 2781 2796 2782 def natSettings(_ctx, _mach, _nicnum, nat, args): 2797 """This command shows/alters NAT settings. 2783 """ 2784 This command shows/alters NAT settings. 2798 2785 usage: nat <vmname|uuid> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]] 2799 2786 mtu - set mtu <= 16000 … … 2810 2797 msg = 'mtu:%s socket(snd:%s, rcv:%s) tcpwnd(snd:%s, rcv:%s)' % (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) 2811 2798 return (0, [msg]) 2812 else: 2813 if args[1] < 16000: 2814 print('invalid mtu value (%s not in range [65 - 16000])' % (args[1])) 2799 2800 if args[1] < 16000: 2801 print('invalid mtu value (%s not in range [65 - 16000])' % (args[1])) 2802 return (1, None) 2803 for i in range(2, len(args)): 2804 if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024: 2805 print('invalid %s parameter (%i not in range [8-1024])' % (i, args[i])) 2815 2806 return (1, None) 2816 for i in range(2, len(args)): 2817 if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024: 2818 print('invalid %s parameter (%i not in range [8-1024])' % (i, args[i])) 2819 return (1, None) 2820 a = [args[1]] 2821 if len(args) < 6: 2822 for i in range(2, len(args)): a.append(args[i]) 2823 for i in range(len(args), 6): a.append(0) 2824 else: 2825 for i in range(2, len(args)): a.append(args[i]) 2826 #print(a) 2827 nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4])) 2807 nic_args = [args[1]] 2808 if len(args) < 6: 2809 for i in range(2, len(args)): nic_args.append(args[i]) 2810 for i in range(len(args), 6): nic_args.append(0) 2811 else: 2812 for i in range(2, len(args)): nic_args.append(args[i]) 2813 #print(a) 2814 nat.setNetworkSettings(int(nic_args[0]), int(nic_args[1]), int(nic_args[2]), int(nic_args[3]), int(nic_args[4])) 2828 2815 return (0, None) 2829 2816 … … 2839 2826 msg = 'passdomain:%s, proxy:%s, usehostresolver:%s' % (yesno[int(nat.DNSPassDomain)], yesno[int(nat.DNSProxy)], yesno[int(nat.DNSUseHostResolver)]) 2840 2827 return (0, [msg]) 2841 else: 2842 2843 2844 2828 2829 nat.DNSPassDomain = 'passdomain' in args 2830 nat.DNSProxy = 'proxy' in args 2831 nat.DNSUseHostResolver = 'usehostresolver' in args 2845 2832 return (0, None) 2846 2833 … … 2861 2848 while server.count('.') != 3: 2862 2849 server += '.0' 2863 ( a, b, c, _d) = server.split('.')2864 server = '%d.%d.%d.4' % ( a, b, c)2850 (ipA, ipB, ipC, _ipD) = server.split('.') 2851 server = '%d.%d.%d.4' % (ipA, ipB, ipC) 2865 2852 prefix = nat.TFTPPrefix 2866 2853 if prefix is None: … … 2871 2858 msg = 'server:%s, prefix:%s, bootfile:%s' % (server, prefix, bootfile) 2872 2859 return (0, [msg]) 2873 else: 2874 2875 cmd = args[1] 2876 if len(args) != 3: 2877 print('invalid args:', args) 2878 print(natTftp.__doc__) 2879 return (1, None) 2880 if cmd == 'prefix': nat.TFTPPrefix = args[2] 2881 elif cmd == 'bootfile': nat.TFTPBootFile = args[2] 2882 elif cmd == 'server': nat.TFTPNextServer = args[2] 2883 else: 2884 print("invalid cmd:", cmd) 2885 return (1, None) 2860 2861 cmd = args[1] 2862 if len(args) != 3: 2863 print('invalid args:', args) 2864 print(natTftp.__doc__) 2865 return (1, None) 2866 if cmd == 'prefix': nat.TFTPPrefix = args[2] 2867 elif cmd == 'bootfile': nat.TFTPBootFile = args[2] 2868 elif cmd == 'server': nat.TFTPNextServer = args[2] 2869 else: 2870 print("invalid cmd:", cmd) 2871 return (1, None) 2886 2872 return (0, None) 2887 2873 … … 2898 2884 proto = {0: 'udp', 1: 'tcp'} 2899 2885 msg = [] 2900 p fs = ctx['global'].getArray(nat, 'redirects')2901 for pf in pfs:2902 (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str( pf).split(', ')2886 port_forwardings = ctx['global'].getArray(nat, 'redirects') 2887 for forwarding in port_forwardings: 2888 (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(forwarding).split(', ') 2903 2889 msg.append('%s: %s %s:%s => %s:%s' % (pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp)) 2904 2890 return (0, msg) # msg is array 2905 else: 2906 proto = {'udp': 0, 'tcp': 1} 2907 pfcmd = { 2908 'simple': { 2909 'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 5, 2910 'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4])) 2911 }, 2912 'no_name': { 2913 'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 7, 2914 'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6])) 2915 }, 2916 'ex': { 2917 'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 8, 2918 'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7])) 2919 }, 2920 'delete': { 2921 'validate': lambda: len(args) == 3, 2922 'func': lambda: nat.removeRedirect(args[2]) 2923 } 2891 2892 proto = {'udp': 0, 'tcp': 1} 2893 pfcmd = { 2894 'simple': { 2895 'validate': lambda: args[1] in list(pfcmd) and args[2] in list(proto) and len(args) == 5, 2896 'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4])) 2897 }, 2898 'no_name': { 2899 'validate': lambda: args[1] in list(pfcmd) and args[2] in list(proto) and len(args) == 7, 2900 'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6])) 2901 }, 2902 'ex': { 2903 'validate': lambda: args[1] in list(pfcmd) and args[2] in list(proto) and len(args) == 8, 2904 'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7])) 2905 }, 2906 'delete': { 2907 'validate': lambda: len(args) == 3, 2908 'func': lambda: nat.removeRedirect(args[2]) 2924 2909 } 2925 2926 if not pfcmd[args[1]]['validate'](): 2927 print('invalid port-forwarding or args of sub command ', args[1]) 2928 print(natPortForwarding.__doc__) 2929 return (1, None) 2930 2931 _a = pfcmd[args[1]]['func']() 2910 } 2911 2912 if not pfcmd[args[1]]['validate'](): 2913 print('invalid port-forwarding or args of sub command ', args[1]) 2914 print(natPortForwarding.__doc__) 2915 return (1, None) 2916 2917 _not_sure_for_what_this_is = pfcmd[args[1]]['func']() 2932 2918 return (0, None) 2933 2919 … … 2942 2928 msg = '10.0.%d.0/24' % (int(nicnum) + 2) 2943 2929 return (0, [msg]) 2944 else: 2945 2946 2947 2948 2949 2930 2931 (addr, mask) = args[1].split('/') 2932 if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32: 2933 print('Invalid arguments') 2934 return (1, None) 2935 nat.network = args[1] 2950 2936 return (0, None) 2951 2937 … … 3001 2987 adapter = mach.getNetworkAdapter(nicnum) 3002 2988 natEngine = adapter.NATEngine 3003 (rc, report ) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)2989 (rc, reports) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs) 3004 2990 if rosession == 0: 3005 2991 if rc == 0: 3006 2992 mach.saveSettings() 3007 2993 session.unlockMachine() 3008 elif report is not None:3009 for r in report:3010 msg ='%s nic%d %s: %s' % (mach.name, nicnum, func, r)2994 elif reports: 2995 for cur_report in reports: 2996 msg ='%s nic%d %s: %s' % (mach.name, nicnum, func, cur_report) 3011 2997 print(msg) 3012 2998 return 0 … … 3015 3001 if len(args) == 1: 3016 3002 yesno = {0: 'off', 1: 'on'} 3017 r = yesno[int(adapter.__getattr__(attr))]3018 return (0, r )3019 else: 3020 3021 3022 3023 3024 adapter.__setattr__(attr, yesno[args[1]])3003 resp = yesno[int(adapter.getattr(attr))] 3004 return (0, resp) 3005 3006 yesno = {'off' : 0, 'on' : 1} 3007 if args[1] not in yesno: 3008 print('%s isn\'t acceptable, please choose %s' % (args[1], list(yesno.keys()))) 3009 return (1, None) 3010 adapter.setsetattr(attr, yesno[args[1]]) 3025 3011 return (0, None) 3026 3012 … … 3029 3015 usage: nic <vmname|uuid> <nicnum> trace [on|off [file]] 3030 3016 ''' 3031 (rc, r ) = nicSwitchOnOff(adapter, 'traceEnabled', args)3017 (rc, resp) = nicSwitchOnOff(adapter, 'traceEnabled', args) 3032 3018 if len(args) == 1 and rc == 0: 3033 r = '%s file:%s' % (r, adapter.traceFile)3034 return (0, r )3035 elif len(args) == 3 and rc == 0:3019 resp = '%s file:%s' % (resp, adapter.traceFile) 3020 return (0, resp) 3021 if len(args) == 3 and rc == 0: 3036 3022 adapter.traceFile = args[2] 3037 3023 return (0, None) … … 3039 3025 def nicLineSpeedSubCmd(_ctx, _vm, _nicnum, adapter, args): 3040 3026 if len(args) == 1: 3041 r = '%d kbps'% (adapter.lineSpeed)3042 return (0, r )3043 else: 3044 3045 3046 3047 3027 resp = '%d kbps'% (adapter.lineSpeed) 3028 return (0, resp) 3029 3030 if not args[1].isdigit(): 3031 print('%s isn\'t a number' % (args[1])) 3032 return (1, None) 3033 adapter.lineSpeed = int(args[1]) 3048 3034 return (0, None) 3049 3035 … … 3070 3056 return (0, str(key)) 3071 3057 return (1, None) 3072 else: 3073 3074 3075 3076 3077 3058 3059 nictypes = ctx['const'].all_values('NetworkAdapterType') 3060 if args[1] not in list(nictypes.keys()): 3061 print('%s not in acceptable values (%s)' % (args[1], list(nictypes.keys()))) 3062 return (1, None) 3063 adapter.adapterType = nictypes[args[1]] 3078 3064 return (0, None) 3079 3065 … … 3092 3078 ctx['global'].constants.NetworkAttachmentType_Generic: ('Generic', ''), 3093 3079 } 3094 if type(adapter.attachmentType) != int:3080 if not isinstance(adapter.attachmentType, int): 3095 3081 t = str(adapter.attachmentType) 3096 3082 else: 3097 3083 t = adapter.attachmentType 3098 (r , p) = nicAttachmentType[t]3099 return (0, 'attachment:%s, name:%s' % (r , p))3100 else: 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 'p': lambda: adapter.__setattr__('bridgedInterface', args[2]),3113 3114 3115 3116 'p': lambda: adapter.__setattr__('internalNetwork', args[2]),3117 3118 3119 3120 'p': lambda: adapter.__setattr__('hostOnlyInterface', args[2]),3121 3122 3123 3124 3125 3126 3127 3128 if args[1] not in list(nicAttachmentType.keys()):3129 3130 3131 3132 print(nicAttachmentType.__doc__)3133 3134 3135 3084 (resp, name) = nicAttachmentType[t] 3085 return (0, 'attachment:%s, name:%s' % (resp, name)) 3086 3087 nicAttachmentType = { 3088 'Null': { 3089 'v': lambda: len(args) == 2, 3090 'p': lambda: 'do nothing', 3091 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Null}, 3092 'NAT': { 3093 'v': lambda: len(args) == 2, 3094 'p': lambda: 'do nothing', 3095 'f': lambda: ctx['global'].constants.NetworkAttachmentType_NAT}, 3096 'Bridged': { 3097 'v': lambda: len(args) == 3, 3098 'p': lambda: adapter.setattr('bridgedInterface', args[2]), 3099 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Bridged}, 3100 'Internal': { 3101 'v': lambda: len(args) == 3, 3102 'p': lambda: adapter.setattr('internalNetwork', args[2]), 3103 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Internal}, 3104 'HostOnly': { 3105 'v': lambda: len(args) == 2, 3106 'p': lambda: adapter.setattr('hostOnlyInterface', args[2]), 3107 'f': lambda: ctx['global'].constants.NetworkAttachmentType_HostOnly}, 3108 # @todo implement setting the properties of a generic attachment 3109 'Generic': { 3110 'v': lambda: len(args) == 3, 3111 'p': lambda: 'do nothing', 3112 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Generic} 3113 } 3114 if args[1] not in list(nicAttachmentType): 3115 print('%s not in acceptable values (%s)' % (args[1], list(nicAttachmentType.keys()))) 3116 return (1, None) 3117 if not nicAttachmentType[args[1]]['v'](): 3118 ## @todo r=andy Log this properly! 3119 return (1, None) 3120 nicAttachmentType[args[1]]['p']() 3121 adapter.attachmentType = nicAttachmentType[args[1]]['f']() 3136 3122 return (0, None) 3137 3123 … … 3161 3147 return 0 3162 3148 3163 vm = ctx['argsToMach'](args) 3164 if vm is None: 3165 print('please specify vm') 3166 return 0 3167 3168 platformProps = vm.platform.properties 3149 mach = ctx['argsToMach'](args) 3150 if not mach: 3151 return 1 3152 3153 platformProps = mach.platform.properties 3169 3154 if len(args) < 3 \ 3170 or int(args[2]) not in list(range(0, platformProps.getMaxNetworkAdapters( vm.platform.chipsetType))):3171 print('please specify adapter num %d isn\'t in range [0-%d]'% (args[2], platformProps.getMaxNetworkAdapters( vm.platform.chipsetType)))3172 return 03155 or int(args[2]) not in list(range(0, platformProps.getMaxNetworkAdapters(mach.platform.chipsetType))): 3156 print('please specify adapter num %d isn\'t in range [0-%d]'% (args[2], platformProps.getMaxNetworkAdapters(mach.platform.chipsetType))) 3157 return 1 3173 3158 nicnum = int(args[2]) 3174 3159 cmdargs = args[3:] 3175 3160 func = args[3] 3176 3161 session = None 3177 session = ctx['global'].openMachineSession( vm, fPermitSharing=True)3178 vm= session.machine3179 adapter = vm.getNetworkAdapter(nicnum)3180 (rc, report) = niccomand[func](ctx, vm, nicnum, adapter, cmdargs)3162 session = ctx['global'].openMachineSession(mach, fPermitSharing=True) 3163 mach = session.machine 3164 adapter = mach.getNetworkAdapter(nicnum) 3165 (rc, report) = niccomand[func](ctx, mach, nicnum, adapter, cmdargs) 3181 3166 if rc == 0: 3182 vm.saveSettings()3167 mach.saveSettings() 3183 3168 if report is not None: 3184 print('%s nic %d %s: %s' % ( vm.name, nicnum, args[3], report))3169 print('%s nic %d %s: %s' % (mach.name, nicnum, args[3], report)) 3185 3170 session.unlockMachine() 3186 3171 return 0 … … 3257 3242 def lspci(ctx, console): 3258 3243 assigned = ctx['global'].getArray(console.machine, 'PCIDeviceAssignments') 3259 for a in assigned:3260 if a .isPhysicalDevice:3261 print("%s: assigned host device %s guest %s" % (colDev(ctx, a .name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress)))3244 for assignment in assigned: 3245 if assignment.isPhysicalDevice: 3246 print("%s: assigned host device %s guest %s" % (colDev(ctx, assignment.name), pciAddr(ctx, assignment.hostAddress), pciAddr(ctx, assignment.guestAddress))) 3262 3247 3263 3248 atts = ctx['global'].getArray(console, 'attachedPCIDevices') 3264 for a in atts:3265 if a .isPhysicalDevice:3266 print("%s: physical, guest %s, host %s" % (colDev(ctx, a .name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress)))3249 for att in atts: 3250 if att.isPhysicalDevice: 3251 print("%s: physical, guest %s, host %s" % (colDev(ctx, att.name), pciAddr(ctx, att.guestAddress), pciAddr(ctx, att.hostAddress))) 3267 3252 else: 3268 print("%s: virtual, guest %s" % (colDev(ctx, a .name), pciAddr(ctx, a.guestAddress)))3253 print("%s: virtual, guest %s" % (colDev(ctx, att.name), pciAddr(ctx, att.guestAddress))) 3269 3254 return 3270 3255 … … 3430 3415 def runCommandArgs(ctx, args): 3431 3416 c = args[0] 3432 if aliases.get(c, None) != None:3417 if aliases.get(c, None): 3433 3418 c = aliases[c] 3434 c i= commands.get(c, None)3435 if ci == None:3419 cmd_internal = commands.get(c, None) 3420 if not cmd_internal: 3436 3421 print("Unknown command: '%s', type 'help' for list of known commands" % (c)) 3437 3422 return 0 … … 3440 3425 print("First connect to remote server with %s command." % (colored('connect', 'blue'))) 3441 3426 return 0 3442 return c i[1](ctx, args)3427 return cmd_internal[1](ctx, args) 3443 3428 3444 3429 … … 3469 3454 if not os.path.isfile(filename): 3470 3455 return 3471 d= {}3456 extDict = {} 3472 3457 try: 3473 exec(compile(open(filename, encoding='utf-8').read(), filename, 'exec'), d, d) # pylint: disable=exec-used 3474 for (k, v) in list(d['commands'].items()): 3458 with open(filename, encoding='utf-8') as file: 3459 file_buf = file.read() 3460 exec(compile(file_buf, filename, 'exec'), extDict, extDict) # pylint: disable=exec-used 3461 for (key, value) in list(extDict['commands'].items()): 3475 3462 if g_fVerbose: 3476 print("customize: adding \"%s\" - %s" % (k , v[0]))3477 cmds[k ] = [v[0], v[1], filename]3463 print("customize: adding \"%s\" - %s" % (key, value[0])) 3464 cmds[key] = [value[0], value[1], filename] 3478 3465 except: 3479 3466 print("Error loading user extensions from %s" % (filename)) … … 3500 3487 return os.path.join(os.environ['VBOX_USER_HOME']) 3501 3488 return os.path.join(os.path.expanduser("~"), ".VirtualBox") 3502 else: 3503 3489 3490 return ctx['vb'].homeFolder 3504 3491 3505 3492 def interpret(ctx): … … 3544 3531 if g_sCmd is not None: 3545 3532 cmds = g_sCmd.split(';') 3546 it = cmds.__iter__()3533 itCmd = iter(cmds) 3547 3534 3548 3535 while True: … … 3551 3538 cmd = 'runScript %s'% (g_sScriptFile) 3552 3539 elif g_sCmd is not None: 3553 cmd = next(it )3540 cmd = next(itCmd) 3554 3541 else: 3555 3542 if sys.version_info[0] <= 2: … … 3558 3545 cmd = input(ctx['prompt']) 3559 3546 done = runCommand(ctx, cmd) 3560 if done != 0: break 3547 if done != 0: 3548 break 3561 3549 if g_fBatchMode: 3562 3550 break
Note:
See TracChangeset
for help on using the changeset viewer.