• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python remote.handle_prompts函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中virttest.remote.handle_prompts函数的典型用法代码示例。如果您正苦于以下问题:Python handle_prompts函数的具体用法?Python handle_prompts怎么用?Python handle_prompts使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了handle_prompts函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: edit_snap_xml

    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), details:
            log = session.get_output()
            session.close()
            raise error.TestFail("Failed to do snapshot-edit: %s\n%s"
                                 % (details, log))
开发者ID:uni-peter-zheng,项目名称:tp-libvirt,代码行数:31,代码来源:virsh_snapshot_edit.py


示例2: virtio_serial_login

    def virtio_serial_login(self, port='vs1'):
        error.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:
            raise error.TestError("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)
            raise error.TestFail("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
开发者ID:Zhengtong,项目名称:tp-qemu,代码行数:30,代码来源:virtio_port_login.py


示例3: edit_image_xml

    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))
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:28,代码来源:virsh_save_image_edit.py


示例4: edit_net_xml

    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: Boolen, 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")
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:32,代码来源:virsh_net_edit.py


示例5: run

def run(test, params, env):
    """
    Test steps:

    1) Check the environment and get the params from params.
    2) while(loop_time < timeout):
            ttcp command.
    3) clean up.
    """
    # Find the ttcp command.
    try:
        path.find_command("ttcp")
    except path.CmdNotFoundError:
        test.cancel("Not find ttcp command on host.")
    # Get VM.
    vms = env.get_all_vms()
    for vm in vms:
        session = vm.wait_for_login()
        status, _ = session.cmd_status_output("which ttcp")
        if status:
            test.cancel("Not find ttcp command on guest.")
    # Get parameters from params.
    timeout = int(params.get("LB_ttcp_timeout", "300"))
    ttcp_server_command = params.get("LB_ttcp_server_command",
                                     "ttcp -s -r -v -D -p5015")
    ttcp_client_command = params.get("LB_ttcp_client_command",
                                     "ttcp -s -t -v -D -p5015 -b65536 -l65536 -n1000 -f K")

    host_session = aexpect.ShellSession("sh")

    try:
        current_time = int(time.time())
        end_time = current_time + timeout
        # Start the loop from current_time to end_time.
        while current_time < end_time:
            for vm in vms:
                session = vm.wait_for_login()
                host_session.sendline(ttcp_server_command)

                cmd = ("%s %s" % (ttcp_client_command, utils_net.get_host_ip_address(params)))

                def _ttcp_good():
                    status, output = session.cmd_status_output(cmd)
                    logging.debug(output)
                    if status:
                        return False
                    return True

                if not utils_misc.wait_for(_ttcp_good, timeout=60):
                    status, output = session.cmd_status_output(cmd)
                    if status:
                        test.fail("Failed to run ttcp command on guest.\n"
                                  "Detail: %s." % output)
                remote.handle_prompts(host_session, None, None, r"[\#\$]\s*$")
                current_time = int(time.time())
    finally:
        # Clean up.
        host_session.close()
        session.close()
开发者ID:balamuruhans,项目名称:tp-libvirt,代码行数:59,代码来源:libvirt_bench_ttcp_from_guest_to_host.py


示例6: conn_setup

    def conn_setup(self):
        """
        Setup of SSH connection.

        (1).Initialization of some variables.
        (2).Check tools.
        (3).Initialization of id_rsa.
        (4).set a ssh_agent.
        (5).copy pub key to server.
        """
        client_session = self.client_session
        ssh_rsa_pub_path = self.ssh_rsa_pub_path
        ssh_id_rsa_path = self.ssh_id_rsa_path
        server_user = self.server_user
        server_ip = self.server_ip
        server_pwd = self.server_pwd
        ssh_keygen = self.SSH_KEYGEN
        ssh_add = self.SSH_ADD
        ssh_copy_id = self.SSH_COPY_ID
        ssh_agent = self.SSH_AGENT
        shell = self.SHELL

        tool_dict = {'ssh_keygen': ssh_keygen,
                     'ssh_add': ssh_add,
                     'ssh_copy_id': ssh_copy_id,
                     'ssh_agent': ssh_agent,
                     'shell': shell}
        for tool_name in tool_dict:
            tool = tool_dict[tool_name]
            if tool is '/bin/true':
                raise ConnToolNotFoundError(tool_name,
                                            "executable not set or found on path,")

        if os.path.exists("/root/.ssh/id_rsa"):
            pass
        else:
            cmd = "%s -t rsa -f /root/.ssh/id_rsa -N '' " % (ssh_keygen)
            status, output = client_session.cmd_status_output(cmd)
            if status:
                raise ConnCmdClientError(cmd, output)

        cmd = "%s %s" % (ssh_agent, shell)
        status, output = client_session.cmd_status_output(cmd)
        if status:
            raise ConnCmdClientError(cmd, output)

        cmd = "%s %s" % (ssh_add, ssh_id_rsa_path)
        status, output = client_session.cmd_status_output(cmd)
        if status:
            raise ConnCmdClientError(cmd, output)

        cmd = "%s -i %s %[email protected]%s" % (ssh_copy_id, ssh_rsa_pub_path,
                                  server_user, server_ip)
        client_session.sendline(cmd)
        try:
            remote.handle_prompts(client_session, server_user,
                                  server_pwd, prompt=r"[\#\$]\s*$")
        except remote.LoginError, detail:
            raise ConnCmdClientError(cmd, detail)
开发者ID:Antique,项目名称:virt-test,代码行数:59,代码来源:utils_conn.py


示例7: run

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)
开发者ID:balamuruhans,项目名称:tp-libvirt,代码行数:55,代码来源:nwfilter_edit_uuid.py


示例8: _start_remote

    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 %[email protected]%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)
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:14,代码来源:ip_sniffing.py


示例9: remote_login

    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))
        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 %[email protected]%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
开发者ID:bssrikanth,项目名称:tp-qemu,代码行数:57,代码来源:openflow_acl_test.py


示例10: execute_ttcp

def execute_ttcp(vm, params):
    """
    Run ttcp between guest and host.

    :param vm: guest vm
    """
    remote_ip = params.get("vfio_remote_ip", "REMOTE_IP.EXAMPLE")
    remote_pwd = params.get("vfio_remote_passwd", "REMOTE_PWD.EXAMPLE")
    if remote_ip.count("EXAMPLE"):
        logging.debug("Please provider remote host for ttcp test.")
        return

    session1 = vm.wait_for_login()
    if session1.cmd_status("which ttcp"):
        session1.close()
        logging.debug("Did not find ttcp command on guest.SKIP...")
        return
    # Check connection first
    try:
        session1.cmd("ping -c 4 %s" % remote_ip)
    except error.CmdError:
        raise error.TestFail("Couldn't connect to %s through %s"
                             % (remote_ip, vm.name))

    # Execute ttcp server on remote host
    ttcp_server = "ttcp -s -r -v -D -p5015"
    session1.sendline("ssh %s" % remote_ip)
    remote.handle_prompts(session1, "root", remote_pwd, r"[\#\$]\s*$",
                          timeout=30, debug=True)
    logging.debug("Executing ttcp server:%s", ttcp_server)
    session1.sendline(ttcp_server)
    # Another session for client
    session2 = vm.wait_for_login()
    ttcp_client = ("ttcp -s -t -v -D -p5015 -b65536 -l65536 -n1000 -f K %s"
                   % remote_ip)
    try:
        ttcp_s, ttcp_o = session2.cmd_status_output(ttcp_client)
        logging.debug(ttcp_o)
        if ttcp_s:
            raise error.TestFail("Run ttcp between %s and %s failed."
                                 % (vm.name, remote_ip))
    finally:
        session1.close()
        session2.close()
开发者ID:Chenditang,项目名称:tp-libvirt,代码行数:44,代码来源:vfio.py


示例11: edit_ifstart_mode

def edit_ifstart_mode(iface_name, old_mode, new_mode):
    """
    Set the start mode of a interface.
    """
    edit_cmd = ":%s/mode='{0}'/mode='{1}'".format(old_mode, new_mode)
    session = aexpect.ShellSession("sudo -s")
    try:
        session.sendline("virsh iface-edit %s" % iface_name)
        logging.info("Change start mode from %s to %s", old_mode, new_mode)
        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 iface-edit: %s\n%s"
                             % (details, log))
开发者ID:lento-sun,项目名称:tp-libvirt,代码行数:19,代码来源:virsh_iface_edit.py


示例12: edit_net_xml

    def edit_net_xml():
        edit_cmd = r":%s /100.254/100.253"

        session = aexpect.ShellSession("sudo -s")
        try:
            logging.info("Execute virsh net-edit %s", net_name)
            session.sendline("virsh net-edit %s" % net_name)

            logging.info("Change the ip value of dhcp end")
            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 net-edit: %s\n%s"
                                 % (details, log))
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:19,代码来源:virsh_net_edit.py


示例13: modify_vcpu

    def modify_vcpu(source, edit_cmd):
        """
        Modify vm's cpu information.

        :param source : virsh edit's option.
        :param dic_mode : a edit commad line .
        :return: True if edit successed,False if edit failed.
        """
        session = aexpect.ShellSession("sudo -s")
        try:
            session.sendline("virsh -c %s edit %s" % (vm.connect_uri, source))
            session.sendline(edit_cmd)
            session.send('\x1b')
            session.send('ZZ')
            remote.handle_prompts(session, None, None, r"[\#\$]\s*$")
            session.close()
            return True
        except:
            return False
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:19,代码来源:virsh_edit.py


示例14: edit_pool

def edit_pool(pool, edit_cmd):
    """
    Edit libvirt storage pool.

    :param pool: pool name or uuid.
    :param edit_cmd : edit commad line.
    """
    session = aexpect.ShellSession("sudo -s")
    try:
        session.sendline("virsh pool-edit %s" % pool)
        for cmd in edit_cmd:
            session.sendline(cmd)
        session.send('\x1b')
        session.send('ZZ')
        remote.handle_prompts(session, None, None, r"[\#\$]\s*$")
        session.close()
        logging.info("Succeed to do pool edit.")
    except (aexpect.ShellError, aexpect.ExpectError), details:
        log = session.get_output()
        session.close()
        raise error.TestFail("Failed to do pool edit: %s\n%s"
                             % (details, log))
开发者ID:PandaWei,项目名称:tp-libvirt,代码行数:22,代码来源:virsh_pool_edit.py


示例15: exec_edit

    def exec_edit(source, edit_cmd):
        """
        Execute edit command.

        :param source : virsh edit's option.
        :param edit_cmd: Edit command list to execute.
        :return: True if edit successed, False if edit failed.
        """
        session = aexpect.ShellSession("sudo -s")
        try:
            session.sendline("virsh -c %s edit %s" % (vm.connect_uri, source))
            for cmd in edit_cmd:
                session.sendline(cmd)
            session.send('\x1b')
            session.send('ZZ')
            remote.handle_prompts(session, None, None, r"[\#\$]\s*$", debug=True)
            session.close()
            return True
        except Exception, e:
            session.close()
            logging.error("Error occured: %s", e)
            return False
开发者ID:zcyes,项目名称:tp-libvirt,代码行数:22,代码来源:virsh_edit.py


示例16: file_transfer

 def file_transfer(sessions, addresses, timeout):
     prepare_cmd = "dd if=/dev/zero of=/tmp/copy_file count=1024 bs=1M"
     md5_cmd = "md5sum /tmp/copy_file"
     port = params.get("shell_port")
     prompt = params.get("shell_prompt")
     username = params.get("username")
     password = params.get("password")
     sessions[0].cmd(prepare_cmd, timeout=timeout)
     ori_md5 = sessions[0].cmd_output(md5_cmd)
     scp_cmd = ("scp -v -o UserKnownHostsFile=/dev/null "
                "-o StrictHostKeyChecking=no "
                "-o PreferredAuthentications=password -r "
                "-P %s /tmp/copy_file %[email protected]\[%s\]:/tmp/copy_file" %
                (port, username, addresses[1]))
     sessions[0].sendline(scp_cmd)
     remote.handle_prompts(sessions[0], username, password, prompt, 600)
     new_md5 = sessions[1].cmd_output(md5_cmd)
     for session in sessions:
         session.cmd("rm -f /tmp/copy_file")
     if new_md5 != ori_md5:
         raise error.TestFail("Md5 value changed after file transfer, "
                              "original is %s and the new file"
                              " is: %s" % (ori_md5, new_md5))
开发者ID:Chenditang,项目名称:tp-qemu,代码行数:23,代码来源:openflow_test.py


示例17: edit_filter_xml

def edit_filter_xml(test, filter_name, edit_cmd):
    """
    Edit network filter xml

    :param filter_name: filter name or uuid
    :param edit_cmd: edit command list in interactive mode
    """
    session = aexpect.ShellSession("sudo -s")
    try:
        session.sendline("virsh nwfilter-edit %s" % filter_name)
        for i in edit_cmd:
            session.sendline(i)
        # Press ESC
        session.send('\x1b')
        # Save and quit
        session.send('ZZ')
        remote.handle_prompts(session, None, None, r"[\#\$]\s*$")
        session.close()
        logging.info("Succeed to do nwfilter edit")
    except (aexpect.ShellError, aexpect.ExpectError) as details:
        log = session.get_output()
        session.close()
        test.fail("Failed to do nwfilter-edit: %s\n%s"
                  % (details, log))
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:24,代码来源:virsh_nwfilter_edit.py


示例18: wait_for_login

    def wait_for_login(self, username, password,
                       timeout=240, internal_timeout=10):
        """
        Make multiple attempts to log into the guest via serial console.

        :param timeout: Time (seconds) to keep trying to log in.
        :param internal_timeout: Timeout to pass to handle_prompts().
        """
        end_time = time.time() + timeout
        while time.time() < end_time:
            try:
                self.sendline()
                remote.handle_prompts(self, username, password,
                                      self.prompt, internal_timeout)
                return
            except aexpect.ExpectTimeoutError as detail:
                raise remote.LoginTimeoutError(detail.output)
            except aexpect.ExpectProcessTerminatedError as detail:
                raise remote.LoginProcessTerminatedError(
                    detail.status, detail.output)
            time.sleep(2)
        # Timeout expired; try one more time but don't catch exceptions
        self.sendline()
        remote.handle_prompts(self, username, password, self.prompt, timeout)
开发者ID:balamuruhans,项目名称:tp-libvirt,代码行数:24,代码来源:serial_functional.py


示例19: run


#.........这里部分代码省略.........
                           "grep {0}".format("vhost_net"))
                    if not utils.system(cmd, ignore_status=True):
                        raise error.TestError("Can't remove "
                                              "vhost_net driver")

            # Attach a interface when vm is shutoff
            if attach_device == 'config':
                iface_mac = utils_net.generate_mac_address_simple()
                iface_xml_obj = create_iface_xml(iface_mac)
                iface_xml_obj.xmltreefile.write()
                ret = virsh.attach_device(vm_name, iface_xml_obj.xml,
                                          flagstr="--config",
                                          ignore_status=True)
                libvirt.check_exit_status(ret)

            # Clone additional vm
            if additional_guest:
                guest_name = "%s_%s" % (vm_name, '1')
                # Clone additional guest
                timeout = params.get("clone_timeout", 360)
                utils_libguestfs.virt_clone_cmd(vm_name, guest_name,
                                                True, timeout=timeout)
                additional_vm = vm.clone(guest_name)
                additional_vm.start()
                #additional_vm.wait_for_login()

            # Start the VM.
            if unprivileged_user:
                virsh.start(vm_name, **virsh_dargs)
                cmd = ("su - %s -c 'virsh console %s'"
                       % (unprivileged_user, vm_name))
                session = aexpect.ShellSession(cmd)
                session.sendline()
                remote.handle_prompts(session, params.get("username"),
                                      params.get("password"), "[\#\$]", 30)
                # Get ip address on guest
                if not get_guest_ip(session, iface_mac):
                    raise error.TestError("Can't get ip address on guest")
            else:
                # Will raise VMStartError exception if start fails
                vm.start()
                if serial_login:
                    session = vm.wait_for_serial_login()
                else:
                    session = vm.wait_for_login()
            if start_error:
                raise error.TestFail("VM started unexpectedly")

            if test_vhost_net:
                if utils.system("lsmod | grep vhost_net", ignore_status=True):
                    raise error.TestFail("vhost_net module can't be"
                                         " loaded automatically")

            # Attach a interface when vm is running
            if attach_device == 'live':
                iface_mac = utils_net.generate_mac_address_simple()
                iface_xml_obj = create_iface_xml(iface_mac)
                iface_xml_obj.xmltreefile.write()
                ret = virsh.attach_device(vm_name, iface_xml_obj.xml,
                                          flagstr="--live",
                                          ignore_status=True)
                libvirt.check_exit_status(ret)
                # Need sleep here for attachment take effect
                time.sleep(5)

            # Update a interface options
开发者ID:nertpinx,项目名称:tp-libvirt,代码行数:67,代码来源:iface_options.py


示例20: run

def run(test, params, env):
    """
    Test the command virsh metadata

    Run in 4 steps:
    1. Set domain metadata
    2. Get domain metadata
    3. Restart libvirtd then get domain metadata again
    4. Remove domain metadata then get domain metadata again
    """
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    metadata_uri = params.get("metadata_uri")
    metadata_key = params.get("metadata_key")
    metadata_value = params.get("metadata_value", "")
    metadata_option = params.get("metadata_option", "")
    virsh_dargs = {'debug': True, 'ignore_status': True}
    metadata_set = "yes" == params.get("metadata_set", "no")
    metadata_get = "yes" == params.get("metadata_get", "yes")
    metadata_remove = "yes" == params.get("metadata_remove", "no")
    restart_libvirtd = "yes" == params.get("restart_libvirtd", "no")
    status_error = "yes" == params.get("status_error", "no")
    if not metadata_uri:
        raise error.TestErrorr("'uri' is needed")
    vmxml = vm_xml.VMXML.new_from_dumpxml(vm_name)
    # Start VM
    if vm.state() != "running":
        vm.destroy()
        vm.start()

    def pretty_xml(xml_str):
        return xml.dom.minidom.parseString(xml_str).toprettyxml()

    def check_result(result, expect_status, expect_output=None):
        """
        Check virsh metadata command
        """
        utlv.check_exit_status(result, expect_status)
        if result.exit_status == 0 and expect_output:
            expect_output = pretty_xml(expect_output)
            logging.debug("Expect metadata: %s", expect_output)
            output = result.stdout.strip()
            output = pretty_xml(output)
            logging.debug("Command get metadata: %s", output)
            if output != expect_output:
                raise error.TestFail("Metadat is not expected")

    def get_metadata():
        """
        Get domain metadata
        """
        option = metadata_option.replace("--edit", "")
        result = virsh.metadata(vm_name,
                                metadata_uri,
                                options=option,
                                key=metadata_key,
                                **virsh_dargs)
        return result

    try:
        # Set metadata XML
        if metadata_set:
            if not metadata_key:
                raise error.TestErrorr("'key' is needed")
            if not metadata_value:
                raise error.TestErrorr("New metadata is needed")
            # Parse metadata value
            if "--edit" in metadata_option:
                virsh_cmd = r"virsh metadata %s --uri %s --key %s %s"
                virsh_cmd = virsh_cmd % (vm_name, metadata_uri,
                                         metadata_key, metadata_option)
                session = aexpect.ShellSession("sudo -s")
                logging.info("Running command: %s", virsh_cmd)
                try:
                    session.sendline(virsh_cmd)
                    session.sendline(r":insert")
                    session.sendline(metadata_value)
                    session.sendline(".")
                    session.send('ZZ')
                    remote.handle_prompts(session, None, None, r"[\#\$]\s*$",
                                          debug=True)
                except Exception, e:
                    logging.error("Error occured: %s", e)
                session.close()
            else:
                result = virsh.metadata(vm_name,
                                        metadata_uri,
                                        options=metadata_option,
                                        key=metadata_key,
                                        new_metadata=metadata_value,
                                        **virsh_dargs)
                check_result(result, status_error)
            if "--config" in metadata_option:
                vm.destroy()
                vm.start()
                check_result(get_metadata(), status_error, metadata_value)
        # Get metadata
        if metadata_get:
            check_result(get_metadata(), status_error, metadata_value)

#.........这里部分代码省略.........
开发者ID:Chenditang,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_metadata.py



注:本文中的virttest.remote.handle_prompts函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python remote.remote_login函数代码示例发布时间:2022-05-26
下一篇:
Python vm_xml.VMXML类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap