How to use aexpect - 10 common examples

To help you get started, we’ve selected a few aexpect examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github avocado-framework / avocado-vt / virttest / libvirt_vm.py View on Github external
for serial in self.params.objects("isa_serials"):
                self.serial_ports.append(serial)
        if self.serial_console is None:
            try:
                cmd = 'virsh'
                if self.connect_uri:
                    cmd += ' --uri=%s' % self.connect_uri
                cmd += (" console %s %s" % (self.name, self.serial_ports[0]))
            except IndexError:
                raise virt_vm.VMConfigMissingError(self.name, "isa_serial")
            output_func = utils_misc.log_line  # Because qemu-kvm uses this
            # Because qemu-kvm hard-codes this
            output_filename = self.get_serial_console_filename(self.serial_ports[0])
            output_params = (output_filename,)
            prompt = self.params.get("shell_prompt", "[\#\$]")
            self.serial_console = aexpect.ShellSession(command=cmd, auto_close=False,
                                                       output_func=output_func,
                                                       output_params=output_params)
            # Cause serial_console.close() to close open log file
            self.serial_console.set_log_file(output_filename)
github avocado-framework / avocado-vt / virttest / libvirt_vm.py View on Github external
self.serial_ports.append(serial)
        if self.serial_console is None or self.serial_console.closed:
            try:
                cmd = 'virsh'
                if self.connect_uri:
                    cmd += ' -c %s' % self.connect_uri
                cmd += (" console %s %s" % (self.name, self.serial_ports[0]))
            except IndexError:
                raise virt_vm.VMConfigMissingError(self.name, "serial")
            output_func = utils_misc.log_line  # Because qemu-kvm uses this
            # Because qemu-kvm hard-codes this
            output_filename = self.get_serial_console_filename(self.serial_ports[0])
            output_params = (output_filename,)
            prompt = self.params.get("shell_prompt", "[\#\$]")
            logging.debug("Command used to create serial console: %s", cmd)
            self.serial_console = aexpect.ShellSession(command=cmd, auto_close=False,
                                                       output_func=output_func,
                                                       output_params=output_params,
                                                       prompt=prompt)
            if not self.serial_console.is_alive():
                logging.error("Failed to create serial_console")
            # Cause serial_console.close() to close open log file
            self.serial_console.set_log_file(output_filename)
            self.serial_console_log = os.path.join(utils_misc.get_log_file_dir(),
                                                   output_filename)
github avocado-framework / avocado-vt / virttest / qemu_vm.py View on Github external
vcpu_thread_pattern = params.get("vcpu_thread_pattern",
                                               "thread_id=(\d+)")
            self.vcpu_threads = re.findall(vcpu_thread_pattern, str(o))
            o = commands.getoutput("ps aux")
            self.vhost_threads = re.findall("\w+\s+(\d+)\s.*\[vhost-%s\]" %
                                            self.get_pid(), o)

            # Establish a session with the serial console
            # Let's consider the first serial port as serial console.
            # Note: requires a version of netcat that supports -U
            try:
                tmp_serial = self.serial_ports[0]
            except IndexError:
                raise virt_vm.VMConfigMissingError(name, "isa_serial")

            self.serial_console = aexpect.ShellSession(
                "nc -U %s" % self.get_serial_console_filename(tmp_serial),
                auto_close=False,
                output_func=utils_misc.log_line,
                output_params=("serial-%s-%s.log" % (tmp_serial, name),),
                prompt=self.params.get("shell_prompt", "[\#\$]"))
            del tmp_serial

            for key, value in self.logs.items():
                outfile = "%s-%s.log" % (key, name)
                self.logsessions[key] = aexpect.Tail(
                    "nc -U %s" % value,
                    auto_close=False,
                    output_func=utils_misc.log_line,
                    output_params=(outfile,))
                self.logsessions[key].set_log_file(outfile)
github avocado-framework / avocado-vt / virttest / virt_admin.py View on Github external
if re.split(patterns[match], output[i])[-1]:
                            output[i] = re.split(patterns[match],
                                                 output[i])[-1]
                            output_slice = output[i:]
                        else:
                            output_slice = output[i + 1:]
                        for j in range(len(output_slice) - 1):
                            output_slice[j] = output_slice[j] + '\n'
                        for k in range(len(output_slice)):
                            out += output_slice[k]
                        return match, out
                return match, o

        # Check if the child has terminated
        if utils_misc.wait_for(lambda: not self.is_alive(), 5, 0, 0.1):
            raise aexpect.ExpectProcessTerminatedError(patterns,
                                                       self.get_status(), o)
        else:
            # This shouldn't happen
            raise aexpect.ExpectError(patterns, o)
github avocado-framework / avocado-vt / virttest / virsh.py View on Github external
if re.split(patterns[match], output[i])[-1]:
                            output[i] = re.split(patterns[match],
                                                 output[i])[-1]
                            output_slice = output[i:]
                        else:
                            output_slice = output[i + 1:]
                        for j in range(len(output_slice) - 1):
                            output_slice[j] = output_slice[j] + '\n'
                        for k in range(len(output_slice)):
                            out += output_slice[k]
                        return match, out
                return match, o

        # Check if the child has terminated
        if utils_misc.wait_for(lambda: not self.is_alive(), 5, 0, 0.1):
            raise aexpect.ExpectProcessTerminatedError(patterns,
                                                       self.get_status(), o)
        else:
            # This shouldn't happen
            raise aexpect.ExpectError(patterns, o)
github autotest / autotest / client / virt / libvirt_monitor.py View on Github external
"""
        Log into the hypervisor using required URIs .

        @timeout: Time in seconds that we will wait before giving up on logging
                into the host.
        @return: A ShellSession object.
        """
        if self.driver is None:
            uri = utils.system_output('%s uri' % self.virsh_exec)
        else:
            uri = "%s+ssh://%s@%s/system" % (self.driver, self.username,
                                             self.host)

        command = "%s --connect  %s" % (self.virsh_exec, uri)

        session = aexpect.ShellSession(command, linesep=self.linesep,
                                       prompt=self.prompt)

        if self.username is not None:
            try:
                remote._remote_login(session, self.username, self.password,
                                          self.prompt, timeout)
            except aexpect.ShellError:
                session.close()
                session = None

        return session
github autotest / autotest / client / virt / libvirt_vm.py View on Github external
# Make qemu command
            install_command = self.__make_libvirt_command()

            logging.info("Running libvirt command (reformatted):")
            for item in install_command.replace(" -", " \n    -").splitlines():
                logging.info("%s", item)
            utils.run(install_command, verbose=False)
            # Wait for the domain to be created
            utils_misc.wait_for(func=self.is_alive, timeout=60,
                                text=("waiting for domain %s to start" %
                                      self.name))
            self.uuid = virsh.domuuid(self.name, uri=self.connect_uri)

            # Establish a session with the serial console
            if self.only_pty == True:
                self.serial_console = aexpect.ShellSession(
                    "virsh console %s" % self.name,
                    auto_close=False,
                    output_func=utils_misc.log_line,
                    output_params=("serial-%s.log" % name,))
            else:
                self.serial_console = aexpect.ShellSession(
                    "tail -f %s" % self.get_serial_console_filename(),
                    auto_close=False,
                    output_func=utils_misc.log_line,
                    output_params=("serial-%s.log" % name,))

        finally:
            fcntl.lockf(lockfile, fcntl.LOCK_UN)
            lockfile.close()
github libvirt / libvirt-test-API / repos / domain / send_key.py View on Github external
def login_guest(guestname, username, password, logger):
    cmd = "virsh console %s --force" % guestname
    session = aexpect.ShellSession(cmd)
    try:
        while True:
            match, text = session.read_until_last_line_matches(
                [r"[E|e]scape character is", r"login:",
                 r"[P|p]assword:", session.prompt],
                10, internal_timeout=1)
            if match == 0:
                logger.debug("Got '^]', sending '\\n'")
                session.sendline()
            elif match == 1:
                logger.debug("Got 'login:', sending '%s'", username)
                session.sendline(username)
            elif match == 2:
                logger.debug("Got 'Password:', sending '%s'", password)
                session.sendline(password)
            elif match == 3:
github avocado-framework / avocado-vt / virttest / utils_libguestfs.py View on Github external
Execute built-in command in a complete guestfish command
        (Not a guestfish session).
        command: guestfish [--options] [commands]
        """
        guestfs_exec = self.__dict_get__('lgf_exec')
        ignore_status = self.__dict_get__('ignore_status')
        debug = self.__dict_get__('debug')
        timeout = self.__dict_get__('timeout')
        if command:
            guestfs_exec += " %s" % command
            return lgf_command(guestfs_exec, ignore_status, debug, timeout)
        else:
            raise LibguestfsCmdError("No built-in command was passed.")


class GuestfishSession(aexpect.ShellSession):

    """
    A shell session of guestfish.
    """

    # Check output against list of known error-status strings
    ERROR_REGEX_LIST = ['libguestfs: error:\s*']

    def __init__(self, guestfs_exec=None, a_id=None, prompt=r">\s*"):
        """
        Initialize guestfish session server, or client if id set.

        :param guestfs_cmd: path to guestfish executable
        :param id: ID of an already running server, if accessing a running
                server, or None if starting a new one.
        :param prompt: Regular expression describing the shell's prompt line.
github autotest / autotest / client / virt / virsh.py View on Github external
def __getitem__(self, key):
        """
        Look up key's value on instance, then parent instance attributes

        @param: key: key to look up non-None value
        @raises: KeyError: When value is None, undefined locally or on parent.
        """
        try:
            return super(DArgMangler, self).__getitem__(key)
        except KeyError:
            # Assume parent raises KeyError if value == None
            return self._parent.__getitem__(key)


class VirshSession(aexpect.ShellSession):
    """
    A virsh shell session, used with Virsh instances.
    """

    # No way to get virsh sub-command "exit" status
    # Check output against list of known error-status strings
    ERROR_REGEX_LIST = ['error:\s*', 'failed']

    def __init__(self, virsh_exec=None, uri=None, id=None,
                 prompt=r"virsh\s*\#\s*"):
        """
        Initialize virsh session server, or client if id set.

        @param: virsh_exec: path to virsh executable
        @param: uri: uri of libvirt instance to connect to
        @param: id: ID of an already running server, if accessing a running