Пример #1
0
    def _ssh_execute(self, cmd_list, check_exit_code=True, attempts=1):
        """Execute cli with status update.

        Executes CLI commands where status return is expected.

        cmd_list is a list of commands, where each command is itself
        a list of parameters.  We use utils.check_ssh_injection to check each
        command, but then join then with " ; " to form a single command.
        """

        # Check that each command is secure
        for cmd in cmd_list:
            utils.check_ssh_injection(cmd)

        # Combine into a single command.
        command = ' ; '.join(map(lambda x: ' '.join(x), cmd_list))

        if not self.sshpool:
            self.sshpool = ssh_utils.SSHPool(self.switch_ip,
                                             self.switch_port,
                                             None,
                                             self.switch_user,
                                             self.switch_pwd,
                                             min_size=1,
                                             max_size=5)
        stdin, stdout, stderr = None, None, None
        LOG.debug("Executing command via ssh: %s" % command)
        last_exception = None
        try:
            with self.sshpool.item() as ssh:
                while attempts > 0:
                    attempts -= 1
                    try:
                        stdin, stdout, stderr = ssh.exec_command(command)
                        greenthread.sleep(random.randint(20, 500) / 100.0)
                        channel = stdout.channel
                        exit_status = channel.recv_exit_status()
                        LOG.debug("Exit Status from ssh:%s", exit_status)
                        # exit_status == -1 if no exit code was returned
                        if exit_status != -1:
                            LOG.debug('Result was %s' % exit_status)
                            if check_exit_code and exit_status != 0:
                                raise processutils.ProcessExecutionError(
                                    exit_code=exit_status,
                                    stdout=stdout,
                                    stderr=stderr,
                                    cmd=command)
                            else:
                                return True
                        else:
                            return True
                    except Exception as e:
                        msg = _("Exception: %s") % six.text_type(e)
                        LOG.error(msg)
                        last_exception = e
                        greenthread.sleep(random.randint(20, 500) / 100.0)
                LOG.debug("Handling error case after SSH:%s", last_exception)
                try:
                    raise processutils.ProcessExecutionError(
                        exit_code=last_exception.exit_code,
                        stdout=last_exception.stdout,
                        stderr=last_exception.stderr,
                        cmd=last_exception.cmd)
                except AttributeError:
                    raise processutils.ProcessExecutionError(
                        exit_code=-1,
                        stdout="",
                        stderr="Error running SSH command",
                        cmd=command)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                msg = (_("Error executing command via ssh: %s") %
                       six.text_type(e))
                LOG.error(msg)
        finally:
            if stdin:
                stdin.flush()
                stdin.close()
            if stdout:
                stdout.close()
            if stderr:
                stderr.close()
Пример #2
0
    def run_cmd(self, cmd, ip0, user, pw, *args, **kwargs):
        """Run a command on SMU or using SSH

        :param cmd: ssc command name
        :param ip0: string IP address of controller
        :param user: string user authentication for array
        :param pw: string password authentication for array
        :returns: formated string with version information
        """
        LOG.debug('Enable ssh: %s',
                  six.text_type(self.drv_configs['ssh_enabled']))

        if self.drv_configs['ssh_enabled'] != 'True':
            # Direct connection via ssc
            args = (cmd, '--user', user, '--password', pw, ip0) + args

            try:
                out, err = utils.execute(*args, **kwargs)
                LOG.debug("command %(cmd)s result: out = %(out)s - err = "
                          "%(err)s", {'cmd': cmd, 'out': out, 'err': err})
                return out, err
            except putils.ProcessExecutionError as e:
                if 'Failed to establish SSC connection' in e.stderr:
                    LOG.debug("SSC connection error!")
                    msg = _("Failed to establish SSC connection.")
                    raise exception.HNASConnError(msg)
                elif 'Connection reset' in e.stderr:
                    LOG.debug("HNAS connection reset!")
                    msg = _("HNAS has disconnected SSC")
                    raise exception.HNASConnError(msg)
                else:
                    raise

        else:
            if self.drv_configs['cluster_admin_ip0'] is None:
                # Connect to SMU through SSH and run ssc locally
                args = (cmd, 'localhost') + args
            else:
                args = (cmd, '--smuauth',
                        self.drv_configs['cluster_admin_ip0']) + args

            utils.check_ssh_injection(args)
            command = ' '.join(args)
            command = command.replace('"', '\\"')

            if not self.sshpool:
                server = self.drv_configs['mgmt_ip0']
                port = int(self.drv_configs['ssh_port'])
                username = self.drv_configs['username']
                # We only accept private/public key auth
                password = ""
                privatekey = self.drv_configs['ssh_private_key']
                self.sshpool = ssh_utils.SSHPool(server,
                                                 port,
                                                 None,
                                                 username,
                                                 password=password,
                                                 privatekey=privatekey)

            with self.sshpool.item() as ssh:

                try:
                    out, err = putils.ssh_execute(ssh, command,
                                                  check_exit_code=True)
                    LOG.debug("command %(cmd)s result: out = "
                              "%(out)s - err = %(err)s",
                              {'cmd': cmd, 'out': out, 'err': err})
                    return out, err
                except putils.ProcessExecutionError as e:
                    if 'Failed to establish SSC connection' in e.stderr:
                        LOG.debug("SSC connection error!")
                        msg = _("Failed to establish SSC connection.")
                        raise exception.HNASConnError(msg)
                    else:
                        raise putils.ProcessExecutionError
Пример #3
0
    def _ssh_execute(self, cmd_list, check_exit_code=True, attempts=1):
        """Execute cli with status update.

        Executes CLI commands such as cfgsave where status return is expected.
        """
        utils.check_ssh_injection(cmd_list)
        command = ' '.join(cmd_list)

        if not self.sshpool:
            self.sshpool = ssh_utils.SSHPool(self.switch_ip,
                                             self.switch_port,
                                             None,
                                             self.switch_user,
                                             self.switch_pwd,
                                             self.switch_key,
                                             min_size=1,
                                             max_size=5)
        stdin, stdout, stderr = None, None, None
        LOG.debug("Executing command via ssh: %s", command)
        last_exception = None
        try:
            with self.sshpool.item() as ssh:
                while attempts > 0:
                    attempts -= 1
                    try:
                        stdin, stdout, stderr = ssh.exec_command(command)
                        stdin.write("%s\n" % zone_constant.YES)
                        channel = stdout.channel
                        exit_status = channel.recv_exit_status()
                        LOG.debug("Exit Status from ssh: %s", exit_status)
                        # exit_status == -1 if no exit code was returned
                        if exit_status != -1:
                            LOG.debug('Result was %s', exit_status)
                            if check_exit_code and exit_status != 0:
                                raise processutils.ProcessExecutionError(
                                    exit_code=exit_status,
                                    stdout=stdout,
                                    stderr=stderr,
                                    cmd=command)
                            else:
                                return True
                        else:
                            return True
                    except Exception as e:
                        LOG.exception('Error executing SSH command.')
                        last_exception = e
                        greenthread.sleep(random.randint(20, 500) / 100.0)
                LOG.debug("Handling error case after "
                          "SSH: %s", last_exception)
                try:
                    raise processutils.ProcessExecutionError(
                        exit_code=last_exception.exit_code,
                        stdout=last_exception.stdout,
                        stderr=last_exception.stderr,
                        cmd=last_exception.cmd)
                except AttributeError:
                    raise processutils.ProcessExecutionError(
                        exit_code=-1,
                        stdout="",
                        stderr="Error running SSH command",
                        cmd=command)
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error("Error executing command via ssh: %s", e)
        finally:
            if stdin:
                stdin.flush()
                stdin.close()
            if stdout:
                stdout.close()
            if stderr:
                stderr.close()
Пример #4
0
 def _init_ssh_pool(self, host, port, username, password):
     return ssh_utils.SSHPool(host, port, self.CONNECTION_KEEP_ALIVE,
                              username, password)
Пример #5
0
                desc = _("Error executing EQL command")
                cmdout = '\n'.join(out)
                LOG.error(_LE("%s"), cmdout)
                raise processutils.ProcessExecutionError(
                    stdout=cmdout, cmd=command, description=desc)
            return out
        finally:
            if not completed:
                LOG.debug("Timed out executing command: '%s'", command)
            chan.close()




sshpool = ssh_utils.SSHPool(
                "192.168.1.48",
                2222,
                10,
                "root",
                password="******",
                privatekey="/root/.ssh/id_dsa");

#                min_size=min_size,
#                max_size=max_size)


#paramiko.client.SSHClient
with sshpool.item() as ssh:
    b=ssh.get();
    #print b;
Пример #6
0
    def get_device_mapping_from_network(self, initiator_wwn_list,
                                        target_wwn_list):
        """Provides the initiator/target map for available SAN contexts.

        Looks up nameserver of each fc SAN configured to find logged in devices
        and returns a map of initiator and target port WWNs for each fabric.

        :param initiator_wwn_list: List of initiator port WWN
        :param target_wwn_list: List of target port WWN
        :returns: List -- device wwn map in following format
            {
                <San name>: {
                    'initiator_port_wwn_list':
                    ('200000051e55a100', '200000051e55a121'..)
                    'target_port_wwn_list':
                    ('100000051e55a100', '100000051e55a121'..)
                }
            }
        :raises: Exception when connection to fabric is failed
        """
        device_map = {}
        formatted_target_list = []
        formatted_initiator_list = []
        fabric_map = {}
        fabric_names = self.configuration.fc_fabric_names
        fabrics = None
        if not fabric_names:
            raise exception.InvalidParameterValue(
                err=_("Missing Fibre Channel SAN configuration "
                      "param - fc_fabric_names"))

        fabrics = [x.strip() for x in fabric_names.split(',')]
        LOG.debug("FC Fabric List: %s", fabrics)
        if fabrics:
            for t in target_wwn_list:
                formatted_target_list.append(self.get_formatted_wwn(t))

            for i in initiator_wwn_list:
                formatted_initiator_list.append(self.get_formatted_wwn(i))

            for fabric_name in fabrics:
                fabric_ip = self.fabric_configs[fabric_name].safe_get(
                    'fc_fabric_address')
                fabric_user = self.fabric_configs[fabric_name].safe_get(
                    'fc_fabric_user')
                fabric_pwd = self.fabric_configs[fabric_name].safe_get(
                    'fc_fabric_password')
                fabric_port = self.fabric_configs[fabric_name].safe_get(
                    'fc_fabric_port')

                ssh_pool = ssh_utils.SSHPool(fabric_ip,
                                             fabric_port,
                                             None,
                                             fabric_user,
                                             password=fabric_pwd)

                # Get name server data from fabric and find the targets
                # logged in
                nsinfo = ''
                try:
                    LOG.debug("Getting name server data for "
                              "fabric %s", fabric_ip)
                    nsinfo = self.get_nameserver_info(ssh_pool)
                except exception.FCSanLookupServiceException:
                    with excutils.save_and_reraise_exception():
                        LOG.error(
                            _LE("Failed collecting name server info from"
                                " fabric %s"), fabric_ip)
                except Exception as e:
                    msg = _("SSH connection failed "
                            "for %(fabric)s with error: %(err)s") % {
                                'fabric': fabric_ip,
                                'err': e
                            }
                    LOG.error(msg)
                    raise exception.FCSanLookupServiceException(message=msg)

                LOG.debug("Lookup service:nsinfo-%s", nsinfo)
                LOG.debug("Lookup service:initiator list from "
                          "caller-%s", formatted_initiator_list)
                LOG.debug("Lookup service:target list from "
                          "caller-%s", formatted_target_list)
                visible_targets = [
                    x for x in nsinfo if x in formatted_target_list
                ]
                visible_initiators = [
                    x for x in nsinfo if x in formatted_initiator_list
                ]

                if visible_targets:
                    LOG.debug("Filtered targets is: %s", visible_targets)
                    # getting rid of the : before returning
                    for idx, elem in enumerate(visible_targets):
                        elem = str(elem).replace(':', '')
                        visible_targets[idx] = elem
                else:
                    LOG.debug("No targets are in the nameserver for SAN %s",
                              fabric_name)

                if visible_initiators:
                    # getting rid of the : before returning ~sk
                    for idx, elem in enumerate(visible_initiators):
                        elem = str(elem).replace(':', '')
                        visible_initiators[idx] = elem
                else:
                    LOG.debug(
                        "No initiators are in the nameserver "
                        "for SAN %s", fabric_name)

                fabric_map = {
                    'initiator_port_wwn_list': visible_initiators,
                    'target_port_wwn_list': visible_targets
                }
                device_map[fabric_name] = fabric_map
        LOG.debug("Device map for SAN context: %s", device_map)
        return device_map