Ejemplo n.º 1
0
 def __init__(self, ls_name):
     CommandMode.__init__(
         self,
         self.PROMPT_TEMPLATE.format(ls_name=ls_name),
         self.ENTER_COMMAND,
         self.EXIT_COMMAND,
         enter_action_map=self.enter_action_map(),
         exit_action_map=self.exit_action_map(),
         enter_error_map=self.enter_error_map(),
         exit_error_map=self.exit_error_map(),
         use_exact_prompt=True,
     )
Ejemplo n.º 2
0
    def _run_ftp_template(self,
                          url_obj,
                          command_template,
                          action_map=None,
                          error_map=None,
                          **kwargs):
        ftp_action_map = OrderedDict([
            (
                r"[Nn]ame|[Uu]sername|[Ll]ogin.*:",
                lambda s, l: s.send_line(url_obj.username, l),
            ),
            (r"[Pp]assword.*:", lambda s, l: s.send_line(url_obj.password, l)),
            (
                r"[Ll]ogin incorrect|failed",
                lambda s, l: self._exception(
                    "Login or Password is not correct."),
            ),
            (
                r"[Cc]onnection timed out|[Nn]ot connected",
                lambda s, l: self._exception("Cannot connect to ftp host."),
            ),
        ])
        ftp_error_map = OrderedDict([
            (r"[Ll]ogin incorrect|failed",
             "Login or Password is not correct."),
            (
                r"[Cc]onnection timed out|[Nn]ot connected",
                "Cannot connect to ftp host.",
            ),
        ])

        ftp_command_mode = CommandMode(
            r"ftp>",
            enter_command="ftp {} {}".format(url_obj.hostname, url_obj.port
                                             or "21"),
            exit_command="exit",
            enter_action_map=ftp_action_map,
            enter_error_map=ftp_error_map,
        )
        try:
            with self._cli_service.enter_mode(ftp_command_mode):
                return CommandTemplateExecutor(
                    cli_service=self._cli_service,
                    error_map=error_map,
                    action_map=action_map,
                    command_template=command_template,
                ).execute_command(**kwargs)
        finally:
            # Fix for https://github.com/QualiSystems/cloudshell-cli/issues/113
            if self._cli_service.command_mode == ftp_command_mode:
                ftp_command_mode.step_down(self._cli_service, self._logger)
    def __init__(self, resource_config, api):
        """Initialize Config command mode.

        :param resource_config:
        """
        self.resource_config = resource_config
        self._api = api

        CommandMode.__init__(
            self,
            AristaConfigCommandMode.PROMPT,
            AristaConfigCommandMode.ENTER_COMMAND,
            AristaConfigCommandMode.EXIT_COMMAND,
            enter_action_map=self.enter_action_map(),
        )
    def __init__(self, resource_config, api):
        """Initialize Enable command mode - default command mode for Arista Shells.

        :param resource_config:
        """
        self.resource_config = resource_config
        self._api = api

        CommandMode.__init__(
            self,
            AristaEnableCommandMode.PROMPT,
            AristaEnableCommandMode.ENTER_COMMAND,
            AristaEnableCommandMode.EXIT_COMMAND,
            enter_action_map=self.enter_action_map(),
        )
    def __init__(self, resource_config, api):
        """Initialize Default command mode.

        only for cases when session started not in enable mode
        :param resource_config:
        """
        self.resource_config = resource_config
        self._api = api

        CommandMode.__init__(
            self,
            AristaDefaultCommandMode.PROMPT,
            AristaDefaultCommandMode.ENTER_COMMAND,
            AristaDefaultCommandMode.EXIT_COMMAND,
        )
Ejemplo n.º 6
0
    def __init__(self, resource_config):
        """Initialize Default command mode."""
        """Only for cases when session started not in enable mode."""
        self.resource_config = resource_config

        CommandMode.__init__(
            self,
            MaintenanceCommandMode.PROMPT,
            MaintenanceCommandMode.ENTER_COMMAND,
            MaintenanceCommandMode.EXIT_COMMAND,
        )

        super(MaintenanceCommandMode,
              self).__init__(self.PROMPT, self.ENTER_COMMAND,
                             self.EXIT_COMMAND)
Ejemplo n.º 7
0
    def __init__(self, resource_config):
        """Initialize Enable command mode - default command mode for Cisco Shells.

        :param resource_config:
        """
        self.resource_config = resource_config

        CommandMode.__init__(
            self,
            EnableCommandMode.PROMPT,
            EnableCommandMode.ENTER_COMMAND,
            EnableCommandMode.EXIT_COMMAND,
            enter_action_map=self.enter_action_map(),
            exit_action_map=self.exit_action_map(),
            enter_error_map=self.enter_error_map(),
            exit_error_map=self.exit_error_map(),
        )
Ejemplo n.º 8
0
    def __init__(self, resource_config):
        """Initialize Config command mode.

        :param resource_config:
        """
        self.resource_config = resource_config

        CommandMode.__init__(
            self,
            ConfigCommandMode.PROMPT,
            ConfigCommandMode.ENTER_COMMAND,
            ConfigCommandMode.EXIT_COMMAND,
            enter_action_map=self.enter_action_map(),
            exit_action_map=self.exit_action_map(),
            enter_error_map=self.enter_error_map(),
            exit_error_map=self.exit_error_map(),
        )
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
Ejemplo n.º 10
0
    def __init__(self, resource_config):
        """Initialize Default command mode.

        Only for cases when session started not in enable mode

        :param resource_config:
        """
        self.resource_config = resource_config

        CommandMode.__init__(
            self,
            DefaultCommandMode.PROMPT,
            DefaultCommandMode.ENTER_COMMAND,
            DefaultCommandMode.EXIT_COMMAND,
            enter_action_map=self.enter_action_map(),
            exit_action_map=self.exit_action_map(),
            enter_error_map=self.enter_error_map(),
            exit_error_map=self.exit_error_map(),
        )
    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)
Ejemplo n.º 12
0
    def test_get_all_attached_command_mode(self):
        class CommandModeA(CommandMode):
            pass

        class CommandModeB(CommandMode):
            pass

        CommandMode.RELATIONS_DICT = {CommandModeA: {CommandModeB: {}}}

        command_modes = list(CommandMode.get_all_attached_command_modes())

        self.assertEqual(command_modes, [CommandModeA, CommandModeB])
Ejemplo n.º 13
0
 def setUp(self):
     self._prompt = Mock()
     self._enter_command = Mock()
     self._enter_action_map = Mock()
     self._enter_error_map = Mock()
     self._exit_command = Mock()
     self._exit_action_map = Mock()
     self._exit_error_map = Mock()
     self._enter_actions = Mock()
     self._session = Mock()
     self._command_mode = CommandMode(
         self._prompt,
         enter_command=self._enter_command,
         enter_action_map=self._enter_action_map,
         enter_error_map=self._enter_error_map,
         exit_command=self._exit_command,
         exit_action_map=self._exit_action_map,
         exit_error_map=self._exit_error_map,
         enter_actions=self._enter_actions,
         use_exact_prompt=False,
     )
     self._logger = Mock()
 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 __init__(self, ip, user, password, prompt="#"):
     self.cli = CLI()
     self.mode = CommandMode(prompt)
     self.session_types = [
         SSHSession(host=ip, username=user, password=password)
     ]
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
class TestCommandMode(TestCase):
    def setUp(self):
        self._prompt = Mock()
        self._enter_command = Mock()
        self._enter_action_map = Mock()
        self._enter_error_map = Mock()
        self._exit_command = Mock()
        self._exit_action_map = Mock()
        self._exit_error_map = Mock()
        self._enter_actions = Mock()
        self._session = Mock()
        self._command_mode = CommandMode(
            self._prompt,
            enter_command=self._enter_command,
            enter_action_map=self._enter_action_map,
            enter_error_map=self._enter_error_map,
            exit_command=self._exit_command,
            exit_action_map=self._exit_action_map,
            exit_error_map=self._exit_error_map,
            enter_actions=self._enter_actions,
            use_exact_prompt=False,
        )
        self._logger = Mock()

    def test_init(self):
        attributes = [
            "_enter_error_map",
            "_prompt",
            "_enter_command",
            "_exit_error_map",
            "_exit_command",
            "child_nodes",
            "_exit_action_map",
            "_enter_actions",
            "parent_node",
            "_enter_action_map",
            "_use_exact_prompt",
            "_exact_prompt",
        ]

        self.assertTrue(
            len(
                set(attributes).difference(
                    set(self._command_mode.__dict__.keys()))) == 0)

    def test_add_parent_mode(self):
        mode = Mock()
        self._command_mode.add_parent_mode(mode)
        mode.add_child_node.assert_called_once_with(self._command_mode)

    def test_step_up_send_command(self):
        cli_service = Mock()
        self._command_mode.step_up(cli_service, self._logger)
        cli_service.send_command.assert_called_once_with(
            self._enter_command,
            expected_string=self._prompt,
            action_map=self._enter_action_map,
            error_map=self._enter_error_map,
        )

    def test_step_up_set_command_mode(self):
        cli_service = Mock()
        self._command_mode.step_up(cli_service, self._logger)
        self.assertTrue(cli_service.command_mode == self._command_mode)

    def test_step_up_call_enter_actions(self):
        cli_service = Mock()
        enter_actions = Mock()
        self._command_mode.enter_actions = enter_actions
        self._command_mode.step_up(cli_service, self._logger)
        enter_actions.assert_called_once_with(cli_service)

    def test_step_down_sent_command(self):
        cli_service = Mock()
        parent_prompt = Mock()
        parent_node = Mock()
        parent_node.prompt = parent_prompt
        self._command_mode.parent_node = parent_node
        self._command_mode.step_down(cli_service, self._logger)
        cli_service.send_command.assert_called_once_with(
            self._exit_command,
            expected_string=parent_prompt,
            action_map=self._exit_action_map,
            error_map=self._exit_error_map,
        )

    def test_step_down_set_mode(self):
        cli_service = Mock()
        parent_prompt = Mock()
        parent_node = Mock()
        parent_node.prompt = parent_prompt
        self._command_mode.parent_node = parent_node
        self._command_mode.step_down(cli_service, self._logger)
        self.assertTrue(cli_service.command_mode == parent_node)

    def test_get_all_attached_command_mode(self):
        class CommandModeA(CommandMode):
            pass

        class CommandModeB(CommandMode):
            pass

        CommandMode.RELATIONS_DICT = {CommandModeA: {CommandModeB: {}}}

        command_modes = list(CommandMode.get_all_attached_command_modes())

        self.assertEqual(command_modes, [CommandModeA, CommandModeB])

    def test_is_attached_command_mode(self):
        class CommandModeA(CommandMode):
            pass

        class CommandModeB(CommandMode):
            pass

        CommandMode.RELATIONS_DICT = {CommandModeA: {}}

        command_mode_a = CommandModeA("")
        command_mode_b = CommandModeB("")

        self.assertTrue(command_mode_a.is_attached_command_mode())
        self.assertFalse(command_mode_b.is_attached_command_mode())