Index: trunk/src/VBox/Frontends/VBoxShell/vboxshell.py
===================================================================
--- trunk/src/VBox/Frontends/VBoxShell/vboxshell.py	(revision 102871)
+++ trunk/src/VBox/Frontends/VBoxShell/vboxshell.py	(revision 102872)
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
+# pylint: disable=too-many-lines
 # $Id$
 
@@ -52,9 +53,9 @@
 import traceback
 import shlex
+import tempfile
 import time
 import re
 import platform
 from optparse import OptionParser
-from pprint import pprint
 
 
@@ -251,7 +252,26 @@
     return colored(str(mbyte)+'M', 'red')
 
-def createVm(ctx, name, kind):
+def platformArchFromString(ctx, arch):
+    if     arch == 'x86' \
+        or arch == 'x86_64' \
+        or arch == 'x64':
+        return ctx['global'].constants.PlatformArchitecture_x86
+    elif    arch == 'arm' \
+         or arch == 'aarch32' \
+         or arch == 'aarch64':
+        return ctx['global'].constants.PlatformArchitecture_ARM
+    return ctx['global'].constants.PlatformArchitecture_None
+
+def createVm(ctx, name, arch, kind):
     vbox = ctx['vb']
-    mach = vbox.createMachine("", name, [], kind, "")
+    enmArch = platformArchFromString(ctx, arch)
+    if enmArch == ctx['global'].constants.PlatformArchitecture_None:
+        print("wrong / invalid platform architecture specified!")
+        return
+    sFlags = ''
+    sCipher = '' ## @todo No encryption support here yet!
+    sPasswordID = ''
+    sPassword = ''
+    mach = vbox.createMachine("", name, enmArch, [], kind, sFlags, sCipher, sPasswordID, sPassword)
     mach.saveSettings()
     print("created machine with UUID", mach.id)
@@ -275,5 +295,4 @@
 
 def startVm(ctx, mach, vmtype):
-    vbox = ctx['vb']
     perf = ctx['perf']
     session = ctx['global'].getSessionObject()
@@ -341,6 +360,6 @@
         print(metric['name'], metric['values_as_string'])
 
-def guestExec(ctx, machine, console, cmds):
-    exec(cmds)
+def guestExec(_ctx, _machine, _console, cmds):
+    exec(cmds) # pylint: disable=exec-used
 
 def printMouseEvent(_ctx, mev):
@@ -412,5 +431,4 @@
             except:
                 traceback.print_exc()
-            pass
 
     if active:
@@ -438,5 +456,5 @@
     except:
         traceback.print_exc()
-        pass
+
     if listener and registered:
         eventSource.unregisterListener(listener)
@@ -477,5 +495,5 @@
     # we create an aggregated event source to listen for multiple event sources (keyboard and mouse in our case)
     agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource])
-    demo = open(filename, 'w')
+    demo = open(filename, 'w', encoding='utf-8')
     header = "VM=" + console.machine.name + "\n"
     demo.write(header)
@@ -495,5 +513,5 @@
     except:
         traceback.print_exc()
-        pass
+
     demo.close()
     if listener and registered:
@@ -502,5 +520,5 @@
 
 def playbackDemo(ctx, console, filename, dur):
-    demo = open(filename, 'r')
+    demo = open(filename, 'r', encoding='utf-8')
 
     if dur == -1:
@@ -554,47 +572,18 @@
     except:
         traceback.print_exc()
-        pass
+
     demo.close()
 
-
-def takeScreenshotOld(_ctx, console, args):
-    from PIL import Image
+def takeScreenshot(ctx, console, args):
     display = console.display
     if len(args) > 0:
         f = args[0]
     else:
-        f = "/tmp/screenshot.png"
+        f = os.path.join(tempfile.gettempdir(), "screenshot.png")
     if len(args) > 3:
         screen = int(args[3])
     else:
         screen = 0
-    (fbw, fbh, _fbbpp, fbx, fby, _) = display.getScreenResolution(screen)
-    if len(args) > 1:
-        w = int(args[1])
-    else:
-        w = fbw
-    if len(args) > 2:
-        h = int(args[2])
-    else:
-        h = fbh
-
-    print("Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f))
-    data = display.takeScreenShotToArray(screen, w, h, ctx['const'].BitmapFormat_RGBA)
-    size = (w, h)
-    mode = "RGBA"
-    im = Image.frombuffer(mode, size, str(data), "raw", mode, 0, 1)
-    im.save(f, "PNG")
-
-def takeScreenshot(_ctx, console, args):
-    display = console.display
-    if len(args) > 0:
-        f = args[0]
-    else:
-        f = "/tmp/screenshot.png"
-    if len(args) > 3:
-        screen = int(args[3])
-    else:
-        screen = 0
-    (fbw, fbh, _fbbpp, fbx, fby, _) = display.getScreenResolution(screen)
+    (fbw, fbh, _fbbpp, _fbx, _fby, _) = display.getScreenResolution(screen)
     if len(args) > 1:
         w = int(args[1])
@@ -638,4 +627,7 @@
 def guestStats(ctx, console, args):
     guest = console.guest
+    if not guest:
+        print("Guest is not in a running state")
+        return
     # we need to set up guest statistics
     if len(args) > 0 :
@@ -691,4 +683,7 @@
 def ginfo(ctx, console, _args):
     guest = console.guest
+    if not guest:
+        print("Guest is not in a running state")
+        return
     if guest.additionsRunLevel != ctx['const'].AdditionsRunLevelType_None:
         print("Additions active, version %s" % (guest.additionsVersion))
@@ -715,5 +710,4 @@
     session = None
     try:
-        vbox = ctx['vb']
         session = ctx['global'].openMachineSession(mach, fPermitSharing=True)
     except Exception as e:
@@ -830,5 +824,5 @@
         return matches
     def apply(self, cmd):
-        exec(cmd, {'obj':self.obj, 'node':self, 'ctx':self.getCtx()}, {})
+        exec(cmd, {'obj':self.obj, 'node':self, 'ctx':self.getCtx()}, {}) # pylint: disable=exec-used
     def getCtx(self):
         if hasattr(self, 'ctx'):
@@ -874,5 +868,5 @@
     def __init__(self, parent, mach):
         XPathNodeHolder.__init__(self, parent, mach, 'nics', XPathNodeVM, 'nics')
-        self.maxNic = self.getCtx()['vb'].systemProperties.getMaxNetworkAdapters(self.obj.chipsetType)
+        self.maxNic = mach.platform.properties.getMaxNetworkAdapters(mach.platform.chipsetType)
     def enum(self):
         children = []
@@ -915,9 +909,9 @@
 def argsToMach(ctx, args):
     if len(args) < 2:
-        print("usage: %s [vmname|uuid]" % (args[0]))
+        print("usage: %s <vmname|uuid>" % (args[0]))
         return None
     uuid = args[1]
     mach = machById(ctx, uuid)
-    if mach == None:
+    if not mach:
         print("Machine '%s' is unknown, use list command to find available machines" % (uuid))
     return mach
@@ -973,8 +967,8 @@
 def infoCmd(ctx, args):
     if len(args) < 2:
-        print("usage: info [vmname|uuid]")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: info <vmname|uuid>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     try:
@@ -987,5 +981,5 @@
     print("  ID [n/a]: %s" % (mach.id))
     print("  OS Type [via OSTypeId]: %s" % (vmos.description if vmos is not None else mach.OSTypeId))
-    print("  Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx, "FirmwareType", mach.firmwareType), mach.firmwareType))
+    print("  Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx, "FirmwareType", mach.firmwareSettings.firmwareType), mach.firmwareSettings.firmwareType))
     print()
     print("  CPUs [CPUCount]: %d" % (mach.CPUCount))
@@ -993,5 +987,5 @@
     print("  VRAM [VRAMSize]: %dM" % (mach.graphicsAdapter.VRAMSize))
     print("  Monitors [monitorCount]: %d" % (mach.graphicsAdapter.monitorCount))
-    print("  Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx, "ChipsetType", mach.chipsetType), mach.chipsetType))
+    print("  Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx, "ChipsetType", mach.platform.chipsetType), mach.platform.chipsetType))
     print()
     print("  Clipboard mode [clipboardMode]: %s (%s)" % (asEnumElem(ctx, "ClipboardMode", mach.clipboardMode), mach.clipboardMode))
@@ -1001,21 +995,21 @@
         print("  Teleport target on port %d (%s)" % (mach.teleporterPort, mach.teleporterPassword))
         print()
-    bios = mach.BIOSSettings
-    print("  ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(bios.ACPIEnabled)))
-    print("  APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(bios.IOAPICEnabled)))
-    hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
-    print("  Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled))
-    hwVirtVPID = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID)
-    print("  VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID))
-    hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging)
-    print("  Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging))
+    print("  ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(mach.firmwareSettings.ACPIEnabled)))
+    print("  APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(mach.firmwareSettings.IOAPICEnabled)))
+    if mach.platform.architecture == ctx['global'].constants.PlatformArchitecture_x86:
+        hwVirtEnabled = mach.platform.x86.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
+        print("  Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled))
+        hwVirtVPID = mach.platform.x86.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID)
+        print("  VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID))
+        hwVirtNestedPaging = mach.platform.x86.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging)
+        print("  Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging))
+        print("  HPET [HPETEnabled]: %s" % (asState(mach.platform.x86.HPETEnabled)))
 
     print("  Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.graphicsAdapter.accelerate3DEnabled))
     print("  Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.graphicsAdapter.accelerate2DVideoEnabled))
-
-    print("  Use universal time [RTCUseUTC]: %s" % (asState(mach.RTCUseUTC)))
-    print("  HPET [HPETEnabled]: %s" % (asState(mach.HPETEnabled)))
-    if mach.audioAdapter.enabled:
-        print("  Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx, "AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx, "AudioDriverType",  mach.audioAdapter.audioDriver)))
+    print("  Use universal time [RTCUseUTC]: %s" % (asState(mach.platform.RTCUseUTC)))
+    audioAdp = mach.audioSettings.adapter
+    if audioAdp.enabled:
+        print("  Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx, "AudioControllerType", audioAdp.audioController), asEnumElem(ctx, "AudioDriverType",  audioAdp.audioDriver)))
     print("  CPU hotplugging [CPUHotPlugEnabled]: %s" % (asState(mach.CPUHotPlugEnabled)))
 
@@ -1094,8 +1088,8 @@
 def startCmd(ctx, args):
     if len(args) < 2:
-        print("usage: start name <frontend>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: start <vmname|uuid> <frontend>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     if len(args) > 2:
@@ -1107,9 +1101,10 @@
 
 def createVmCmd(ctx, args):
-    if len(args) != 3:
-        print("usage: createvm name ostype")
+    if len(args) != 4:
+        print("usage: createvm <name> <arch> <ostype>")
         return 0
     name = args[1]
-    oskind = args[2]
+    arch = args[2]
+    oskind = args[3]
     try:
         ctx['vb'].getGuestOSType(oskind)
@@ -1117,36 +1112,88 @@
         print('Unknown OS type:', oskind)
         return 0
-    createVm(ctx, name, oskind)
+    createVm(ctx, name, arch, oskind)
     return 0
 
 def ginfoCmd(ctx, args):
     if len(args) < 2:
-        print("usage: ginfo [vmname|uuid]")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: ginfo <vmname|uuid>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'ginfo', '')
     return 0
 
-def execInGuest(ctx, console, args, env, user, passwd, tmo, inputPipe=None, outputPipe=None):
+def gstctlPrintOk(_ctx, string):
+    return print(colored(string, 'green'))
+
+def gstctlPrintErr(_ctx, string):
+    return print(colored(string, 'red'))
+
+def execInGuest(ctx, console, args, env, user, passwd, tmo, inputPipe=None, _outputPipe=None):
     if len(args) < 1:
         print("exec in guest needs at least program name")
         return
     guest = console.guest
-    guestSession = guest.createSession(user, passwd, "", "vboxshell guest exec")
     # shall contain program name as argv[0]
     gargs = args
-    print("executing %s with args %s as %s" % (args[0], gargs, user))
-    flags = 0
+    if g_fVerbose:
+        gstctlPrintOk(ctx, "starting guest session for user '%s' (password '%s')" % (user, passwd))
+    else:
+        gstctlPrintOk(ctx, ("starting guest session for user '%s' ..." % (user)))
+    try:
+        guestSession = guest.createSession(user, passwd, "", "vboxshell guest exec")
+        guestSession.waitForArray([ ctx['global'].constants.GuestSessionWaitForFlag_Start ], 30 * 1000)
+    except Exception as e:
+        gstctlPrintErr(ctx, "starting guest session failed:")
+        printErr(ctx, e)
+        return 1
+    if g_fVerbose:
+        gstctlPrintOk(ctx, "guest session %d started" % guestSession.id)
+    aProcCreateFlags = [ ctx['global'].constants.ProcessCreateFlag_WaitForStdOut, \
+                         ctx['global'].constants.ProcessCreateFlag_WaitForStdErr ]
     if inputPipe is not None:
-        flags = 1 # set WaitForProcessStartOnly
-    print(args[0])
-    process = guestSession.processCreate(args[0], gargs, env, [], tmo)
-    print("executed with pid %d" % (process.PID))
-    if pid != 0:
+        aProcCreateFlags.extend([ ctx['global'].constants.ProcessCreateFlag_WaitForStdIn ])
+    if g_fVerbose:
+        gstctlPrintOk(ctx, "starting process '%s' with args '%s' as user '%s' (password '%s')" % (args[0], gargs, user, passwd))
+    process = guestSession.processCreate(args[0], gargs, '', env, aProcCreateFlags, tmo)
+    try:
+        waitResult = process.waitForArray([ ctx['global'].constants.ProcessWaitForFlag_Start ], 30 * 1000)
+    except Exception as e:
+        gstctlPrintErr(ctx, "waiting for guest process start failed:")
+        printErr(ctx, e)
+        return 1
+    if waitResult != ctx['global'].constants.ProcessWaitResult_Start:
+        gstctlPrintErr(ctx, "process start failed: got wait result %d, expected %d" \
+                       % (waitResult, ctx['global'].constants.ProcessWaitResult_Start) )
+        return 1
+    procStatus = process.status
+    if procStatus != ctx['global'].constants.ProcessStatus_Started:
+        gstctlPrintErr(ctx, "process start failed: got process status %d, expected %d" \
+                       % (procStatus, ctx['global'].constants.ProcessStatus_Started) )
+        return 1
+    if g_fVerbose:
+        gstctlPrintOk(ctx, "process %d started" % (process.PID))
+    if process.PID != 0:
         try:
-            while True:
-                if inputPipe is not None:
+            fCompleted  = False
+            fReadStdOut = False
+            fReadStdErr = False
+            while not fCompleted:
+                waitResult = process.waitForArray([ ctx['global'].constants.ProcessWaitForFlag_Terminate, \
+                                                    ctx['global'].constants.ProcessWaitForFlag_StdOut, \
+                                                    ctx['global'].constants.ProcessWaitForFlag_StdErr ], 1000)
+                if waitResult == ctx['global'].constants.ProcessWaitResult_WaitFlagNotSupported:
+                    fReadStdOut = True
+                    fReadStdErr = True
+                elif waitResult == ctx['global'].constants.ProcessWaitResult_Terminate:
+                    fCompleted = True
+                    break
+                elif waitResult == ctx['global'].constants.ProcessWaitResult_Timeout:
+                    gstctlPrintErr(ctx, "timeout while waiting for process")
+                    break
+                else:
+                    gstctlPrintErr(ctx, "got unhandled wait result %d" % (waitResult))
+                if inputPipe:
                     indata = inputPipe(ctx)
                     if indata is not None:
@@ -1154,5 +1201,5 @@
                         off = 0
                         while write > 0:
-                            w = guest.setProcessInput(pid, 0, 10*1000, indata[off:])
+                            w = process.write(0, 10*1000, indata[off:])
                             off = off + w
                             write = write - w
@@ -1160,33 +1207,43 @@
                         # EOF
                         try:
-                            guest.setProcessInput(pid, 1, 10*1000, " ")
+                            process.write(0, 10*1000, " ")
                         except:
                             pass
-                data = guest.getProcessOutput(pid, 0, 10000, 4096)
-                if data and len(data) > 0:
-                    sys.stdout.write(data)
-                    continue
-                progress.waitForCompletion(100)
+                if fReadStdOut:
+                    data = process.read(1, 64 * 1024, 10*1000)
+                    if data and len(data):
+                        sys.stdout.write(bytes(data).decode('utf-8'))
+                    fReadStdOut = False
+                if fReadStdErr:
+                    data = process.read(2, 64 * 1024, 10*1000)
+                    if data and len(data):
+                        sys.stderr.write(bytes(data).decode('utf-8'))
+                    fReadStdErr = False
                 ctx['global'].waitForEvents(0)
-                data = guest.getProcessOutput(pid, 0, 0, 4096)
-                if data and len(data) > 0:
-                    if outputPipe is not None:
-                        outputPipe(ctx, data)
-                    else:
-                        sys.stdout.write(data)
-                    continue
-                if progress.completed:
-                    break
+
+            if fCompleted:
+                exitCode = process.exitCode
+                if exitCode == 0:
+                    gstctlPrintOk(ctx, "process exit code: %d" % (exitCode))
+                else:
+                    gstctlPrintErr(ctx, "process exit code: %d" % (exitCode))
 
         except KeyboardInterrupt:
             print("Interrupted.")
             ctx['interrupt'] = True
-            if progress.cancelable:
-                progress.cancel()
-        (_reason, code, _flags) = guest.getProcessStatus(pid)
-        print("Exit code: %d" % (code))
-        return 0
-    else:
-        reportError(ctx, progress)
+
+        except Exception as e:
+            printErr(ctx, e)
+
+    if guestSession:
+        try:
+            if g_fVerbose:
+                gstctlPrintOk(ctx, "closing guest session ...")
+            guestSession.close()
+        except:
+            printErr(ctx, e)
+
+    return 0
+
 
 def copyToGuest(ctx, console, args, user, passwd):
@@ -1199,8 +1256,7 @@
 
 def nh_raw_input(prompt=""):
-    stream = sys.stdout
-    prompt = str(prompt)
     if prompt:
-        stream.write(prompt)
+        sys.stdout.write(prompt)
+        sys.stdout.flush()
     line = sys.stdin.readline()
     if not line:
@@ -1210,9 +1266,11 @@
     return line
 
-
 def getCred(_ctx):
     import getpass
     user = getpass.getuser()
-    user_inp = nh_raw_input("User (%s): " % (user))
+    if user:
+        user_inp = nh_raw_input("User (%s): " % (user))
+    else:
+        user_inp = nh_raw_input("User: ")
     if len(user_inp) > 0:
         user = user_inp
@@ -1223,8 +1281,8 @@
 def gexecCmd(ctx, args):
     if len(args) < 2:
-        print("usage: gexec [vmname|uuid] command args")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: gexec <vmname|uuid> command args")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     gargs = args[2:]
@@ -1237,8 +1295,8 @@
 def gcopyCmd(ctx, args):
     if len(args) < 2:
-        print("usage: gcopy [vmname|uuid] host_path guest_path")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: gcopy <vmname|uuid> host_path guest_path")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     gargs = args[2:]
@@ -1256,8 +1314,8 @@
 def gpipeCmd(ctx, args):
     if len(args) < 4:
-        print("usage: gpipe [vmname|uuid] hostProgram guestProgram, such as gpipe linux  '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: gpipe <vmname|uuid> hostProgram guestProgram, such as gpipe linux  '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     hcmd = args[2]
@@ -1280,5 +1338,5 @@
 def removeVmCmd(ctx, args):
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     removeVm(ctx, mach)
@@ -1287,5 +1345,5 @@
 def pauseCmd(ctx, args):
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'pause', '')
@@ -1294,5 +1352,5 @@
 def powerdownCmd(ctx, args):
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'powerdown', '')
@@ -1301,5 +1359,5 @@
 def powerbuttonCmd(ctx, args):
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'powerbutton', '')
@@ -1308,5 +1366,5 @@
 def resumeCmd(ctx, args):
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'resume', '')
@@ -1315,5 +1373,5 @@
 def saveCmd(ctx, args):
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'save', '')
@@ -1322,5 +1380,5 @@
 def statsCmd(ctx, args):
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'stats', '')
@@ -1329,8 +1387,8 @@
 def guestCmd(ctx, args):
     if len(args) < 3:
-        print("usage: guest name commands")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: guest <vmname|uuid> commands")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     if mach.state != ctx['const'].MachineState_Running:
@@ -1342,8 +1400,8 @@
 def screenshotCmd(ctx, args):
     if len(args) < 2:
-        print("usage: screenshot vm <file> <width> <height> <monitor>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: screenshot <vmname|uuid> <file> <width> <height> <monitor>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'screenshot', args[2:])
@@ -1352,8 +1410,8 @@
 def teleportCmd(ctx, args):
     if len(args) < 3:
-        print("usage: teleport name host:port <password>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: teleport <vmname|uuid> host:port <password>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'teleport', args[2:])
@@ -1371,8 +1429,8 @@
 def openportalCmd(ctx, args):
     if len(args) < 3:
-        print("usage: openportal name port <password>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: openportal <vmname|uuid> port <password>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     port = int(args[2])
@@ -1388,8 +1446,8 @@
 def closeportalCmd(ctx, args):
     if len(args) < 2:
-        print("usage: closeportal name")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: closeportal <vmname|uuid>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     if mach.teleporterEnabled:
@@ -1399,8 +1457,8 @@
 def gueststatsCmd(ctx, args):
     if len(args) < 2:
-        print("usage: gueststats name <check interval>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: gueststats <vmname|uuid> <check interval>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'gueststats', args[2:])
@@ -1419,8 +1477,8 @@
 def plugcpuCmd(ctx, args):
     if len(args) < 2:
-        print("usage: plugcpu name cpuid")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: plugcpu <vmname|uuid> <cpuid>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     if str(mach.sessionState) != str(ctx['const'].SessionState_Locked):
@@ -1433,8 +1491,8 @@
 def unplugcpuCmd(ctx, args):
     if len(args) < 2:
-        print("usage: unplugcpu name cpuid")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: unplugcpu <vmname|uuid> <cpuid>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     if str(mach.sessionState) != str(ctx['const'].SessionState_Locked):
@@ -1448,12 +1506,12 @@
     expr = 'mach.'+args[0]+' = '+args[1]
     print("Executing", expr)
-    exec(expr)
+    exec(expr) # pylint: disable=exec-used
 
 def setvarCmd(ctx, args):
     if len(args) < 4:
-        print("usage: setvar [vmname|uuid] expr value")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: setvar <vmname|uuid> <expr> <value>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     cmdClosedVm(ctx, mach, setvar, args[2:])
@@ -1480,5 +1538,5 @@
 
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdClosedVm(ctx, mach, setvmextra, [key, value])
@@ -1516,5 +1574,5 @@
     return 1
 
-def aliasCmd(ctx, args):
+def aliasCmd(_ctx, args):
     if len(args) == 3:
         aliases[args[1]] = args[2]
@@ -1525,5 +1583,5 @@
     return 0
 
-def verboseCmd(ctx, args):
+def verboseCmd(_ctx, args):
     global g_fVerbose
     if len(args) > 1:
@@ -1533,5 +1591,5 @@
     return 0
 
-def colorsCmd(ctx, args):
+def colorsCmd(_ctx, args):
     global g_fHasColors
     if len(args) > 1:
@@ -1541,5 +1599,5 @@
     return 0
 
-def hostCmd(ctx, args):
+def hostCmd(ctx, _args):
     vbox = ctx['vb']
     try:
@@ -1595,8 +1653,8 @@
 def monitorGuestCmd(ctx, args):
     if len(args) < 2:
-        print("usage: monitorGuest name (duration)")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: monitorGuest <vmname|uuid> (duration)")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     dur = 5
@@ -1612,5 +1670,5 @@
         return 0
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     dur = 5
@@ -1626,5 +1684,5 @@
         return 0
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     dur = 5
@@ -1640,5 +1698,5 @@
         return 0
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     dur = 5
@@ -1680,8 +1738,8 @@
 def portForwardCmd(ctx, args):
     if len(args) != 5:
-        print("usage: portForward <vm> <adapter> <hostPort> <guestPort>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: portForward <vmname|uuid> <adapter> <hostPort> <guestPort>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     adapterNum = int(args[2])
@@ -1711,8 +1769,8 @@
 def showLogCmd(ctx, args):
     if len(args) < 2:
-        print("usage: showLog vm <num>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: showLog <vmname|uuid> <num>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
 
@@ -1734,8 +1792,8 @@
 def findLogCmd(ctx, args):
     if len(args) < 3:
-        print("usage: findLog vm pattern <num>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: findLog <vmname|uuid> <pattern> <num>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
 
@@ -1765,8 +1823,8 @@
 def findAssertCmd(ctx, args):
     if len(args) < 2:
-        print("usage: findAssert vm <num>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: findAssert <vmname|uuid> <num>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
 
@@ -1805,5 +1863,5 @@
     expr = ' '.join(args[1:])
     try:
-        exec(expr)
+        exec(expr) # pylint: disable=exec-used
     except Exception as e:
         printErr(ctx, e)
@@ -1812,5 +1870,5 @@
     return 0
 
-def reloadExtCmd(ctx, args):
+def reloadExtCmd(ctx, _args):
     # maybe will want more args smartness
     checkUserExtensions(ctx, commands, getHomeFolder(ctx))
@@ -1823,5 +1881,5 @@
         return 0
     try:
-        lf = open(args[1], 'r')
+        lf = open(args[1], 'r', encoding='utf-8')
     except IOError as e:
         print("cannot open:", args[1], ":", e)
@@ -1846,5 +1904,5 @@
     return 0
 
-def sleepCmd(ctx, args):
+def sleepCmd(_ctx, args):
     if len(args) != 2:
         print("usage: sleep <secs>")
@@ -1859,5 +1917,5 @@
 
 
-def shellCmd(ctx, args):
+def shellCmd(_ctx, args):
     if len(args) < 2:
         print("usage: shell <commands>")
@@ -1926,5 +1984,5 @@
     return 0
 
-def reconnectCmd(ctx, args):
+def reconnectCmd(ctx, _args):
     if ctx['wsinfo'] is None:
         print("Never connected...")
@@ -2238,7 +2296,7 @@
         print("created HDD at %s as %s" % (colPath(ctx,hdd.location), hdd.id))
     else:
-       print("cannot create disk (file %s exist?)" % (loc))
-       reportError(ctx,progress)
-       return 0
+        print("cannot create disk (file %s exist?)" % (loc))
+        reportError(ctx,progress)
+        return 0
 
     return 0
@@ -2251,13 +2309,9 @@
     vbox = ctx['vb']
     loc = args[1]
-    setImageId = False
-    imageId = ""
-    setParentId = False
-    parentId = ""
     hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
     print("registered HDD as %s" % (hdd.id))
     return 0
 
-def controldevice(ctx, mach, args):
+def controldevice(_ctx, mach, args):
     [ctr, port, slot, devtype, uuid] = args
     mach.attachDevice(ctr, port, slot, devtype, uuid)
@@ -2265,5 +2319,5 @@
 def attachHddCmd(ctx, args):
     if len(args) < 3:
-        print("usage: attachHdd vm hdd controller port:slot")
+        print("usage: attachHdd <vmname|uuid> <hdd> <controller> <port:slot>")
         return 0
 
@@ -2300,5 +2354,5 @@
 def detachHddCmd(ctx, args):
     if len(args) < 3:
-        print("usage: detachHdd vm hdd")
+        print("usage: detachHdd <vmname|uuid> <hdd>")
         return 0
 
@@ -2383,4 +2437,20 @@
     loc = args[1]
     try:
+        vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
+    except:
+        print("no DVD with path %s registered" % (loc))
+        return 0
+
+    print("Unregistered ISO at %s" % (colPath(ctx, loc)))
+    return 0
+
+def removeIsoCmd(ctx, args):
+    if len(args) != 2:
+        print("usage: removeIso path")
+        return 0
+
+    vbox = ctx['vb']
+    loc = args[1]
+    try:
         dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
     except:
@@ -2388,16 +2458,21 @@
         return 0
 
-    progress = dvd.close()
-    print("Unregistered ISO at %s" % (colPath(ctx, loc)))
-
-    return 0
-
-def removeIsoCmd(ctx, args):
-    if len(args) != 2:
-        print("usage: removeIso path")
-        return 0
-
+    progress = dvd.deleteStorage()
+    if progressBar(ctx, progress):
+        print("Removed ISO at %s" % (colPath(ctx, dvd.location)))
+    else:
+        reportError(ctx, progress)
+    return 0
+
+def attachIsoCmd(ctx, args):
+    if len(args) < 3:
+        print("usage: attachIso <vmname|uuid> <iso> <controller> <port:slot>")
+        return 0
+
+    mach = argsToMach(ctx, args)
+    if mach is None:
+        return 0
     vbox = ctx['vb']
-    loc = args[1]
+    loc = args[2]
     try:
         dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
@@ -2405,15 +2480,15 @@
         print("no DVD with path %s registered" % (loc))
         return 0
-
-    progress = dvd.deleteStorage()
-    if progressBar(ctx, progress):
-        print("Removed ISO at %s" % (colPath(ctx, dvd.location)))
-    else:
-        reportError(ctx, progress)
-    return 0
-
-def attachIsoCmd(ctx, args):
+    if len(args) > 3:
+        ctr = args[3]
+        (port, slot) = args[4].split(":")
+    else:
+        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
+    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd))
+    return 0
+
+def detachIsoCmd(ctx, args):
     if len(args) < 3:
-        print("usage: attachIso vm iso controller port:slot")
+        print("usage: detachIso <vmname|uuid> <iso>")
         return 0
 
@@ -2428,51 +2503,28 @@
         print("no DVD with path %s registered" % (loc))
         return 0
+
+    detachMedium(ctx, mach.id, dvd)
+    return 0
+
+def mountIsoCmd(ctx, args):
+    if len(args) < 3:
+        print("usage: mountIso <vmname|uuid> <iso> <controller> <port:slot>")
+        return 0
+
+    mach = argsToMach(ctx, args)
+    if mach is None:
+        return 0
+    vbox = ctx['vb']
+    loc = args[2]
+    try:
+        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
+    except:
+        print("no DVD with path %s registered" % (loc))
+        return 0
+
     if len(args) > 3:
         ctr = args[3]
         (port, slot) = args[4].split(":")
     else:
-        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
-    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd))
-    return 0
-
-def detachIsoCmd(ctx, args):
-    if len(args) < 3:
-        print("usage: detachIso vm iso")
-        return 0
-
-    mach = argsToMach(ctx, args)
-    if mach is None:
-        return 0
-    vbox = ctx['vb']
-    loc = args[2]
-    try:
-        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
-    except:
-        print("no DVD with path %s registered" % (loc))
-        return 0
-
-    detachMedium(ctx, mach.id, dvd)
-    return 0
-
-def mountIsoCmd(ctx, args):
-    if len(args) < 3:
-        print("usage: mountIso vm iso controller port:slot")
-        return 0
-
-    mach = argsToMach(ctx, args)
-    if mach is None:
-        return 0
-    vbox = ctx['vb']
-    loc = args[2]
-    try:
-        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
-    except:
-        print("no DVD with path %s registered" % (loc))
-        return 0
-
-    if len(args) > 3:
-        ctr = args[3]
-        (port, slot) = args[4].split(":")
-    else:
         # autodetect controller and location, just find first controller with media == DVD
         [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
@@ -2484,5 +2536,5 @@
 def unmountIsoCmd(ctx, args):
     if len(args) < 2:
-        print("usage: unmountIso vm controller port:slot")
+        print("usage: unmountIso <vmname|uuid> <controller> <port:slot>")
         return 0
 
@@ -2490,5 +2542,4 @@
     if mach is None:
         return 0
-    vbox = ctx['vb']
 
     if len(args) > 3:
@@ -2503,5 +2554,5 @@
     return 0
 
-def attachCtr(ctx, mach, args):
+def attachCtr(_ctx, mach, args):
     [name, bus, ctrltype] = args
     ctr = mach.addStorageController(name, bus)
@@ -2511,5 +2562,5 @@
 def attachCtrCmd(ctx, args):
     if len(args) < 4:
-        print("usage: attachCtr vm cname bus <type>")
+        print("usage: attachCtr <vmname|uuid> <controller name> <bus> <type>")
         return 0
 
@@ -2535,5 +2586,5 @@
 def detachCtrCmd(ctx, args):
     if len(args) < 3:
-        print("usage: detachCtr vm name")
+        print("usage: detachCtr <vmname|uuid> <controller name>")
         return 0
 
@@ -2545,5 +2596,5 @@
     return 0
 
-def usbctr(ctx, mach, console, args):
+def usbctr(_ctx, _mach, console, args):
     if args[0]:
         console.attachUSBDevice(args[1], "")
@@ -2553,5 +2604,5 @@
 def attachUsbCmd(ctx, args):
     if len(args) < 3:
-        print("usage: attachUsb vm deviceuid")
+        print("usage: attachUsb <vmname|uuid> <device uid>")
         return 0
 
@@ -2565,5 +2616,5 @@
 def detachUsbCmd(ctx, args):
     if len(args) < 3:
-        print("usage: detachUsb vm deviceuid")
+        print("usage: detachUsb <vmname|uuid> <device uid>")
         return 0
 
@@ -2593,5 +2644,5 @@
 def shareFolderCmd(ctx, args):
     if len(args) < 4:
-        print("usage: shareFolder vm path name <writable> <persistent>")
+        print("usage: shareFolder <vmname|uuid> <path> <name> <writable|persistent>")
         return 0
 
@@ -2617,5 +2668,5 @@
 def unshareFolderCmd(ctx, args):
     if len(args) < 3:
-        print("usage: unshareFolder vm name")
+        print("usage: unshareFolder <vmname|uuid> <name>")
         return 0
 
@@ -2637,7 +2688,7 @@
 def snapshotCmd(ctx, args):
     if (len(args) < 2 or args[1] == 'help'):
-        print("Take snapshot:    snapshot vm take name <description>")
-        print("Restore snapshot: snapshot vm restore name")
-        print("Merge snapshot:   snapshot vm merge name")
+        print("Take snapshot:    snapshot <vmname|uuid> take <name> <description>")
+        print("Restore snapshot: snapshot <vmname|uuid> restore <name>")
+        print("Merge snapshot:   snapshot <vmname|uuid> merge <name>")
         return 0
 
@@ -2648,5 +2699,5 @@
     if cmd == 'take':
         if len(args) < 4:
-            print("usage: snapshot vm take name <description>")
+            print("usage: snapshot <vmname|uuid> take <name> <description>")
             return 0
         name = args[3]
@@ -2660,5 +2711,5 @@
     if cmd == 'restore':
         if len(args) < 4:
-            print("usage: snapshot vm restore name")
+            print("usage: snapshot <vmname|uuid> restore <name>")
             return 0
         name = args[3]
@@ -2669,5 +2720,5 @@
     if cmd == 'restorecurrent':
         if len(args) < 4:
-            print("usage: snapshot vm restorecurrent")
+            print("usage: snapshot <vmname|uuid> restorecurrent")
             return 0
         snap = mach.currentSnapshot()
@@ -2677,5 +2728,5 @@
     if cmd == 'delete':
         if len(args) < 4:
-            print("usage: snapshot vm delete name")
+            print("usage: snapshot <vmname|uuid> delete <name>")
             return 0
         name = args[3]
@@ -2687,7 +2738,7 @@
     return 0
 
-def natAlias(ctx, mach, nicnum, nat, args=[]):
+def natAlias(_ctx, _mach, _nicnum, nat, args=[]):
     """This command shows/alters NAT's alias settings.
-    usage: nat <vm> <nicnum> alias [default|[log] [proxyonly] [sameports]]
+    usage: nat <vmname|uuid> <nicnum> alias [default|[log] [proxyonly] [sameports]]
     default - set settings to default values
     log - switch on alias logging
@@ -2724,7 +2775,7 @@
     return (0, None)
 
-def natSettings(ctx, mach, nicnum, nat, args):
+def natSettings(_ctx, _mach, _nicnum, nat, args):
     """This command shows/alters NAT settings.
-    usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
+    usage: nat <vmname|uuid> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
     mtu - set mtu <= 16000
     socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
@@ -2758,7 +2809,7 @@
     return (0, None)
 
-def natDns(ctx, mach, nicnum, nat, args):
+def natDns(_ctx, _mach, _nicnum, nat, args):
     """This command shows/alters DNS's NAT settings
-    usage: nat <vm> <nicnum> dns [passdomain] [proxy] [usehostresolver]
+    usage: nat <vmname|uuid> <nicnum> dns [passdomain] [proxy] [usehostresolver]
     passdomain - enforces builtin DHCP server to pass domain
     proxy - switch on builtin NAT DNS proxying mechanism
@@ -2777,5 +2828,5 @@
 def natTftp(ctx, mach, nicnum, nat, args):
     """This command shows/alters TFTP settings
-    usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
+    usage nat <vmname|uuid> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
     prefix - alters prefix TFTP settings
     bootfile - alters bootfile TFTP settings
@@ -2788,8 +2839,8 @@
             if server is None:
                 server = '10.0.%d/24' % (int(nicnum) + 2)
-            (server, mask) = server.split('/')
+            (server, _mask) = server.split('/')
             while server.count('.') != 3:
                 server += '.0'
-            (a, b, c, d) = server.split('.')
+            (a, b, c, _d) = server.split('.')
             server = '%d.%d.%d.4' % (a, b, c)
         prefix = nat.TFTPPrefix
@@ -2816,8 +2867,8 @@
     return (0, None)
 
-def natPortForwarding(ctx, mach, nicnum, nat, args):
+def natPortForwarding(ctx, _mach, _nicnum, nat, args):
     """This command shows/manages port-forwarding settings
     usage:
-        nat <vm> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
+        nat <vmname|uuid> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
             |[no_name tcp|udp <hostip> <hostport> <guestip> <guestport>]
             |[ex tcp|udp <pf-name> <hostip> <hostport> <guestip> <guestport>]
@@ -2859,10 +2910,10 @@
             return (1, None)
 
-        a = pfcmd[args[1]]['func']()
+        _a = pfcmd[args[1]]['func']()
     return (0, None)
 
-def natNetwork(ctx, mach, nicnum, nat, args):
+def natNetwork(_ctx, _mach, nicnum, nat, args):
     """This command shows/alters NAT network settings
-    usage: nat <vm> <nicnum> network [<network>]
+    usage: nat <vmname|uuid> <nicnum> network [<network>]
     """
     if len(args) == 1:
@@ -2882,5 +2933,5 @@
 def natCmd(ctx, args):
     """This command is entry point to NAT settins management
-    usage: nat <vm> <nicnum> <cmd> <cmd-args>
+    usage: nat <vmname|uuid> <nicnum> <cmd> <cmd-args>
     cmd - [alias|settings|tftp|dns|pf|network]
     for more information about commands:
@@ -2906,10 +2957,11 @@
         print(natCmd.__doc__)
         return 0
-    mach = ctx['argsToMach'](args)
-    if mach == None:
+    mach = argsToMach(ctx, args)
+    if not mach:
         print("please specify vm")
         return 0
-    if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in list(range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType))):
-        print('please specify adapter num %d isn\'t in range [0-%d]' % (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType)))
+    platformProps = mach.platform.properties
+    if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in list(range(0, platformProps.getMaxNetworkAdapters(mach.platform.chipsetType))):
+        print('please specify adapter num %d isn\'t in range [0-%d]' % (args[2], platformProps.getMaxNetworkAdapters(mach.platform.chipsetType)))
         return 0
     nicnum = int(args[2])
@@ -2954,7 +3006,7 @@
     return (0, None)
 
-def nicTraceSubCmd(ctx, vm, nicnum, adapter, args):
+def nicTraceSubCmd(_ctx, _vm, _nicnum, adapter, args):
     '''
-    usage: nic <vm> <nicnum> trace [on|off [file]]
+    usage: nic <vmname|uuid> <nicnum> trace [on|off [file]]
     '''
     (rc, r) = nicSwitchOnOff(adapter, 'traceEnabled', args)
@@ -2966,5 +3018,5 @@
     return (0, None)
 
-def nicLineSpeedSubCmd(ctx, vm, nicnum, adapter, args):
+def nicLineSpeedSubCmd(_ctx, _vm, _nicnum, adapter, args):
     if len(args) == 1:
         r = '%d kbps'% (adapter.lineSpeed)
@@ -2977,19 +3029,19 @@
     return (0, None)
 
-def nicCableSubCmd(ctx, vm, nicnum, adapter, args):
+def nicCableSubCmd(_ctx, _vm, _nicnum, adapter, args):
     '''
-    usage: nic <vm> <nicnum> cable [on|off]
+    usage: nic <vmname|uuid> <nicnum> cable [on|off]
     '''
     return nicSwitchOnOff(adapter, 'cableConnected', args)
 
-def nicEnableSubCmd(ctx, vm, nicnum, adapter, args):
+def nicEnableSubCmd(_ctx, _vm, _nicnum, adapter, args):
     '''
-    usage: nic <vm> <nicnum> enable [on|off]
+    usage: nic <vmname|uuid> <nicnum> enable [on|off]
     '''
     return nicSwitchOnOff(adapter, 'enabled', args)
 
-def nicTypeSubCmd(ctx, vm, nicnum, adapter, args):
+def nicTypeSubCmd(ctx, _vm, _nicnum, adapter, args):
     '''
-    usage: nic <vm> <nicnum> type [Am79c970A|Am79c970A|I82540EM|I82545EM|I82543GC|Virtio]
+    usage: nic <vmname|uuid> <nicnum> type [Am79c970A|Am79c970A|I82540EM|I82545EM|I82543GC|Virtio]
     '''
     if len(args) == 1:
@@ -3007,7 +3059,7 @@
     return (0, None)
 
-def nicAttachmentSubCmd(ctx, vm, nicnum, adapter, args):
+def nicAttachmentSubCmd(ctx, _vm, _nicnum, adapter, args):
     '''
-    usage: nic <vm> <nicnum> attachment [Null|NAT|Bridged <interface>|Internal <name>|HostOnly <interface>
+    usage: nic <vmname|uuid> <nicnum> attachment [Null|NAT|Bridged <interface>|Internal <name>|HostOnly <interface>
     '''
     if len(args) == 1:
@@ -3068,5 +3120,5 @@
     '''
     This command to manage network adapters
-    usage: nic <vm> <nicnum> <cmd> <cmd-args>
+    usage: nic <vmname|uuid> <nicnum> <cmd> <cmd-args>
     where cmd : attachment, trace, linespeed, cable, enable, type
     '''
@@ -3095,7 +3147,8 @@
         return 0
 
+    platformProps = vm.platform.properties
     if    len(args) < 3 \
-       or int(args[2]) not in list(range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType))):
-        print('please specify adapter num %d isn\'t in range [0-%d]'% (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType)))
+       or int(args[2]) not in list(range(0, platformProps.getMaxNetworkAdapters(vm.platform.chipsetType))):
+        print('please specify adapter num %d isn\'t in range [0-%d]'% (args[2], platformProps.getMaxNetworkAdapters(vm.platform.chipsetType)))
         return 0
     nicnum = int(args[2])
@@ -3152,8 +3205,8 @@
 def recordDemoCmd(ctx, args):
     if len(args) < 3:
-        print("usage: recordDemo vm filename (duration)")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: recordDemo <vmname|uuid> <filename> [duration in s]")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     filename = args[2]
@@ -3166,8 +3219,8 @@
 def playbackDemoCmd(ctx, args):
     if len(args) < 3:
-        print("usage: playbackDemo vm filename (duration)")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: playbackDemo <vmname|uuid> <filename> [duration in s]")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     filename = args[2]
@@ -3210,5 +3263,5 @@
         return 0
     mach = argsToMach(ctx, args)
-    if mach == None:
+    if not mach:
         return 0
     cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  lspci(ctx, console)])
@@ -3217,8 +3270,8 @@
 def attachpciCmd(ctx, args):
     if len(args) < 3:
-        print("usage: attachpci vm hostpci <guestpci>")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: attachpci <vmname|uuid> <host pci address> <guest pci address>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     hostaddr = parsePci(args[2])
@@ -3239,8 +3292,8 @@
 def detachpciCmd(ctx, args):
     if len(args) < 3:
-        print("usage: detachpci vm hostpci")
-        return 0
-    mach = argsToMach(ctx, args)
-    if mach == None:
+        print("usage: detachpci <vmname|uuid> <host pci address>")
+        return 0
+    mach = argsToMach(ctx, args)
+    if not mach:
         return 0
     hostaddr = parsePci(args[2])
@@ -3273,6 +3326,6 @@
 
 commands = {'help':['Prints help information', helpCmd, 0],
-            'start':['Start virtual machine by name or uuid: start Linux headless', startCmd, 0],
-            'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
+            'start':['Start virtual machine by name or uuid: start mytestvm headless', startCmd, 0],
+            'createVm':['Create virtual machine: createVm myvmname x86 MacOS', createVmCmd, 0],
             'removeVm':['Remove virtual machine', removeVmCmd, 0],
             'pause':['Pause virtual machine', pauseCmd, 0],
@@ -3290,32 +3343,32 @@
             'alias':['Control aliases', aliasCmd, 0],
             'verbose':['Toggle verbosity', verboseCmd, 0],
-            'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
+            'setvar':['Set VM variable: setvar mytestvm firmwareSettings.ACPIEnabled True', setvarCmd, 0],
             'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print(m.name, "has", m.memorySize, "M")\'', evalCmd, 0],
             'quit':['Exits', quitCmd, 0],
             'host':['Show host information', hostCmd, 0],
-            'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
-            'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
-            'monitorGuestKbd':['Monitor guest keyboard for some time: monitorGuestKbd Win32 10', monitorGuestKbdCmd, 0],
-            'monitorGuestMouse':['Monitor guest mouse for some time: monitorGuestMouse Win32 10', monitorGuestMouseCmd, 0],
-            'monitorGuestMultiTouch':['Monitor guest touch screen for some time: monitorGuestMultiTouch Win32 10', monitorGuestMultiTouchCmd, 0],
+            'guest':['Execute command for guest: guest mytestvm \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
+            'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest mytestvm 10', monitorGuestCmd, 0],
+            'monitorGuestKbd':['Monitor guest keyboard for some time: monitorGuestKbd mytestvm 10', monitorGuestKbdCmd, 0],
+            'monitorGuestMouse':['Monitor guest mouse for some time: monitorGuestMouse mytestvm 10', monitorGuestMouseCmd, 0],
+            'monitorGuestMultiTouch':['Monitor guest touch screen for some time: monitorGuestMultiTouch mytestvm 10', monitorGuestMultiTouchCmd, 0],
             'monitorVBox':['Monitor what happens with VirtualBox for some time: monitorVBox 10', monitorVBoxCmd, 0],
-            'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
-            'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
-            'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
-            'findAssert':['Find assert in log file of the VM, : findAssert Win32', findAssertCmd, 0],
+            'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward mytestvm 0 8080 80', portForwardCmd, 0],
+            'showLog':['Show log file of the VM, : showLog mytestvm', showLogCmd, 0],
+            'findLog':['Show entries matching pattern in log file of the VM, : findLog mytestvm PDM|CPUM', findLogCmd, 0],
+            'findAssert':['Find assert in log file of the VM, : findAssert mytestvm', findAssertCmd, 0],
             'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
             'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
             'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
             'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
-            'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
-            'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768 0', screenshotCmd, 0],
-            'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
+            'exportVm':['Export VM in OVF format: exportVm mytestvm /tmp/win.ovf', exportVMCmd, 0],
+            'screenshot':['Take VM screenshot to a file: screenshot mytestvm /tmp/win.png 1024 768 0', screenshotCmd, 0],
+            'teleport':['Teleport VM to another box (see openportal): teleport mytestvm anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
             'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
-            'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
+            'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal mytestvm 8000 <passwd>', openportalCmd, 0],
             'closeportal':['Close teleportation portal (see openportal, teleport): closeportal Win', closeportalCmd, 0],
             'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
             'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
-            'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
-            'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
+            'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats mytestvm', gueststatsCmd, 0],
+            'plugcpu':['Add a CPU to a running VM: plugcpu mytestvm 1', plugcpuCmd, 0],
             'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
             'createHdd': ['Create virtual HDD:  createHdd 1000 /disk.vdi ', createHddCmd, 0],
@@ -3323,20 +3376,20 @@
             'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
             'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
-            'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
-            'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
+            'attachHdd': ['Attach HDD to the VM: attachHdd mytestvm /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
+            'detachHdd': ['Detach HDD from the VM: detachHdd mytestvm /disk.vdi', detachHddCmd, 0],
             'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
             'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
             'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
-            'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
-            'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
-            'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
-            'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
-            'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
-            'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
-            'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
-            'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
+            'attachIso': ['Attach CD/DVD to the VM: attachIso mytestvm /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
+            'detachIso': ['Detach CD/DVD from the VM: detachIso mytestvm /os.iso', detachIsoCmd, 0],
+            'mountIso': ['Mount CD/DVD to the running VM: mountIso mytestvm /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
+            'unmountIso': ['Unmount CD/DVD from running VM: unmountIso mytestvm "IDE Controller" 0:1', unmountIsoCmd, 0],
+            'attachCtr': ['Attach storage controller to the VM: attachCtr mytestvm Ctr0 IDE ICH6', attachCtrCmd, 0],
+            'detachCtr': ['Detach HDD from the VM: detachCtr mytestvm Ctr0', detachCtrCmd, 0],
+            'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb mytestvm uuid', attachUsbCmd, 0],
+            'detachUsb': ['Detach USB device from the VM: detachUsb mytestvm uuid', detachUsbCmd, 0],
             'listMedia': ['List media known to this VBox instance', listMediaCmd, 0],
             'listUsb': ['List known USB devices', listUsbCmd, 0],
-            'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
+            'shareFolder': ['Make host\'s folder visible to guest: shareFolder mytestvm /share share writable', shareFolderCmd, 0],
             'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
             'gui': ['Start GUI frontend', guiCmd, 0],
@@ -3348,9 +3401,9 @@
             'foreachvm' : ['Perform command for each VM', foreachvmCmd, 0],
             'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print(obj.name)"', foreachCmd, 0],
-            'recordDemo':['Record demo: recordDemo Win32 file.dmo 10', recordDemoCmd, 0],
-            'playbackDemo':['Playback demo: playbackDemo Win32 file.dmo 10', playbackDemoCmd, 0],
-            'lspci': ['List PCI devices attached to the VM: lspci Win32', lspciCmd, 0],
-            'attachpci': ['Attach host PCI device to the VM: attachpci Win32 01:00.0', attachpciCmd, 0],
-            'detachpci': ['Detach host PCI device from the VM: detachpci Win32 01:00.0', detachpciCmd, 0],
+            'recordDemo':['Record demo: recordDemo mytestvm file.dmo 10', recordDemoCmd, 0],
+            'playbackDemo':['Playback demo: playbackDemo mytestvm file.dmo 10', playbackDemoCmd, 0],
+            'lspci': ['List PCI devices attached to the VM: lspci mytestvm', lspciCmd, 0],
+            'attachpci': ['Attach host PCI device to the VM: attachpci mytestvm 01:00.0', attachpciCmd, 0],
+            'detachpci': ['Detach host PCI device from the VM: detachpci mytestvm 01:00.0', detachpciCmd, 0],
             'goto': ['Go to line in script (script-only)', gotoCmd, 0]
             }
@@ -3394,10 +3447,10 @@
 # they will also be picked up, so this way one can exchange
 # shell extensions easily.
-def addExtsFromFile(ctx, cmds, filename):
+def addExtsFromFile(_ctx, cmds, filename):
     if not os.path.isfile(filename):
         return
     d = {}
     try:
-        exec(compile(open(filename).read(), filename, 'exec'), d, d)
+        exec(compile(open(filename, encoding='utf-8').read(), filename, 'exec'), d, d) # pylint: disable=exec-used
         for (k, v) in list(d['commands'].items()):
             if g_fVerbose:
@@ -3482,5 +3535,5 @@
             else:
                 if sys.version_info[0] <= 2:
-                    cmd = raw_input(ctx['prompt'])
+                    cmd = raw_input(ctx['prompt']) # pylint: disable=undefined-variable
                 else:
                     cmd = input(ctx['prompt'])
@@ -3502,5 +3555,5 @@
     try:
         # There is no need to disable metric collection. This is just an example.
-        if ct['perf']:
+        if ctx['perf']:
             ctx['perf'].disable(['*'], [vbox.host])
     except:
@@ -3515,5 +3568,5 @@
 def runGuestCommandCb(ctx, uuid, guestLambda, args):
     mach = machById(ctx, uuid)
-    if mach == None:
+    if not mach:
         return 0
     args.insert(0, guestLambda)
@@ -3521,5 +3574,5 @@
     return 0
 
-def main(argv):
+def main(_argv):
 
     #
@@ -3534,5 +3587,5 @@
     parse.add_option("-o", dest="opt_line", help = "option line")
     global g_fVerbose, g_sScriptFile, g_fBatchMode, g_fHasColors, g_fHasReadline, g_sCmd
-    (options, args) = parse.parse_args()
+    (options, _args) = parse.parse_args()
     g_fVerbose = options.verbose
     style = options.style
@@ -3633,3 +3686,2 @@
 if __name__ == '__main__':
     main(sys.argv)
-
