class SSHHandler:
    def __init__(self, ip, user, password, prompt="#"):
        self.cli = CLI()
        self.mode = CommandMode(prompt)
        self.session_types = [
            SSHSession(host=ip, username=user, password=password)
        ]

    def send_command(self, command):
        with self.cli.get_session(self.session_types,
                                  self.mode) as cli_service:
            output = cli_service.send_command(command)
        return output
class CreateSession():
    def __init__(self, host, username, password, logger=None, base_mode="#"):
        self.cli = CLI()
        self.logger = logger
        self.mode = CommandMode(fr'{base_mode}')  # for example r'%\s*$'
        enable_action_map = {
            "[Pp]assword for {}".format(username):
            lambda session, logger: session.send_line(password, logger)
        }
        self.elevated_mode = CommandMode(r'(?:(?!\)).)#\s*$',
                                         enter_command='sudo su',
                                         exit_command='exit',
                                         enter_action_map=enable_action_map)
        self.mode.add_child_node(self.elevated_mode)
        self.elevated_mode.add_parent_mode(self.mode)
        self.session_types = [
            SSHSession(host=host, username=username, password=password)
        ]

        self.session = self.cli.get_session(
            command_mode=self.mode, defined_sessions=self.session_types)

    def send_terminal_command(self, command, password=None):
        outp = []
        out = None
        with self.session as my_session:
            if isinstance(command, list):
                for single_command in command:
                    if password:
                        single_command = '{command}'.format(
                            command=single_command, password=password)
                        # single_command = 'echo {password} | sudo -S sh -c "{command}"'.format(command=single_command,
                        #                                                               password=password)
                    self.logger.info(
                        'sending command {}'.format(single_command))
                    current_outp = my_session.send_command(single_command)
                    outp.append(current_outp)
                    self.logger.info('got output {}'.format(current_outp))
                    out = '\n'.join(outp)
            else:
                if password:
                    command = '{command}'.format(command=command)
                out = my_session.send_command(command)
            return out
class CreateSession():
    COMMAND_MODE_PROMPT = r'#'

    def __init__(self, host, username, password, logger=None):
        """
        :param host:
        :param username:
        :param password:
        :param logger:
        """
        self.cli = CLI()
        self.logger = logger
        self.mode = CommandMode(
            prompt=self.COMMAND_MODE_PROMPT)  # for example r'%\s*$'
        self.session_types = [
            SSHSession(host=host, username=username, password=password)
        ]
        self.session = self.cli.get_session(
            command_mode=self.mode, defined_sessions=self.session_types)

    def send_terminal_command(self,
                              single_command,
                              action_map=None,
                              error_map=None):
        """
        :param str single_command:
        :return:
        """
        if not isinstance(single_command, str):
            raise Exception(
                "Expected string input for command. Received type {}, {}.".
                format(type(single_command), str(single_command)))
        with self.session as my_session:
            outp = self._send_single_command(my_session, single_command,
                                             action_map, error_map)
            return r"{}".format(outp)

    def send_commands_list(self, commands_list):
        """
        iterate over list and return concatenated output
        :param list commands_list:
        :return:
        """
        if not isinstance(commands_list, list):
            raise Exception(
                "this method accepts a list. Input: {}".format(commands_list))
        multi_command_outp = []
        with self.session as my_session:
            if isinstance(commands_list, list):
                for single_command in commands_list:
                    outp = self._send_single_command(my_session,
                                                     single_command)
                    multi_command_outp.append(outp)
                final_outp = '\n'.join(multi_command_outp)
                return r"{}".format(final_outp)

    def _send_single_command(self,
                             session,
                             single_command,
                             action_map=None,
                             error_map=None):
        """

        :param session:
        :param single_command:
        :return:
        """
        single_command = '{}'.format(single_command)
        if self.logger:
            self.logger.info('sending command {}'.format(single_command))
        current_outp = session.send_command(single_command,
                                            action_map=action_map,
                                            error_map=error_map)
        if self.logger:
            self.logger.info('got output {}'.format(current_outp))
        return current_outp
예제 #4
0
from cloudshell.cli.service.cli import CLI
from cloudshell.cli.session.ssh_session import SSHSession
from cloudshell.cli.service.command_mode import CommandMode

host = "192.168.105.40"
username = "******"
password = "******"

cli = CLI()
mode = CommandMode(r'#')  # for example r'%\s*$'

session_types = [SSHSession(host=host, username=username, password=password)]

# extract a session from the pool, send the command and return the session to the pool upon completing the "with"
# block:
with cli.get_session(session_types, mode) as cli_service:
    out = cli_service.send_command('show interface | no-more')
    print(out)