Exemple #1
0
def check_duplicated_console(command, force_command, status_error, login_user,
                             login_passwd, test):
    """
    Test opening a second console with another console active using --force
    option or not.

    :param command: Test command without --force option
    :param force_command: Test command with --force option
    :param status_error: Whether the command is fault.
    :param login_user: User name for logging into the VM.
    :param login_passwd: Password for logging into the VM.
    :param test: Test Object
    """
    session = aexpect.ShellSession(command)
    if not status_error:
        # Test duplicated console session
        res = process.run(command, timeout=10, ignore_status=True, shell=True)
        logging.debug(res)
        if res.exit_status == 0:
            test.fail("Duplicated console session should fail. "
                      "but succeeded with:\n%s" % res)

        # Test duplicated console session with force option
        force_session = aexpect.ShellSession(force_command)
        force_status = utils_test.libvirt.verify_virsh_console(force_session,
                                                               login_user,
                                                               login_passwd,
                                                               timeout=10,
                                                               debug=True)
        if not force_status:
            test.fail("Expect force console session should succeed, "
                      "but failed.")
        force_session.close()
    session.close()
Exemple #2
0
    def test_launch(self):

        host = self.params.get("hostname", '/tests/', "localhost")
        hostfile = self.params.get("hostfile1", '/files/', "/tmp/hostfile1")
        urifile = self.params.get("urifile", '/files/', "/tmp/urifile")

        server_count = len(genio.read_all_lines(hostfile))

        get_prompt = "/bin/bash"
        launch_cmd = "../../install/bin/orterun --np {0} ".format(server_count)
        launch_cmd += "--hostfile {0} --enable-recovery ".format(hostfile)
        launch_cmd += "--report-uri {0} -x D_LOG_FILE=/mnt/shared/test/tmp/daos.log ".format(
            urifile)
        launch_cmd += "-x LD_LIBRARY_PATH=/home/skirvan/daos_m10/install/lib:/home/skirvan/daos_m10/install/lib/daos_srv "
        launch_cmd += "../../install/bin/daos_server -d /tmp/.daos -g daos_server"

        try:
            session = aexpect.ShellSession(get_prompt)
            if (session.is_responsive()):
                session.sendline(launch_cmd)
                session.read_until_any_line_matches(
                    "XDAOS server (v0.0.2) started on rank *",
                    timeout=5.0,
                    print_func=printFunc)
            else:
                self.fail("Server did not start.\n")
        except Exception as e:
            self.fail("Server did not start.\n")

        session.sendcontrol("c")
Exemple #3
0
def runServer(hostfile, setname, basepath):

    global sessions
    try:
        server_count = len(genio.read_all_lines(hostfile))

        initial_cmd = "/bin/sh"
        server_cmd = basepath + "/install/bin/orterun --np {0} ".format(
            server_count)
        server_cmd += "--hostfile {0} --enable-recovery ".format(hostfile)
        server_cmd += "-x D_LOG_MASK=DEBUG,RPC=ERR,MEM=ERR -x D_LOG_FILE="
        server_cmd += basepath + "/install/tmp/daos.log "
        server_cmd += "-x LD_LIBRARY_PATH={0}/install/lib:".format(basepath)
        server_cmd += "{0}/install/lib/daos_srv ".format(basepath)
        server_cmd += basepath + "/install/bin/daos_server -g {0} -c 1 ".format(
            setname)
        server_cmd += " -a" + basepath + "/install/tmp/"

        print "Start CMD>>>>{0}".format(server_cmd)

        sessions[setname] = aexpect.ShellSession(initial_cmd)
        if (sessions[setname].is_responsive()):
            sessions[setname].sendline(server_cmd)
            sessions[setname].read_until_any_line_matches(
                "DAOS server (v0.0.2) started on rank 0*",
                print_func=printFunc)
            print "<SERVER> server started"
    except Exception as e:
        print "<SERVER> Exception occurred: {0}".format(str(e))
        raise ServerFailed("Server didn't start!")
Exemple #4
0
    def _start_tcpdump(self):
        port = self._params.get('shell_port')
        prompt = self._params.get('shell_prompt')
        address = self._params.get('ovirt_node_address')
        username = self._params.get('ovirt_node_user')
        password = self._params.get('ovirt_node_password')

        cmd_template = "%s -npvvvi any 'port 68 or port 546'"
        cmd = cmd_template % utils_misc.find_command("tcpdump")
        if self._params.get("remote_preprocess") == "yes":
            login_cmd = ("ssh -o UserKnownHostsFile=/dev/null "
                         "-o StrictHostKeyChecking=no "
                         "-o PreferredAuthentications=password -p %s %s@%s" %
                         (port, username, address))

            self._tcpdump = aexpect.ShellSession(
                login_cmd,
                output_func=_update_address_cache,
                output_params=(self, ))

            remote.handle_prompts(self._tcpdump, username, password, prompt)
            self._tcpdump.sendline(cmd)

        else:
            self._tcpdump = aexpect.Tail(command=cmd,
                                         output_func=_tcpdump_handler,
                                         output_params=(self, "tcpdump.log"))

        if utils_misc.wait_for(lambda: not self._tcpdump.is_alive(), 0.1, 0.1,
                               1.0):
            logging.warn("Could not start tcpdump")
            logging.warn("Status: %s", self._tcpdump.get_status())
            msg = utils_misc.format_str_for_message(self._tcpdump.get_output())
            logging.warn("Output: %s", msg)
    def edit_image_xml():
        edit_cmd = r":%s /<boot dev='hd'\/>/<boot dev='cdrom'\/>"

        if restore_state == "running":
            option = "--running"
        elif restore_state == "paused":
            option = "--paused"
        elif restore_state == "":
            option = ""
        else:
            test.fail("Unknown save-image-define option")

        session = aexpect.ShellSession("sudo -s")
        try:
            logging.info("Execute virsh save-image-edit %s %s",
                         vm_save, option)
            session.sendline("virsh save-image-edit %s %s " %
                             (vm_save, option))

            logging.info("Replace '<boot dev='hd'/>' to '<boot dev='cdrom'/>'")
            session.sendline(edit_cmd)
            session.send('\x1b')
            session.send('ZZ')
            session.read_until_any_line_matches(
                    patterns=['State file.*%s edited' % vm_save, 'not changed'],
                    timeout=5,
                    print_func=logging.debug)
        except (aexpect.ShellError, aexpect.ExpectError,
                aexpect.ShellTimeoutError) as details:
            session.close()
            test.error("Failed to do save-image-edit: %s" % details)
Exemple #6
0
    def create_ssh_session(self):
        """Create ssh session"""
        user_known_hosts_file = '/dev/null'
        port = 22
        _, output = self.serial_cmd("ping -c 2 %s" % NETWORKS.ipaddr)
        LOG.debug("check ping result %s" % output)
        ssh_session = aexpect.ShellSession(
            "ssh %s -o UserKnownHostsFile=%s -o StrictHostKeyChecking=no -p %s"
            % (self.guest_ip, user_known_hosts_file, port),
            auto_close=False,
            output_func=self.serial_log.debug,
            prompt=r"[\#\$]",
            status_test_command="echo $?")

        try:
            self.console_manager.handle_session(ssh_session,
                                                username=CONFIG.vm_username,
                                                password=CONFIG.vm_password,
                                                prompt=r"[\#\$]",
                                                timeout=60.0)
        except Exception:
            ssh_session.close()
            raise Exception("handle_prompts ssh session failed!")

        return ssh_session
    def edit_snap_xml(dom_name, edit_opts, edit_cmd):
        """
        Edit domain snapshot xml

        :param dom_name: name of domain
        :param snap_name: name of snapshot
        :param edit_opts: snapshot-edit options
        :param edit_cmd: edit command list in interactive mode
        """

        session = aexpect.ShellSession("sudo -s")
        try:
            logging.debug("snapshot-edit options is: %s" % edit_opts)
            logging.debug("edit cmd is: %s" % edit_cmd)
            session.sendline("virsh snapshot-edit %s %s"
                             % (dom_name, edit_opts))
            for i in edit_cmd:
                session.sendline(i)
            # Press ESC
            session.send('\x1b')
            # Save and quit
            session.send('ZZ')
            # use sleep(1) to make sure the modify has been completed.
            remote.handle_prompts(session, None, None, r"[\#\$]\s*$")
            session.close()
            logging.info("Succeed to do snapshot edit")
        except (aexpect.ShellError, aexpect.ExpectError) as details:
            log = session.get_output()
            session.close()
            test.fail("Failed to do snapshot-edit: %s\n%s"
                      % (details, log))
    def edit_net_xml(edit_cmd, expect_error, **dargs):
        """
        Edit net xml with virsh net-edit

        :params edit_cmd: The edit cmd to execute
        :params expect_error: Boolean, expect success or not
        :params **dargs: The virsh edit's option
        """
        logging.debug("edit_cmd: %s", edit_cmd)
        readonly = dargs.get("readonly", False)
        session = aexpect.ShellSession("sudo -s")
        try:
            logging.info("Execute virsh net-edit %s", net_name)
            virsh_cmd = "virsh net-edit %s" % net_name
            if readonly:
                virsh_cmd = "virsh -r net-edit %s" % net_name
            logging.debug("virsh_cmd: %s", virsh_cmd)
            session.sendline(virsh_cmd)
            session.sendline(edit_cmd)
            session.send('\x1b')
            session.send('ZZ')
            remote.handle_prompts(session, None, None, r"[\#\$]\s*$")
            session.close()
        except (aexpect.ShellError, aexpect.ExpectError,
                remote.LoginTimeoutError) as details:
            log = session.get_output()
            session.close()
            if not expect_error:
                test.fail("Failed to do net-edit: %s\n%s" % (details, log))
            logging.debug("Expected error: %s" % log)
            if readonly and "read only" not in log:
                test.fail("Not expected error")
Exemple #9
0
    def virtio_serial_login(self, port='vs1'):
        error_context.context("Try to login guest via '%s'" % port,
                              logging.info)
        username = self.params.get("username")
        password = self.params.get("password")
        prompt = self.params.get("shell_prompt", "[#$]")
        linesep = eval("'%s'" % self.params.get("shell_linesep", r"\n"))
        for vport in self.get_virtio_ports(self.vm)[1]:
            if vport.name == port:
                break
            vport = None
        if not vport:
            self.test.error("Not virtio serial port '%s' found" % port)

        logfile = "serial-%s-%s.log" % (vport.name, self.vm.name)
        socat_cmd = "nc -U %s" % vport.hostfile
        session = aexpect.ShellSession(socat_cmd,
                                       auto_close=False,
                                       output_func=utils_misc.log_line,
                                       output_params=(logfile, ),
                                       prompt=prompt)
        session.set_linesep(linesep)
        session.sendline()
        self.__sessions__.append(session)
        try:
            remote.handle_prompts(session, username, password, prompt, 180)
            self.test.fail("virtio serial '%s' should no " % port +
                           "channel to login")
        except remote.LoginTimeoutError:
            self.__sessions__.append(session)
            logging.info("Can't login via %s" % port)
        return session
Exemple #10
0
    def edit_image_xml():
        edit_cmd = r":%s /<boot dev='hd'\/>/<boot dev='cdrom'\/>"

        if restore_state == "running":
            option = "--running"
        elif restore_state == "paused":
            option = "--paused"
        else:
            raise error.TestFail("Unknown save-image-define option")

        session = aexpect.ShellSession("sudo -s")
        try:
            logging.info("Execute virsh save-image-edit %s %s", vm_save,
                         option)
            session.sendline("virsh save-image-edit %s %s " %
                             (vm_save, option))

            logging.info("Replace '<boot dev='hd'/>' to '<boot dev='cdrom'/>'")
            session.sendline(edit_cmd)
            session.send('\x1b')
            session.send('ZZ')
            remote.handle_prompts(session, None, None, r"[\#\$]\s*$")
            session.close()
        except (aexpect.ShellError, aexpect.ExpectError), details:
            log = session.get_output()
            session.close()
            raise error.TestFail("Failed to do save-image-edit: %s\n%s" %
                                 (details, log))
Exemple #11
0
    def login(self, timeout=LOGIN_TIMEOUT):
        """
        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:
                virt_utils._remote_login(session, self.username, self.password,
                                         self.prompt, timeout)
            except aexpect.ShellError:
                session.close()
                session = None

        return session
Exemple #12
0
def remote_login(client, host, port, username, password, prompt, linesep="\n",
                 log_filename=None, timeout=10, interface=None,
                 status_test_command="echo $?"):
    """
    Log into a remote host (guest) using SSH/Telnet/Netcat.

    :param client: The client to use ('ssh', 'telnet' or 'nc')
    :param host: Hostname or IP address
    :param port: Port to connect to
    :param username: Username (if required)
    :param password: Password (if required)
    :param prompt: Shell prompt (regular expression)
    :param linesep: The line separator to use when sending lines
            (e.g. '\\n' or '\\r\\n')
    :param log_filename: If specified, log all output to this file
    :param timeout: The maximal time duration (in seconds) to wait for
            each step of the login procedure (i.e. the "Are you sure" prompt
            or the password prompt)
    :interface: The interface the neighbours attach to (only use when using ipv6
                linklocal address.)
    :param status_test_command: Command to be used for getting the last
            exit status of commands run inside the shell (used by
            cmd_status_output() and friends).

    :raise LoginError: If using ipv6 linklocal but not assign a interface that
                       the neighbour attache
    :raise LoginBadClientError: If an unknown client is requested
    :raise: Whatever handle_prompts() raises
    :return: A ShellSession object.
    """
    if host and host.lower().startswith("fe80"):
        if not interface:
            raise LoginError("When using ipv6 linklocal an interface must "
                             "be assigned")
        host = "%s%%%s" % (host, interface)
    if client == "ssh":
        cmd = ("ssh -o UserKnownHostsFile=/dev/null "
               "-o StrictHostKeyChecking=no "
               "-o PreferredAuthentications=password -p %s %s@%s" %
               (port, username, host))
    elif client == "telnet":
        cmd = "telnet -l %s %s %s" % (username, host, port)
    elif client == "nc":
        cmd = "nc %s %s" % (host, port)
    else:
        raise LoginBadClientError(client)

    logging.debug("Login command: '%s'", cmd)
    session = aexpect.ShellSession(cmd, linesep=linesep, prompt=prompt,
                                   status_test_command=status_test_command)
    try:
        handle_prompts(session, username, password, prompt, timeout)
    except Exception:
        session.close()
        raise
    if log_filename:
        session.set_output_func(utils_misc.log_line)
        session.set_output_params((log_filename,))
        session.set_log_file(log_filename)
    return session
Exemple #13
0
 def _verify_multipathd_alive():
     """
     Verify whether multipathd statue is active, return bool value
     """
     host_session = aexpect.ShellSession("sh")
     return utils_misc.get_guest_service_status(
         host_session, 'multipathd') == 'active'
Exemple #14
0
    def power_on(self):
        assert not self.is_on()

        self.monitor_socket = tempfile.mktemp()
        self.devices.add_qmp_monitor(self.monitor_socket)
        self._qmp = monitor.QEMUMonitorProtocol(self.monitor_socket,
                                                server=True)
        self.serial_socket = tempfile.mktemp()
        self.devices.add_serial(self.serial_socket)

        tmpl = self.params.get('contents', '/plugins/virt/qemu/template/*')

        if tmpl is None:
            cmdline = self.devices.get_cmdline()
        else:
            tags = self._template_build_tags()
            cmdline = self._template_apply(tmpl, tags)

        try:
            self._popen = process.SubProcess(cmd=cmdline)
            self.pid = self._popen.start()
            self._qmp.accept()
            self.serial_console = aexpect.ShellSession(
                "nc -U %s" % self.serial_socket,
                auto_close=False,
                output_func=genio.log_line,
                output_params=("serial-console-%s.log" % self.short_id,),
                prompt=self.params.get("shell_prompt",
                                       "/plugins/virt/guest/*",
                                       default="[\#\$]"))
            self._screendump_thread_start()
        finally:
            os.remove(self.monitor_socket)
Exemple #15
0
    def cmd_output(self, command, timeout=60):
        """
        Get output from shell session. If the create flag is True, init the
        shell session and set the create flag to False.
        :param command: command to execute in qemu-io
        :param timeout: timeout for execute the command
        """
        qemu_io_cmd = self.qemu_io_cmd
        prompt = self.prompt
        output_func = self.output_func
        output_params = self.output_params
        output_prefix = self.output_prefix
        if self.create_session:
            error.context("Running command: %s" % qemu_io_cmd, self.log_func)
            self.session = aexpect.ShellSession(qemu_io_cmd,
                                                echo=True,
                                                prompt=prompt,
                                                output_func=output_func,
                                                output_params=output_params,
                                                output_prefix=output_prefix)
            # Record the command line in log file
            if self.output_func:
                params = self.output_params + (qemu_io_cmd, )
                self.output_func(*params)

            self.create_session = False
            # Get the reaction from session
            self.session.cmd_output("\n")

        error.context("Executing command: %s" % command, self.log_func)
        return self.session.cmd_output(command, timeout=timeout)
    def test_data_transfer(dev_type):
        """
        Test data transfer between guest and host via console/serial device

        :param dev_type: The device type to be tested, console or channel
        """
        vmxml = vm_xml.VMXML.new_from_dumpxml(vm_name)
        console_xml = vmxml.xmltreefile.find('devices').find(dev_type)
        host_path = console_xml.find('source').get('path')
        guest_path = '/dev/hvc0' if dev_type == 'console' else '/dev/vport0p1'
        test_message = 'virtiochannel'
        cat_cmd = "cat %s" % host_path
        logfile = "test_data_transfer-%s.log" % dev_type
        host_process = aexpect.ShellSession(cat_cmd,
                                            auto_close=False,
                                            output_func=utils_misc.log_line,
                                            output_params=(logfile, ))
        guest_session = vm.wait_for_login()
        guest_session.cmd_output('echo %s > %s' % (test_message, guest_path))
        guest_session.close()
        try:
            host_process.read_until_last_line_matches(test_message, timeout=10)
        except aexpect.exceptions.ExpectError as e:
            test.fail('Did not catch the expected output from host side,'
                      ' the detail of the failure: %s' % str(e))
        finally:
            host_process.close()
Exemple #17
0
def runServer(hostfile, urifile):

    global session
    try:
        server_count = len(genio.read_all_lines(hostfile))

        initial_cmd = "/bin/bash"
        server_cmd = "/home/skirvan/daos_m10/install/bin/orterun --np {0} ".format(
            server_count)
        server_cmd += "--hostfile {0} --enable-recovery ".format(hostfile)
        server_cmd += "--report-uri {0} -x DD_LOG=/mnt/shared/test/tmp/daos.log ".format(
            urifile)
        server_cmd += "-x LD_LIBRARY_PATH=/home/skirvan/daos_m10/install/lib:/home/skirvan/daos_m10/install/lib/daos_srv "
        server_cmd += "/home/skirvan/daos_m10/install/bin/daos_server -g daos_server"

        print "Start CMD>>>>{0}".format(server_cmd)

        session = aexpect.ShellSession(initial_cmd)
        if (session.is_responsive()):
            session.sendline(server_cmd)
            session.read_until_any_line_matches(
                "DAOS server (v0.0.2) started on rank 0*",
                print_func=printFunc)
            print "<SERVER> server started"
    except Exception as e:
        print "<SERVER> Exception occurred: {0}".format(str(e))
        raise ServerFailed("Server didn't start!")
Exemple #18
0
def setup_remote_ssh_key(hostname1, user1, password1,
                         hostname2=None, user2=None, password2=None,
                         port=22, config_options=None, public_key="rsa"):
    """
    Setup up remote to remote login in another server by using public key
    If hostname2 is not supplied, setup to local.

    :param hostname1: the server wants to login other host
    :param hostname2: the server to be logged in
    :type hostname: str
    :param user: user to login
    :type user: str
    :param password: password
    :type password: str
    :param port: port number
    :type port: int
    :param config_options: list of options eg: ["StrictHostKeyChecking=no"]
    :type config_options: list of str
    """
    LOG.debug('Performing SSH key setup on %s:%d as %s.' %
              (hostname1, port, user1))

    try:
        session1 = remote.remote_login(client='ssh', host=hostname1, port=port,
                                       username=user1, password=password1,
                                       prompt=r'[$#%]')
        public_key = get_remote_public_key(session1, public_key=public_key)

        if hostname2 is None:
            # Simply create a session to local
            session2 = aexpect.ShellSession("sh", linesep='\n', prompt='#')
            # set config in local machine
            if config_options:
                for each_option in config_options:
                    session2.cmd_output("echo '%s' >> ~/.ssh/config" %
                                        each_option)
        else:
            session2 = remote.remote_login(client='ssh', host=hostname2,
                                           port=port, username=user2,
                                           password=password2,
                                           prompt=r'[$#%]')
            # set config in remote machine
            if config_options:
                for each_option in config_options:
                    session1.cmd_output("echo '%s' >> ~/.ssh/config" %
                                        each_option)
        session2.cmd_output('mkdir -p ~/.ssh')
        session2.cmd_output('chmod 700 ~/.ssh')
        session2.cmd_output("echo '%s' >> ~/.ssh/authorized_keys; " %
                            public_key)
        session2.cmd_output('chmod 600 ~/.ssh/authorized_keys')
        LOG.debug('SSH key setup on %s complete.', session2)
    except Exception as err:
        LOG.debug('SSH key setup has failed: %s', err)
        try:
            session1.close()
            session2.close()
        except Exception:
            pass
Exemple #19
0
def remote_login(client,
                 host,
                 port,
                 username,
                 password,
                 prompt,
                 linesep="\n",
                 log_filename=None,
                 timeout=10,
                 interface=None):
    """
    log into a remote host(guest) using SSH/Telnet/Netcat.
    :param client: the client to use ('ssh', 'telnet' or the other nc)
    :param host: Hostname or IP address
    :param username: Username (if required)
    :param password: Password (if required)
    :param prompt: shell prompt (regular expression)
    :param linesep: The line separator to use when sending lines (e.g. '\\n' or '\\r\\n')
    :param log_filename: if specified, log all output to this file
    :param timeout: the maximal time duration (in seconds) to wait for
        each step of the login procedure
    :interface: The interface the neighbours attach to (only use when using the ipv6
        linklocal address.)
    :raise LoginError: If using ipv6 linklocal but not assign a interface that the neighbour attache
    :raise LoginBadClientError: If an unknown client is requested
    :raise Whatever handle_prompts() raises
    :return: A ShellSession object
    """

    if host and host.lower.startswith("fe800"):
        if not interface:
            raise LoginError(
                "When using ipv6 linklocal an interface must be assigned")
        host = "%s%%%s" % (host, interface)

    if client == "ssh":
        cmd = (
            "ssh -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=password "
            "-p %s %s@%s " % (port, username, host))
    elif client == "telnet":
        cmd = "telent -l %s %s %s" % (username, host, port)
    else:
        raise LoginBadClientError(client)

    logging.debug("Login Command: '%s'", cmd)
    # need to realize the aexpect.ShellSession
    session = aexpect.ShellSession(cmd, linesep=linesep, prompt=prompt)
    try:
        handle_prompts(session, username, password, prompt, timeout)
    except Exception:
        session.close()
        raise
    if log_filename:
        session.set_output_func(utils.log_line)
        session.set_output_params((log_filename, ))
        session.set_log_file(log_filename)
    return session
Exemple #20
0
    def remote_login(client, host, src, params_login, host_ip):
        src_name = src
        if src != "localhost":
            src_name = src.name
        logging.info("Login %s from %s" % (host, src_name))
        port = params_login["target_port"]
        username = params_login["username"]
        password = params_login["password"]
        prompt = params_login["shell_prompt"]
        linesep = eval("'%s'" % params_login.get("shell_linesep", r"\n"))
        quit_cmd = params.get("quit_cmd", "exit")
        if host == host_ip:
            # Try to login from guest to host.
            prompt = r"^\[.*\][\#\$]\s*$"
            linesep = "\n"
            username = params_login["host_username"]
            password = params_login["host_password"]
            quit_cmd = "exit"

        if client == "ssh":
            # We only support ssh for Linux in this test
            cmd = ("ssh -o UserKnownHostsFile=/dev/null "
                   "-o StrictHostKeyChecking=no "
                   "-o PreferredAuthentications=password -p %s %s@%s" %
                   (port, username, host))
        elif client == "telnet":
            cmd = "telnet -l %s %s %s" % (username, host, port)
        else:
            raise remote.LoginBadClientError(client)

        if src == "localhost":
            logging.debug("Login with command %s" % cmd)
            session = aexpect.ShellSession(cmd, linesep=linesep, prompt=prompt)
        else:
            if params_login.get("os_type") == "windows":
                if client == "telnet":
                    cmd = "C:\\telnet.py %s %s " % (host, username)
                    cmd += "%s \"%s\" && " % (password, prompt)
                    cmd += "C:\\wait_for_quit.py"
                cmd = "%s || ping 127.0.0.1 -n 5 -w 1000 > nul" % cmd
            else:
                cmd += " || sleep 5"
            session = src.wait_for_login()
            logging.debug("Sending login command: %s" % cmd)
            session.sendline(cmd)
        try:
            out = remote.handle_prompts(session, username, password,
                                        prompt, timeout, debug=True)
        except Exception as err:
            session.close()
            raise err
        try:
            session.cmd(quit_cmd)
            session.close()
        except Exception:
            pass
        return out
Exemple #21
0
 def create_isula_shellsession(self, name):
     """Create session to isula container"""
     self.isula_session = aexpect.ShellSession(
         "isula exec -ti %s sh" % name,
         auto_close=False,
         output_func=LOG.debug,
         prompt=r"[\#\$]",
         status_test_command="echo $?")
     return self.isula_session
Exemple #22
0
def run(test, params, env):
    """
    Test virsh nwfilter-edit with uuid.

    1) Prepare parameters.
    2) Run nwfilter-edit command.
    3) Check result.
    4) Clean env
    """
    # Prepare parameters
    filter_name = params.get("edit_filter_name", "")
    status_error = params.get("status_error", "no")
    new_uuid = "11111111-1111-1111-1111-111111111111"
    edit_cmd = ":2s/<uuid>.*$/<uuid>%s<\/uuid>/" % new_uuid

    # Since commit 46a811d, the logic changed for not allow update filter
    # uuid, so decide status_error with libvirt version.
    if libvirt_version.version_compare(1, 2, 7):
        status_error = True
    else:
        status_error = False

    # Backup filter xml
    new_filter = libvirt_xml.NwfilterXML()
    filterxml = new_filter.new_from_filter_dumpxml(filter_name)
    logging.debug("the filter xml is: %s" % filterxml.xmltreefile)

    try:
        # Run command
        session = aexpect.ShellSession("sudo -s")
        try:
            session.sendline("virsh nwfilter-edit %s" % filter_name)
            session.sendline(edit_cmd)
            # Press ESC
            session.send('\x1b')
            # Save and quit
            session.send('ZZ')
            remote.handle_prompts(session, None, None, r"[\#\$]\s*$")
            session.close()
            if not status_error:
                logging.info("Succeed to do nwfilter edit")
            else:
                test.fail("edit uuid should fail but got succeed.")
        except (aexpect.ShellError, aexpect.ExpectError,
                remote.LoginTimeoutError) as details:
            log = session.get_output()
            session.close()
            if "Try again? [y,n,f,?]:" in log and status_error:
                logging.debug("edit uuid failed as expected.")
            else:
                test.fail("Failed to do nwfilter-edit: %s\n%s" %
                          (details, log))
    finally:
        # Clean env
        virsh.nwfilter_undefine(filter_name, debug=True)
        virsh.nwfilter_define(filterxml.xml, debug=True)
Exemple #23
0
def setup_remote_ssh_key(hostname1,
                         user1,
                         password1,
                         hostname2=None,
                         user2=None,
                         password2=None,
                         port=22):
    '''
    Setup up remote to remote login in another server by using public key
    If hostname2 is not supplied, setup to local.

    :param hostname1: the server wants to login other host
    :param hostname2: the server to be logged in
    :type hostname: str
    :param user: user to login
    :type user: str
    :param password: password
    :type password: str
    :param port: port number
    :type port: int
    '''
    logging.debug('Performing SSH key setup on %s:%d as %s.' %
                  (hostname1, port, user1))

    try:
        session1 = remote.remote_login(client='ssh',
                                       host=hostname1,
                                       port=port,
                                       username=user1,
                                       password=password1,
                                       prompt=r'[$#%]')
        public_key = get_remote_public_key(session1)

        if hostname2 is None:
            # Simply create a session to local
            session2 = aexpect.ShellSession("sh", linesep='\n', prompt='#')
        else:
            session2 = remote.remote_login(client='ssh',
                                           host=hostname2,
                                           port=port,
                                           username=user2,
                                           password=password2,
                                           prompt=r'[$#%]')
        session2.cmd_output('mkdir -p ~/.ssh')
        session2.cmd_output('chmod 700 ~/.ssh')
        session2.cmd_output("echo '%s' >> ~/.ssh/authorized_keys; " %
                            public_key)
        session2.cmd_output('chmod 600 ~/.ssh/authorized_keys')
        logging.debug('SSH key setup on %s complete.', session2)
    except Exception as err:
        logging.debug('SSH key setup has failed: %s', err)
        try:
            session1.close()
            session2.close()
        except Exception:
            pass
Exemple #24
0
 def create_serial_control(self):
     """Create serial control"""
     self._wait_console_create()
     self.serial_console = aexpect.ShellSession(
         "/usr/bin/nc -U %s" % self._console_address,
         auto_close=False,
         output_func=self.serial_log.debug,
         prompt=r"[\#\$]",
         status_test_command="echo $?")
     self.console_manager.config_console(self.serial_console)
Exemple #25
0
def check_disconnect_on_shutdown(command, status_error, login_user,
                                 login_passwd, test):
    """
    Test whether an active console will disconnect after shutting down the VM.

    :param command: Test command without --force option
    :param status_error: Whether the command is fault.
    :param login_user: User name for logging into the VM.
    :param login_passwd: Password for logging into the VM.
    :param test: Test Object
    """
    session = aexpect.ShellSession(command)
    if not status_error:
        log = ""
        console_cmd = "shutdown -h now"
        try:
            while True:
                match, text = session.read_until_last_line_matches(
                    [
                        r"[E|e]scape character is", r"login:"******"[P|p]assword:", session.prompt
                    ],
                    10,
                    internal_timeout=1)

                if match == 0:
                    logging.debug("Got '^]', sending '\\n'")
                    session.sendline()
                elif match == 1:
                    logging.debug("Got 'login:'******'%s'", login_user)
                    session.sendline(login_user)
                elif match == 2:
                    logging.debug("Got 'Password:'******'%s'",
                                  login_passwd)
                    session.sendline(login_passwd)
                elif match == 3:
                    logging.debug("Got Shell prompt -- logged in")
                    break

            session.cmd_output(console_cmd)
            # On newer OS like RHEL7, 'shutdown -h now' will not exit before
            # machine shutdown. But on RHEL6, 'shutdown -h now' will exit and
            # allow user to execute another command. This next command will not
            # exit before machine shutdown.
            session.cmd_output("echo $?")
            session.close()
            test.error('Do not expect any command can be executed '
                       'after successfully shutdown')
        except (aexpect.ShellError, aexpect.ExpectError) as detail:
            if 'Shell process terminated' not in str(detail):
                test.fail('Expect shell terminated, but found %s' % detail)
            log = session.get_output()
            logging.debug("Shell terminated on VM shutdown:\n%s\n%s", detail,
                          log)
            session.close()
Exemple #26
0
    def add_running_host(self, log, remote_ip, password):
        cmd = "ssh-copy-id -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=" \
              "no root@%s" % remote_ip

        session = aexpect.ShellSession(cmd, prompt="password:"******"password:"******"Done")
Exemple #27
0
    def _start_remote(self):
        address, port, username, password, prompt = self._remote_opts
        cmd = "%s %s" % (self.command, self.options)
        logging.debug("Run '%s' on host '%s'", cmd, address)
        login_cmd = ("ssh -o UserKnownHostsFile=/dev/null "
                     "-o StrictHostKeyChecking=no "
                     "-o PreferredAuthentications=password -p %s %s@%s" %
                     (port, username, address))

        self._process = aexpect.ShellSession(
            login_cmd, output_func=self._output_logger_handler)
        handle_prompts(self._process, username, password, prompt)
        self._process.sendline(cmd)
Exemple #28
0
    def check_vm_network_accessed(vm_session,
                                  expected_iface_no=3,
                                  ping_dest="8.8.8.8",
                                  timeout=30,
                                  tcpdump_iface=None,
                                  tcpdump_status_error=False):
        """
        Test VM's network by checking ifaces' number and the accessibility

        :param vm_session: The session object to the guest
        :param expected_iface_no: The expected number of ifaces
        :param ping_dest: The destination to be ping
        :param timeout: The timeout of the checking
        :param tcpdump_iface: The interface to check
        :param tcpdump_status_error: Whether the tcpdump's output should include
            the string "ICMP echo request"
        :raise: test.fail when ifaces' number is incorrect or ping fails.
        """
        if not utils_misc.wait_for(
                lambda: check_vm_iface_num(vm_session, expected_iface_no),
                first=3,
                timeout=timeout):
            test.fail("%d interfaces should be found on the vm." %
                      expected_iface_no)
        if tcpdump_iface:
            cmd = "tcpdump  -i %s icmp" % tcpdump_iface
            tcpdump_session = aexpect.ShellSession('bash')
            tcpdump_session.sendline(cmd)

        if not utils_misc.wait_for(
                lambda: not utils_test.ping(ping_dest,
                                            count=3,
                                            timeout=5,
                                            output_func=logging.debug,
                                            session=vm_session)[0],
                first=5,
                timeout=timeout):
            test.fail("Failed to ping %s." % ping_dest)
        if tcpdump_iface:
            output = tcpdump_session.get_stripped_output()
            logging.debug("tcpdump's output: %s.", output)
            pat_str = "ICMP echo request"
            if re.search(pat_str, output):
                if tcpdump_status_error:
                    test.fail(
                        "Get incorrect tcpdump output: {}, it should not "
                        "include '{}'.".format(output, pat_str))
            else:
                if not tcpdump_status_error:
                    test.fail("Get incorrect tcpdump output: {}, it should "
                              "include '{}'.".format(output, pat_str))
    def start_avahi_autoipd(self):
        """
        Start avahi-autoipd on veth0
        verify ip by logging in with the ip
        and check using ip command
        """

        subprocess.Popen("avahi-autoipd veth0 1>%s/out 2>%s/err &" %
                         (self.tmpdir, self.tmpdir),
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
        time.sleep(15)
        result = open("%s/err" % self.tmpdir, "r").readlines()
        for line in result:
            if "Successfully claimed IP address" in line:
                self.ip_addr = line.split()[-1]

        if self.ip_addr is None:
            self.nfail += 1
            raise error.TestError('\n avahi-autoipd failed to assign veth0 ip')
        else:
            logging.info('\nIP assigned is %s' % self.ip_addr)

        pass_word = utils.system_output("openssl passwd -crypt password")
        utils.system("useradd testuser -p %s" % pass_word)

        p = aexpect.ShellSession("ssh testuser@%s" % self.ip_addr)
        time.sleep(5)

        if "Are you sure you want to continue connecting" in p.get_output():
            p.sendline("yes")
            time.sleep(5)
            if "password:"******"password")
            else:
                raise error.TestError(
                    '\n Failed to login giving password to avahi-autoipd ip')
        elif "password:"******"password")
        else:
            print p.get_output()
            raise error.TestError('\n Failed to login to avahi-autoipd ip')

        print p.get_output()
        status, output = p.get_command_status_output(
            "ip addr show veth0|grep -w inet")
        if self.ip_addr not in output:
            self.nfail += 1
            raise error.TestError('\n avahi-autoipd failed to assign valid ip')
        p.close()
Exemple #30
0
def remote_login(client,
                 host,
                 port,
                 username,
                 password,
                 prompt,
                 linesep="\n",
                 log_filename=None,
                 timeout=10):
    """
    Log into a remote host (guest) using SSH/Telnet/Netcat.

    :param client: The client to use ('ssh', 'telnet' or 'nc')
    :param host: Hostname or IP address
    :param port: Port to connect to
    :param username: Username (if required)
    :param password: Password (if required)
    :param prompt: Shell prompt (regular expression)
    :param linesep: The line separator to use when sending lines
            (e.g. '\\n' or '\\r\\n')
    :param log_filename: If specified, log all output to this file
    :param timeout: The maximal time duration (in seconds) to wait for
            each step of the login procedure (i.e. the "Are you sure" prompt
            or the password prompt)
    :raise LoginBadClientError: If an unknown client is requested
    :raise: Whatever handle_prompts() raises
    :return: A ShellSession object.
    """
    if client == "ssh":
        cmd = ("ssh -o UserKnownHostsFile=/dev/null "
               "-o PreferredAuthentications=password -p %s %s@%s" %
               (port, username, host))
    elif client == "telnet":
        cmd = "telnet -l %s %s %s" % (username, host, port)
    elif client == "nc":
        cmd = "nc %s %s" % (host, port)
    else:
        raise LoginBadClientError(client)

    logging.debug("Login command: '%s'", cmd)
    session = aexpect.ShellSession(cmd, linesep=linesep, prompt=prompt)
    try:
        handle_prompts(session, username, password, prompt, timeout)
    except Exception:
        session.close()
        raise
    if log_filename:
        session.set_output_func(utils_misc.log_line)
        session.set_output_params((log_filename, ))
        session.set_log_file(log_filename)
    return session