VirtualBox

Changeset 102912 in vbox


Ignore:
Timestamp:
Jan 17, 2024 10:18:24 AM (12 months ago)
Author:
vboxsync
Message:

Frontends/VBoxShell: Make it pass pylint 10.00. Kept the coding style as-is, as I didn't feel rewriting a lot of the code.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Frontends/VBoxShell/vboxshell.py

    r102890 r102912  
    11#!/bin/sh
    22# -*- 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
    46# $Id$
    57
     
    2527from __future__ import print_function
    2628
    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.
    4343
    4444__copyright__ = \
     
    128128            http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
    129129            """
    130             if False and text == "":
     130            if text == "":
    131131                return ['\t', None][state]
    132             else:
    133                 return rlcompleter.Completer.complete(self, text, state)
     132            return rlcompleter.Completer.complete(self, text, state)
    134133
    135134        def canBePath(self, _phrase, word):
     
    272271
    273272def platformArchFromString(ctx, arch):
    274     if     arch == 'x86' \
    275         or arch == 'x86_64' \
    276         or arch == 'x64':
     273    if arch in [ 'x86', 'x86_64', 'x64' ]:
    277274        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' ]:
    281276        return ctx['global'].constants.PlatformArchitecture_ARM
    282277    return ctx['global'].constants.PlatformArchitecture_None
     
    336331        else:
    337332            self.name = '<inaccessible>'
    338         self.id = mach.id
     333        self.id = mach.id # pylint: disable=invalid-name
    339334
    340335def cacheMachines(_ctx, lst):
     
    352347        if simple:
    353348            return ctx['_machlistsimple']
    354         else:
    355             return ctx['_machlist']
    356     else:
    357         return []
     349        return ctx['_machlist']
     350    return []
    358351
    359352def asState(var):
    360353    if var:
    361354        return colored('on', 'green')
    362     else:
    363         return colored('off', 'green')
     355    return colored('off', 'green')
    364356
    365357def asFlag(var):
    366358    if var:
    367359        return 'yes'
    368     else:
    369         return 'no'
     360    return 'no'
    370361
    371362def getFacilityStatus(ctx, guest, facilityType):
     
    482473g_tsLast = 0
    483474def recordDemo(ctx, console, filename, dur):
    484     demo = open(filename, 'w')
    485     header = "VM=" + console.machine.name + "\n"
    486     demo.write(header)
    487 
    488475    global g_tsLast
    489476    g_tsLast = time.time()
     
    514501    # we create an aggregated event source to listen for multiple event sources (keyboard and mouse in our case)
    515502    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
     527def playbackDemo(ctx, console, filename, dur):
    519528    if dur == -1:
    520529        # not infinity, but close enough
    521530        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()
    595583
    596584def takeScreenshot(ctx, console, args):
    597585    display = console.display
    598586    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")
    602590    if len(args) > 3:
    603591        screen = int(args[3])
     
    606594    (fbw, fbh, _fbbpp, _fbx, _fby, _) = display.getScreenResolution(screen)
    607595    if len(args) > 1:
    608         w = int(args[1])
    609     else:
    610         w = fbw
     596        width = int(args[1])
     597    else:
     598        width = fbw
    611599    if len(args) > 2:
    612         h = int(args[2])
    613     else:
    614         h = fbh
    615 
    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()
    621609
    622610def teleport(ctx, _session, console, args):
     
    685673    machine.saveSettings()
    686674
    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")))
     675def cond(condToCheck, resTrue, resFalse):
     676    if condToCheck:
     677        return resTrue
     678    return resFalse
     679
     680def 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
     684def 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
     688def 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")))
    701691
    702692def ginfo(ctx, console, _args):
     
    715705    usbs = ctx['global'].getArray(console, 'USBDevices')
    716706    print("Attached USB:")
    717     for ud in usbs:
    718         printUsbDev(ctx, ud)
     707    for usbdev in usbs:
     708        printUsbDev(ctx, usbdev)
    719709    rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
    720710    print("Remote USB:")
    721     for ud in rusbs:
    722         printHostUsbDev(ctx, ud)
     711    for usbdev in rusbs:
     712        printHostUsbDev(ctx, usbdev)
    723713    print("Transient shared folders:")
    724714    sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
    725     for sf in sfs:
    726         printSf(ctx, sf)
     715    for sharedfolder in sfs:
     716        printSf(ctx, sharedfolder)
    727717
    728718def cmdExistingVm(ctx, mach, cmd, args):
     
    746736        return
    747737    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(),
    752742           'stats':           lambda: perfStats(ctx, mach),
    753743           'guest':           lambda: guestExec(ctx, mach, console, args),
     
    774764
    775765
    776 def cmdClosedVm(ctx, mach, cmd, args=[], save=True):
     766def cmdClosedVm(ctx, mach, cmd, args=None, save=True):
    777767    session = ctx['global'].openMachineSession(mach, fPermitSharing=True)
    778768    mach = session.machine
     
    794784
    795785
    796 def cmdAnyVm(ctx, mach, cmd, args=[], save=False):
     786def cmdAnyVm(ctx, mach, cmd, args=None, save=False):
    797787    session = ctx['global'].openMachineSession(mach, fPermitSharing=True)
    798788    mach = session.machine
     
    838828                attr = xdict['a']
    839829                val = xdict['v']
    840                 matches = (str(getattr(self.obj, attr)) == val)
     830                matches = str(getattr(self.obj, attr)) == val
    841831        except:
    842832            pass
     
    936926    return mach
    937927
    938 def helpSingleCmd(cmd, h, sp):
    939     if sp != 0:
    940         spec = " [ext from "+sp+"]"
     928def helpSingleCmd(cmd, help_text, from_ext):
     929    if from_ext != 0:
     930        spec = " [ext from "+from_ext+"]"
    941931    else:
    942932        spec = ""
    943     print("    %s: %s%s" % (colored(cmd, 'blue'), h, spec))
     933    print("    %s: %s%s" % (colored(cmd, 'blue'), help_text, spec))
    944934
    945935def helpCmd(_ctx, args):
     
    953943        cmd = args[1]
    954944        c = commands.get(cmd)
    955         if c == None:
     945        if not c:
    956946            print("Command '%s' not known" % (cmd))
    957947        else:
     
    10641054        print()
    10651055        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.medium
    1069         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:
    10701060            print("   HDD:")
    10711061            print("    Id: %s" % (medium.id))
     
    10741064            print("    Format: %s" % (medium.format))
    10751065
    1076         if a.type == ctx['global'].constants.DeviceType_DVD:
     1066        if att.type == ctx['global'].constants.DeviceType_DVD:
    10771067            print("   DVD:")
    10781068            if medium:
     
    10811071                if medium.hostDrive:
    10821072                    print("    Host DVD %s" % (colPath(ctx, medium.location)))
    1083                     if a.passthrough:
     1073                    if att.passthrough:
    10841074                        print("    [passthrough mode]")
    10851075                else:
     
    10871077                    print("    Size: %s" % (medium.size))
    10881078
    1089         if a.type == ctx['global'].constants.DeviceType_Floppy:
     1079        if att.type == ctx['global'].constants.DeviceType_Floppy:
    10901080            print("   Floppy:")
    10911081            if medium:
     
    11001090    print()
    11011091    print(colCat(ctx, "  Shared folders:"))
    1102     for sf in ctx['global'].getArray(mach, 'sharedFolders'):
    1103         printSf(ctx, sf)
     1092    for sharedfolder in ctx['global'].getArray(mach, 'sharedFolders'):
     1093        printSf(ctx, sharedfolder)
    11041094
    11051095    return 0
     
    11531143    if len(args) < 1:
    11541144        print("exec in guest needs at least program name")
    1155         return
     1145        return 1
    11561146    guest = console.guest
    11571147    # shall contain program name as argv[0]
     
    12201210                        off = 0
    12211211                        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
    12251215                    else:
    12261216                        # EOF
     
    13421332    (user, passwd) = getCred(ctx)
    13431333    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         pass
    1353     ctx['process'] = None
     1334    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
    13541344    return 0
    13551345
     
    15781568    else:
    15791569        obj = argsToMach(ctx, args)
    1580         if obj == None:
     1570        if not obj:
    15811571            return 0
    15821572
    1583     if key == None:
     1573    if not key:
    15841574        keys = obj.getExtraDataKeys()
    15851575    else:
     
    16051595    global g_fVerbose
    16061596    if len(args) > 1:
    1607         g_fVerbose = (args[1]=='on')
     1597        g_fVerbose = args[1]=='on'
    16081598    else:
    16091599        g_fVerbose = not g_fVerbose
     
    16131603    global g_fHasColors
    16141604    if len(args) > 1:
    1615         g_fHasColors = (args[1] == 'on')
     1605        g_fHasColors = args[1] == 'on'
    16161606    else:
    16171607        g_fHasColors = not g_fHasColors
     
    16491639
    16501640    print(colCat(ctx, "Network interfaces:"))
    1651     for ni in 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))
    16531643
    16541644    print(colCat(ctx, "DVD drives:"))
    1655     for dd in ctx['global'].getArray(host, 'DVDDrives'):
    1656         print("  %s - %s" % (dd.name, dd.description))
     1645    for drive in ctx['global'].getArray(host, 'DVDDrives'):
     1646        print("  %s - %s" % (drive.name, drive.description))
    16571647
    16581648    print(colCat(ctx, "Floppy drives:"))
    1659     for dd in ctx['global'].getArray(host, 'floppyDrives'):
    1660         print("  %s - %s" % (dd.name, dd.description))
     1649    for drive in ctx['global'].getArray(host, 'floppyDrives'):
     1650        print("  %s - %s" % (drive.name, drive.description))
    16611651
    16621652    print(colCat(ctx, "USB devices:"))
    1663     for ud in ctx['global'].getArray(host, 'USBDevices'):
    1664         printHostUsbDev(ctx, ud)
     1653    for usbdev in ctx['global'].getArray(host, 'USBDevices'):
     1654        printHostUsbDev(ctx, usbdev)
    16651655
    16661656    if ctx['perf']:
     
    17391729
    17401730def getAdapterType(ctx, natype):
    1741     if (natype == ctx['global'].constants.NetworkAdapterType_Am79C970A or
    1742         natype == ctx['global'].constants.NetworkAdapterType_Am79C973 or
    1743         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)):
    17441734        return "pcnet"
    1745     elif (natype == ctx['global'].constants.NetworkAdapterType_I82540EM or
    1746           natype == ctx['global'].constants.NetworkAdapterType_I82545EM or
    1747           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)):
    17481738        return "e1000"
    1749     elif (natype == ctx['global'].constants.NetworkAdapterType_Virtio):
     1739    if natype == ctx['global'].constants.NetworkAdapterType_Virtio:
    17501740        return "virtio"
    1751     elif (natype == ctx['global'].constants.NetworkAdapterType_Null):
     1741    if natype == ctx['global'].constants.NetworkAdapterType_Null:
    17521742        return None
    1753     else:
    1754         raise Exception("Unknown adapter type: "+natype)
    1755 
     1743    raise Exception("Unknown adapter type: "+natype)
    17561744
    17571745def portForwardCmd(ctx, args):
     
    18281816        if len(data) == 0:
    18291817            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)
    18331821            if len(match) > 0:
    1834                 for mt in 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)
    18371825        uOffset += len(data)
    18381826
     
    18611849        if len(data) == 0:
    18621850            break
    1863         d = str(data).split("\n")
    1864         for s in d:
     1851        buf = str(data).split("\n")
     1852        for line in buf:
    18651853            if active:
    1866                 print(s)
     1854                print(line)
    18671855                if context == 0:
    18681856                    active = False
     
    18701858                    context = context - 1
    18711859                continue
    1872             match = ere.findall(s)
     1860            match = ere.findall(line)
    18731861            if len(match) > 0:
    18741862                active = True
    18751863                context = 50
    1876                 print(s)
     1864                print(line)
    18771865        uOffset += len(data)
    18781866
     
    18991887        print("usage: runScript <script>")
    19001888        return 0
     1889
    19011890    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()
    19031908    except IOError as e:
    19041909        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
    19231911    return 0
    19241912
     
    21832171            time.sleep(0.3)
    21842172            continue
    2185         if  ch == '^' or  ch == '|' or ch == '$' or ch == '_':
     2173        if ch in ('^', '|', '$', '_'):
    21862174            if ch == '^':
    21872175                ch = 'LCTR'
     
    22432231    if verbose:
    22442232        return ": "+uuid
    2245     else:
    2246         return ""
     2233    return ""
    22472234
    22482235def asSize(val, inBytes):
    22492236    if inBytes:
    22502237        return int(val)/(1024*1024)
    2251     else:
    2252         return int(val)
     2238    return int(val)
    22532239
    22542240def listMediaCmd(ctx, args):
     
    22862272
    22872273    host = ctx['vb'].host
    2288     for ud in ctx['global'].getArray(host, 'USBDevices'):
    2289         printHostUsbDev(ctx, ud)
     2274    for usbdev in ctx['global'].getArray(host, 'USBDevices'):
     2275        printHostUsbDev(ctx, usbdev)
    22902276
    22912277    return 0
    22922278
    22932279def findDevOfType(ctx, mach, devtype):
    2294     atts = 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]
    22982284    return [None, 0, 0]
    22992285
     
    23612347
    23622348def detachVmDevice(ctx, mach, args):
    2363     atts = ctx['global'].getArray(mach, 'mediumAttachments')
     2349    attachments = ctx['global'].getArray(mach, 'mediumAttachments')
    23642350    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)
    23692355
    23702356def detachMedium(ctx, mid, medium):
     
    25762562    [name, bus, ctrltype] = args
    25772563    ctr = mach.addStorageController(name, bus)
    2578     if ctrltype != None:
     2564    if ctrltype:
    25792565        ctr.controllerType = ctrltype
    25802566
     
    25862572    if len(args) > 4:
    25872573        ctrltype = enumFromString(ctx, 'StorageControllerType', args[4])
    2588         if ctrltype == None:
     2574        if not ctrltype:
    25892575            print("Controller type %s unknown" % (args[4]))
    25902576            return 0
     
    26742660    persistent = False
    26752661    if len(args) > 4:
    2676         for a in args[4:]:
    2677             if a == 'writable':
     2662        for cur_arg in args[4:]:
     2663            if cur_arg == 'writable':
    26782664                writable = True
    2679             if a == 'persistent':
     2665            if cur_arg == 'persistent':
    26802666                persistent = True
    26812667    if persistent:
     
    26952681    name = args[2]
    26962682    found = False
    2697     for sf in ctx['global'].getArray(mach, 'sharedFolders'):
    2698         if sf.name == name:
     2683    for sharedfolder in ctx['global'].getArray(mach, 'sharedFolders'):
     2684        if sharedfolder.name == name:
    26992685            cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeSharedFolder(name), [])
    27002686            found = True
     
    27572743    return 0
    27582744
    2759 def natAlias(_ctx, _mach, _nicnum, nat, args=[]):
     2745def natAlias(_ctx, _mach, _nicnum, nat, args=None):
    27602746    """This command shows/alters NAT's alias settings.
    27612747    usage: nat <vmname|uuid> <nicnum> alias [default|[log] [proxyonly] [sameports]]
     
    27832769                msg += '%s: %s' % (aliasmode, 'off')
    27842770        return (0, [msg])
    2785     else:
    2786         nat.aliasMode = 0
    2787         if 'default' not in args:
    2788             for a in range(1, len(args)):
    2789                 if args[a] not in alias:
    2790                     print('Invalid alias mode: ' + args[a])
    2791                     print(natAlias.__doc__)
    2792                     return (1, None)
    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]]
    27942780    return (0, None)
    27952781
    27962782def natSettings(_ctx, _mach, _nicnum, nat, args):
    2797     """This command shows/alters NAT settings.
     2783    """
     2784    This command shows/alters NAT settings.
    27982785    usage: nat <vmname|uuid> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
    27992786    mtu - set mtu <= 16000
     
    28102797        msg = 'mtu:%s socket(snd:%s, rcv:%s) tcpwnd(snd:%s, rcv:%s)' % (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd)
    28112798        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]))
    28152806            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]))
    28282815    return (0, None)
    28292816
     
    28392826        msg = 'passdomain:%s, proxy:%s, usehostresolver:%s' % (yesno[int(nat.DNSPassDomain)], yesno[int(nat.DNSProxy)], yesno[int(nat.DNSUseHostResolver)])
    28402827        return (0, [msg])
    2841     else:
    2842         nat.DNSPassDomain = 'passdomain' in args
    2843         nat.DNSProxy = 'proxy' in args
    2844         nat.DNSUseHostResolver = 'usehostresolver' in args
     2828
     2829    nat.DNSPassDomain = 'passdomain' in args
     2830    nat.DNSProxy = 'proxy' in args
     2831    nat.DNSUseHostResolver = 'usehostresolver' in args
    28452832    return (0, None)
    28462833
     
    28612848            while server.count('.') != 3:
    28622849                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)
    28652852        prefix = nat.TFTPPrefix
    28662853        if prefix is None:
     
    28712858        msg = 'server:%s, prefix:%s, bootfile:%s' % (server, prefix, bootfile)
    28722859        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)
    28862872    return (0, None)
    28872873
     
    28982884        proto = {0: 'udp', 1: 'tcp'}
    28992885        msg = []
    2900         pfs = 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(', ')
    29032889            msg.append('%s: %s %s:%s => %s:%s' % (pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
    29042890        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])
    29242909        }
    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']()
    29322918    return (0, None)
    29332919
     
    29422928            msg = '10.0.%d.0/24' % (int(nicnum) + 2)
    29432929        return (0, [msg])
    2944     else:
    2945         (addr, mask) = args[1].split('/')
    2946         if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
    2947             print('Invalid arguments')
    2948             return (1, None)
    2949         nat.network = args[1]
     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]
    29502936    return (0, None)
    29512937
     
    30012987    adapter = mach.getNetworkAdapter(nicnum)
    30022988    natEngine = adapter.NATEngine
    3003     (rc, report) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
     2989    (rc, reports) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
    30042990    if rosession == 0:
    30052991        if rc == 0:
    30062992            mach.saveSettings()
    30072993        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)
    30112997            print(msg)
    30122998    return 0
     
    30153001    if len(args) == 1:
    30163002        yesno = {0: 'off', 1: 'on'}
    3017         r = yesno[int(adapter.__getattr__(attr))]
    3018         return (0, r)
    3019     else:
    3020         yesno = {'off' : 0, 'on' : 1}
    3021         if args[1] not in yesno:
    3022             print('%s isn\'t acceptable, please choose %s' % (args[1], list(yesno.keys())))
    3023             return (1, None)
    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]])
    30253011    return (0, None)
    30263012
     
    30293015    usage: nic <vmname|uuid> <nicnum> trace [on|off [file]]
    30303016    '''
    3031     (rc, r) = nicSwitchOnOff(adapter, 'traceEnabled', args)
     3017    (rc, resp) = nicSwitchOnOff(adapter, 'traceEnabled', args)
    30323018    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:
    30363022        adapter.traceFile = args[2]
    30373023    return (0, None)
     
    30393025def nicLineSpeedSubCmd(_ctx, _vm, _nicnum, adapter, args):
    30403026    if len(args) == 1:
    3041         r = '%d kbps'% (adapter.lineSpeed)
    3042         return (0, r)
    3043     else:
    3044         if not args[1].isdigit():
    3045             print('%s isn\'t a number' % (args[1]))
    3046             return (1, None)
    3047         adapter.lineSpeed = int(args[1])
     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])
    30483034    return (0, None)
    30493035
     
    30703056                return (0, str(key))
    30713057        return (1, None)
    3072     else:
    3073         nictypes = ctx['const'].all_values('NetworkAdapterType')
    3074         if args[1] not in list(nictypes.keys()):
    3075             print('%s not in acceptable values (%s)' % (args[1], list(nictypes.keys())))
    3076             return (1, None)
    3077         adapter.adapterType = nictypes[args[1]]
     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]]
    30783064    return (0, None)
    30793065
     
    30923078            ctx['global'].constants.NetworkAttachmentType_Generic: ('Generic', ''),
    30933079        }
    3094         if type(adapter.attachmentType) != int:
     3080        if not isinstance(adapter.attachmentType, int):
    30953081            t = str(adapter.attachmentType)
    30963082        else:
    30973083            t = adapter.attachmentType
    3098         (r, p) = nicAttachmentType[t]
    3099         return (0, 'attachment:%s, name:%s' % (r, p))
    3100     else:
    3101         nicAttachmentType = {
    3102             'Null': {
    3103                 'v': lambda: len(args) == 2,
    3104                 'p': lambda: 'do nothing',
    3105                 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Null},
    3106             'NAT': {
    3107                 'v': lambda: len(args) == 2,
    3108                 'p': lambda: 'do nothing',
    3109                 'f': lambda: ctx['global'].constants.NetworkAttachmentType_NAT},
    3110             'Bridged': {
    3111                 'v': lambda: len(args) == 3,
    3112                 'p': lambda: adapter.__setattr__('bridgedInterface', args[2]),
    3113                 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Bridged},
    3114             'Internal': {
    3115                 'v': lambda: len(args) == 3,
    3116                 'p': lambda: adapter.__setattr__('internalNetwork', args[2]),
    3117                 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Internal},
    3118             'HostOnly': {
    3119                 'v': lambda: len(args) == 2,
    3120                 'p': lambda: adapter.__setattr__('hostOnlyInterface', args[2]),
    3121                 'f': lambda: ctx['global'].constants.NetworkAttachmentType_HostOnly},
    3122             # @todo implement setting the properties of a generic attachment
    3123             'Generic': {
    3124                 'v': lambda: len(args) == 3,
    3125                 'p': lambda: 'do nothing',
    3126                 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Generic}
    3127         }
    3128         if args[1] not in list(nicAttachmentType.keys()):
    3129             print('%s not in acceptable values (%s)' % (args[1], list(nicAttachmentType.keys())))
    3130             return (1, None)
    3131         if not nicAttachmentType[args[1]]['v']():
    3132             print(nicAttachmentType.__doc__)
    3133             return (1, None)
    3134         nicAttachmentType[args[1]]['p']()
    3135         adapter.attachmentType = nicAttachmentType[args[1]]['f']()
     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']()
    31363122    return (0, None)
    31373123
     
    31613147        return 0
    31623148
    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
    31693154    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 0
     3155       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
    31733158    nicnum = int(args[2])
    31743159    cmdargs = args[3:]
    31753160    func = args[3]
    31763161    session = None
    3177     session = ctx['global'].openMachineSession(vm, fPermitSharing=True)
    3178     vm = session.machine
    3179     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)
    31813166    if rc == 0:
    3182         vm.saveSettings()
     3167        mach.saveSettings()
    31833168    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))
    31853170    session.unlockMachine()
    31863171    return 0
     
    32573242def lspci(ctx, console):
    32583243    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)))
    32623247
    32633248    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)))
    32673252        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)))
    32693254    return
    32703255
     
    34303415def runCommandArgs(ctx, args):
    34313416    c = args[0]
    3432     if aliases.get(c, None) != None:
     3417    if aliases.get(c, None):
    34333418        c = aliases[c]
    3434     ci = commands.get(c, None)
    3435     if ci == None:
     3419    cmd_internal = commands.get(c, None)
     3420    if not cmd_internal:
    34363421        print("Unknown command: '%s', type 'help' for list of known commands" % (c))
    34373422        return 0
     
    34403425            print("First connect to remote server with %s command." % (colored('connect', 'blue')))
    34413426            return 0
    3442     return ci[1](ctx, args)
     3427    return cmd_internal[1](ctx, args)
    34433428
    34443429
     
    34693454    if not os.path.isfile(filename):
    34703455        return
    3471     d = {}
     3456    extDict = {}
    34723457    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()):
    34753462            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]
    34783465    except:
    34793466        print("Error loading user extensions from %s" % (filename))
     
    35003487            return os.path.join(os.environ['VBOX_USER_HOME'])
    35013488        return os.path.join(os.path.expanduser("~"), ".VirtualBox")
    3502     else:
    3503         return ctx['vb'].homeFolder
     3489
     3490    return ctx['vb'].homeFolder
    35043491
    35053492def interpret(ctx):
     
    35443531    if g_sCmd is not None:
    35453532        cmds = g_sCmd.split(';')
    3546     it = cmds.__iter__()
     3533    itCmd = iter(cmds)
    35473534
    35483535    while True:
     
    35513538                cmd = 'runScript %s'% (g_sScriptFile)
    35523539            elif g_sCmd is not None:
    3553                 cmd = next(it)
     3540                cmd = next(itCmd)
    35543541            else:
    35553542                if sys.version_info[0] <= 2:
     
    35583545                    cmd = input(ctx['prompt'])
    35593546            done = runCommand(ctx, cmd)
    3560             if done != 0: break
     3547            if done != 0:
     3548                break
    35613549            if g_fBatchMode:
    35623550                break
Note: See TracChangeset for help on using the changeset viewer.

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