コード例 #1
0
def ssh_to_cumulus_server(server=None, user=None, password=None, prompt=None):
    if server is None:
        server = CumulusCreds.HOST
    if user is None:
        user = CumulusCreds.LINUX_USER
    if password is None:
        password = CumulusCreds.LINUX_PASSWORD

    if prompt is None:
        prompt = Prompt.CONTROLLER_PROMPT

    server_conn = SSHClient(server,
                            user=user,
                            password=password,
                            initial_prompt=prompt)
    server_conn.connect()

    try:
        yield server_conn
    finally:
        server_conn.close()
コード例 #2
0
def ssh_to_compliance_server(server=None,
                             user=None,
                             password=None,
                             prompt=None):
    """
    ssh to given compliance server

    Args:
        server:
        user (str):
        password (str):
        prompt (str|None): expected prompt. such as: cumulus@tis-compliance-test-node:~$

    Yields (SSHClient): ssh client for given compliance server and user

    """
    if server is None:
        server = ComplianceCreds.get_host()
    if user is None:
        user = ComplianceCreds.get_user()
    if password is None:
        password = ComplianceCreds.get_password()

    set_ps1 = False
    if prompt is None:
        prompt = r'.*{}@.*:.*\$ '.format(user)
        set_ps1 = True
    server_conn = SSHClient(server,
                            user=user,
                            password=password,
                            initial_prompt=prompt)
    server_conn.connect()
    if set_ps1:
        server_conn.exec_cmd(r'export PS1="\u@\h:\w\$ "')

    try:
        yield server_conn
    finally:
        server_conn.close()
コード例 #3
0
def test_root_access_denied(keyfile_setup):
    """
    Verify SSH root access to the regular lab is rejected after the change to sshd_config

    Skip Condition:
        - N/A

    Test Setup:

    Test Steps:
        -Generate an SSH key-pair ssh-keygen -t rsa
        - Copy the Public key over the Lab controller scp ~/.ssh/<id_rsa.pub> sysadmin@<lab.ip>
        - Copy the public key from your sysadmin account into the “authorized_keys” file of the “root” account
            *login to controller
            *do sudo su to get to root
            *create folder/file: /root/.ssh/authorized_keys if they do not exist
            *cat /home/sysadmin/<id_rsa.pub/  >> /root/.ssh/authorized_keys

        - This adds your key into the roots authorized_ssh key
        - Now login from your desktop using Ssh –I <public_key> root@<lab.ip>
        - on attempting to ssh with root(with/without password). The user will now get  "Permission denied" Error.

    """

    # attempt to access the lab as root
    lab = ProjVar.get_var("LAB")
    con_ssh = SSHClient(lab['floating ip'], 'root', 'Li69nux*',
                        CONTROLLER_PROMPT)

    # this is expected to fail with permission denied exception
    LOG.tc_step(
        "check permission denied exception is raised when logging in as root")
    with raises(Exception) as excinfo:
        con_ssh.connect(retry=False, retry_timeout=30)
        con_ssh.close()
    assert 'permission denied' in str(excinfo.value)
コード例 #4
0
ファイル: multi_thread.py プロジェクト: starlingx/test
    def run(self):
        """
        Do not run this command. Start threads from start_thread functions
        Returns:

        """
        LOG.info("Starting {}".format(self.name))
        # run the function
        try:
            MThread.running_threads.append(self)
            LOG.info("Connecting to lab fip in new thread...")
            lab = ProjVar.get_var('lab')
            lab_fip = lab['floating ip']
            con_ssh = SSHClient(lab_fip)
            con_ssh.connect(use_current=False)
            ControllerClient.set_active_controller(con_ssh)

            if ProjVar.get_var('IS_DC'):
                LOG.info("Connecting to subclouds fip in new thread...")
                ControllerClient.set_active_controller(con_ssh, 'RegionOne')
                con_ssh_dict = ControllerClient.get_active_controllers_map()
                for name in con_ssh_dict:
                    if name in lab:
                        subcloud_fip = lab[name]['floating ip']
                        subcloud_ssh = SSHClient(subcloud_fip)
                        try:
                            subcloud_ssh.connect(use_current=False)
                            ControllerClient.set_active_controller(
                                subcloud_ssh, name=name)
                        except:
                            if name == ProjVar.get_var('PRIMARY_SUBCLOUD'):
                                raise
                            LOG.warning('Cannot connect to {}'.format(name))

            LOG.info("Connecting to NatBox in new thread...")
            NATBoxClient.set_natbox_client()

            LOG.info("Execute function {}({}, {})".format(
                self.func.__name__, self.args, self.kwargs))
            self._output = self.func(*self.args, **self.kwargs)
            LOG.info("{} returned: {}".format(self.func.__name__,
                                              self._output.__str__()))
            self._output_returned.set()
        except:
            err = traceback.format_exc()
            # LOG.error("Error found in thread call {}".format(err))
            self._err = err
            raise
        finally:
            LOG.info("Terminating thread: {}".format(self.thread_id))
            if ProjVar.get_var('IS_DC'):
                ssh_clients = ControllerClient.get_active_controllers(
                    current_thread_only=True)
                for con_ssh in ssh_clients:
                    con_ssh.close()
            else:
                ControllerClient.get_active_controller().close()

            natbox_ssh = NATBoxClient.get_natbox_client()
            if natbox_ssh:
                natbox_ssh.close()

            LOG.debug("{} has finished".format(self.name))
            MThread.running_threads.remove(self)
コード例 #5
0
def ssh_to_remote_node(host,
                       username=None,
                       password=None,
                       prompt=None,
                       ssh_client=None,
                       use_telnet=False,
                       telnet_session=None):
    """
    ssh to a external node from sshclient.

    Args:
        host (str|None): hostname or ip address of remote node to ssh to.
        username (str):
        password (str):
        prompt (str):
        ssh_client (SSHClient): client to ssh from
        use_telnet:
        telnet_session:

    Returns (SSHClient): ssh client of the host

    Examples: with ssh_to_remote_node('128.224.150.92) as remote_ssh:
                  remote_ssh.exec_cmd(cmd)
\    """

    if not host:
        raise exceptions.SSHException(
            "Remote node hostname or ip address must be provided")

    if use_telnet and not telnet_session:
        raise exceptions.SSHException(
            "Telnet session cannot be none if using telnet.")

    if not ssh_client and not use_telnet:
        ssh_client = ControllerClient.get_active_controller()

    if not use_telnet:
        from keywords.security_helper import LinuxUser
        default_user, default_password = LinuxUser.get_current_user_password()
    else:
        default_user = HostLinuxUser.get_user()
        default_password = HostLinuxUser.get_password()

    user = username if username else default_user
    password = password if password else default_password
    if use_telnet:
        original_host = telnet_session.exec_cmd('hostname')[1]
    else:
        original_host = ssh_client.host

    if not prompt:
        prompt = '.*' + host + r'\:~\$'

    remote_ssh = SSHClient(host,
                           user=user,
                           password=password,
                           initial_prompt=prompt)
    remote_ssh.connect()
    current_host = remote_ssh.host
    if not current_host == host:
        raise exceptions.SSHException(
            "Current host is {} instead of {}".format(current_host, host))
    try:
        yield remote_ssh
    finally:
        if current_host != original_host:
            remote_ssh.close()