Ejemplo n.º 1
0
    def connect(self, re_string=''):
        """Open ssh or telnet connection to device

        :param re_string: expected string
        :return:
        """

        try:
            self._session_handler.connect(re_string)
            if self._console_port:
                self._connect_to_console(re_string)
        except Exception as error_object:
            if re.search('incompatible version',
                         str(error_object).lower()) is None:
                self._session_handler = TelnetSession(self._console_username,
                                                      self._console_password,
                                                      self._console_host,
                                                      port=23,
                                                      logger=self.logger)
                self._session_handler.connect(re_string)

                if self._console_port:
                    self._connect_to_console(re_string)
            else:
                raise error_object
 def test_eq(self, expect_session):
     self._instance = TelnetSession(
         self._hostname,
         self._username,
         self._password,
         port=self._port,
         on_session_start=self._on_session_start,
     )
     self.assertTrue(
         self._instance.__eq__(
             TelnetSession(
                 self._hostname,
                 self._username,
                 self._password,
                 port=self._port,
                 on_session_start=self._on_session_start,
             )))
     self.assertFalse(
         self._instance.__eq__(
             TelnetSession(
                 self._hostname,
                 "incorrect_username",
                 self._password,
                 port=self._port,
                 on_session_start=self._on_session_start,
             )))
     self.assertFalse(
         self._instance.__eq__(
             TelnetSession(
                 self._hostname,
                 self._username,
                 "incorrect_password",
                 port=self._port,
                 on_session_start=self._on_session_start,
             )))
 def test_init_attributes(self, connection_params, expect_session):
     self._instance = TelnetSession(self._hostname,
                                    self._username,
                                    self._password,
                                    port=self._port,
                                    on_session_start=self._on_session_start)
     mandatory_attributes = ['username', '_handler', 'password']
     self.assertEqual(
         len(
             set(mandatory_attributes).difference(
                 set(self._instance.__dict__.keys()))), 0)
class TestTelnetSession(TestCase):
    def setUp(self):
        self._username = '******'
        self._password = '******'
        self._hostname = 'hostname'
        self._port = 22
        self._on_session_start = Mock()

    @patch('cloudshell.cli.session.telnet_session.ExpectSession')
    @patch('cloudshell.cli.session.telnet_session.ConnectionParams')
    def test_init_attributes(self, connection_params, expect_session):
        self._instance = TelnetSession(self._hostname,
                                       self._username,
                                       self._password,
                                       port=self._port,
                                       on_session_start=self._on_session_start)
        mandatory_attributes = ['username', '_handler', 'password']
        self.assertEqual(
            len(
                set(mandatory_attributes).difference(
                    set(self._instance.__dict__.keys()))), 0)

    @patch('cloudshell.cli.session.ssh_session.ExpectSession')
    def test_eq(self, expect_session):
        self._instance = TelnetSession(self._hostname,
                                       self._username,
                                       self._password,
                                       port=self._port,
                                       on_session_start=self._on_session_start)
        self.assertTrue(
            self._instance.__eq__(
                TelnetSession(self._hostname,
                              self._username,
                              self._password,
                              port=self._port,
                              on_session_start=self._on_session_start)))
        self.assertFalse(
            self._instance.__eq__(
                TelnetSession(self._hostname,
                              'incorrect_username',
                              self._password,
                              port=self._port,
                              on_session_start=self._on_session_start)))
        self.assertFalse(
            self._instance.__eq__(
                TelnetSession(self._hostname,
                              self._username,
                              'incorrect_password',
                              port=self._port,
                              on_session_start=self._on_session_start)))
    def test_intialize_session(self, telnet_lib):
        # Setup
        telnet_mock = Mock()
        telnet_lib.Telnet.return_value = telnet_mock
        hostname = "localhost"
        self._instance = TelnetSession(
            hostname,
            self._username,
            "incorrect_password",
            port=self._port,
            on_session_start=self._on_session_start,
        )

        # Act
        self._instance._initialize_session(">", logger=Mock())

        # Assert
        self.assertIsNotNone(self._instance._handler)
        self.assertEqual(telnet_mock, self._instance._handler)
Ejemplo n.º 6
0
 def _console_telnet_session(self):
     console_port = int(self.resource_config.console_port)
     return [
         TelnetSession(
             self.resource_config.console_server_ip_address,
             self.username,
             self.password,
             console_port,
             self.on_session_start,
         ),
     ]
    def test_connect_actions(self):
        # Setup
        hostname = "localhost"
        on_session_start = Mock()
        self._instance = TelnetSession(
            hostname,
            self._username,
            "password",
            port=self._port,
            on_session_start=on_session_start,
        )
        self._instance._timeout = 0
        self._instance.hardware_expect = Mock(return_value="Done")
        self._instance._handler = Mock()

        # Act
        self._instance._connect_actions(">", logger=Mock())

        # Assert
        self._instance.hardware_expect.assert_called_once()
        on_session_start.assert_called_once()
Ejemplo n.º 8
0
    def _set_session_types(self):
        self._cs_session_handler()

        if self.connection_type == 'Auto':
            self.session_types = [
                SSHSession(host=self.address,
                           username=self.user,
                           password=self.cs_session.DecryptPassword(
                               self.password_hash).Value),
                TelnetSession(host=self.address,
                              username=self.user,
                              password=self.cs_session.DecryptPassword(
                                  self.password_hash).Value)
            ]
        elif self.connection_type == 'Console':
            message = 'Unimplemented CLI Connection Type: "%s"' % self.connection_type
            self.logger.error(message)
            raise Cli.UnImplementedCliConnectionType(message)
        elif self.connection_type == 'SSH':
            self.session_types = [
                SSHSession(host=self.address,
                           username=self.user,
                           password=self.cs_session.DecryptPassword(
                               self.password_hash).Value)
            ]
        elif self.connection_type == 'TCP':
            message = 'Unimplemented CLI Connection Type: "%s"' % self.connection_type
            self.logger.error(message)
            raise Cli.UnImplementedCliConnectionType(message)
        elif self.connection_type == 'Telnet':
            self.session_types = [
                TelnetSession(host=self.address,
                              username=self.user,
                              password=self.cs_session.DecryptPassword(
                                  self.password_hash).Value)
            ]
        else:
            message = 'Unsupported CLI Connection Type: "%s"' % self.connection_type
            self.logger.error(message)
            raise Cli.UnSupportedCliConnectionType(message)
Ejemplo n.º 9
0
    def _cli_session_handler(self, context):
        self._cs_session_handler(context)
        logger = LogHelper.get_logger(context)

        self.cli_connection_type = context.resource.attributes['CLI Connection Type']
        self.cli_prompt_regex = context.resource.attributes['CLI Prompt Regular Expression']
        self.mode = CommandMode(self.cli_prompt_regex)
        self.session_types = None

        logger.info('CLI Connection Type: "%s"' % self.cli_connection_type)
        logger.info('CLI Prompt Regular Expression: "%s"' % self.cli_prompt_regex)

        if self.cli_connection_type == 'Auto':
            self.session_types = [SSHSession(host=self.address,
                                             username=self.user,
                                             password=self.cs_session.DecryptPassword(self.password_hash).Value),
                                  TelnetSession(host=self.address,
                                                username=self.user,
                                                password=self.cs_session.DecryptPassword(self.password_hash).Value)]
        elif self.cli_connection_type == 'Console':
            message = 'Unimplemented CLI Connection Type: "%s"' % self.cli_connection_type
            logger.error(message)
            raise GenericResourceDriver.UnImplementedCliConnectionType(message)
        elif self.cli_connection_type == 'SSH':
            self.session_types = [SSHSession(host=self.address,
                                             username=self.user,
                                             password=self.cs_session.DecryptPassword(self.password_hash).Value)]
        elif self.cli_connection_type == 'TCP':
            message = 'Unimplemented CLI Connection Type: "%s"' % self.cli_connection_type
            logger.error(message)
            raise GenericResourceDriver.UnImplementedCliConnectionType(message)
        elif self.cli_connection_type == 'Telnet':
            self.session_types = [TelnetSession(host=self.address,
                                                username=self.user,
                                                password=self.cs_session.DecryptPassword(self.password_hash).Value)]
        else:
            message = 'Unsupported CLI Connection Type: "%s"' % self.cli_connection_type
            logger.error(message)
            raise GenericResourceDriver.UnSupportedCliConnectionType(message)
Ejemplo n.º 10
0
    def __init__(self, *args, **kwargs):
        """Initiate console connection, by default open ssh to 22 port and login to console server

        :param args:
        :param kwargs: 'console_server_ip', 'console_server_user', 'console_server_password', 'console_port' mandatory'
        :return:
        """

        ExpectSession.__init__(self, None, *args, **kwargs)

        self._console_username = kwargs['console_server_user']
        self._console_password = kwargs['console_server_password']
        self._console_host = kwargs['console_server_ip']

        self._session_handler = SSHSession(self._console_username, self._console_password, self._console_host,
                                           port=22, logger=self.logger)

        self._console_port = kwargs['console_port']
Ejemplo n.º 11
0
    def __init__(self, *args, **kwargs):
        """Initiate console connection, by default open ssh to 22 port and login to console server

        :param args:
        :param kwargs: 'console_server_ip', 'console_server_user', 'console_server_password', 'console_port' mandatory'
        :return:
        """

        ExpectSession.__init__(self, None, *args, **kwargs)

        self._console_username = kwargs['console_server_user']
        self._console_password = kwargs['console_server_password']
        self._console_host = kwargs['console_server_ip']

        self._session_handler = SSHSession(self._console_username,
                                           self._console_password,
                                           self._console_host,
                                           port=22,
                                           logger=self.logger)

        self._console_port = kwargs['console_port']
Ejemplo n.º 12
0
    def connect(self, re_string=''):
        """Open ssh or telnet connection to device

        :param re_string: expected string
        :return:
        """

        try:
            self._session_handler.connect(re_string)
            if self._console_port:
                self._connect_to_console(re_string)
        except Exception as error_object:
            if re.search('incompatible version', str(error_object).lower()) is None:
                self._session_handler = TelnetSession(self._console_username, self._console_password,
                                                      self._console_host, port=23, logger=self._logger)
                self._session_handler.connect(re_string)

                if self._console_port:
                    self._connect_to_console(re_string)
            else:
                raise error_object
Ejemplo n.º 13
0
class ConsoleSession(ExpectSession):
    def __init__(self, *args, **kwargs):
        """Initiate console connection, by default open ssh to 22 port and login to console server

        :param args:
        :param kwargs: 'console_server_ip', 'console_server_user', 'console_server_password', 'console_port' mandatory'
        :return:
        """

        ExpectSession.__init__(self, None, *args, **kwargs)

        self._console_username = kwargs['console_server_user']
        self._console_password = kwargs['console_server_password']
        self._console_host = kwargs['console_server_ip']

        self._session_handler = SSHSession(self._console_username,
                                           self._console_password,
                                           self._console_host,
                                           port=22,
                                           logger=self.logger)

        self._console_port = kwargs['console_port']

    def _clear_console(self, re_string=''):
        """Disconnect console if it's used by sending 'clear line xx' command

        :param re_string:
        :return:
        """

        expect_map = OrderedDict()
        expect_map['[Pp]assword:'] = lambda: self.send_line(
            self._password, self.logger)
        expect_map['\[confirm\]'] = lambda: self.send_line('', self.logger)

        self.hardware_expect('enable',
                             re_string=re_string,
                             expect_map=expect_map)

        output_str = self.hardware_expect('show hosts | i {0}'.format(
            self._console_port),
                                          re_string=re_string,
                                          expect_map=expect_map)

        pattern_str = '{0}\s+[\d][\d]([\d][\d])\s+\(.*\).*'.format(
            self._console_port)
        line_number = None
        for line_str in output_str.splitlines():
            result_match = re.search(pattern_str, line_str)
            if result_match:
                line_number = result_match.group(1)
                break

        if line_number:
            self.hardware_expect('clear line {0}'.format(line_number),
                                 re_string=re_string,
                                 expect_map=expect_map)

    def _connect_to_console(self, re_string=''):
        """Open console connection

        :param re_string:
        :return:
        """

        expect_map = OrderedDict()
        expect_map['[Ll]ogin:|[Uu]sername:'] = lambda: self.send_line(
            self._username, self.logger)
        expect_map['[Pp]assword:'] = lambda: self.send_line(
            self._password, self.logger)
        expect_map['[Cc]onnection refused'] = lambda: (self._clear_console(
            re_string), self.send_line(self.console_port, self.logger))

        self.hardware_expect(self._console_port, re_string=re_string)

    def connect(self, re_string=''):
        """Open ssh or telnet connection to device

        :param re_string: expected string
        :return:
        """

        try:
            self._session_handler.connect(re_string)
            if self._console_port:
                self._connect_to_console(re_string)
        except Exception as error_object:
            if re.search('incompatible version',
                         str(error_object).lower()) is None:
                self._session_handler = TelnetSession(self._console_username,
                                                      self._console_password,
                                                      self._console_host,
                                                      port=23,
                                                      logger=self.logger)
                self._session_handler.connect(re_string)

                if self._console_port:
                    self._connect_to_console(re_string)
            else:
                raise error_object

    def disconnect(self):
        """Disconnect from device

        :return:
        """

        self._session_handler.disconnect()

    def _send(self, command_string):
        """Send data to device

        :param command_string: command string
        :return:
        """

        self._session_handler._send(command_string)

    def _receive(self, timeout, logger):
        """Read data from device

        :param timeout: time for waiting buffer
        :return: str
        """

        self._session_handler._receive(timeout=timeout)
Ejemplo n.º 14
0
class ConsoleSession(ExpectSession):
    def __init__(self, *args, **kwargs):
        """Initiate console connection, by default open ssh to 22 port and login to console server

        :param args:
        :param kwargs: 'console_server_ip', 'console_server_user', 'console_server_password', 'console_port' mandatory'
        :return:
        """

        ExpectSession.__init__(self, None, *args, **kwargs)

        self._console_username = kwargs['console_server_user']
        self._console_password = kwargs['console_server_password']
        self._console_host = kwargs['console_server_ip']

        self._session_handler = SSHSession(self._console_username, self._console_password, self._console_host,
                                           port=22, logger=self.logger)

        self._console_port = kwargs['console_port']

    def _clear_console(self, re_string=''):
        """Disconnect console if it's used by sending 'clear line xx' command

        :param re_string:
        :return:
        """

        expect_map = OrderedDict()
        expect_map['[Pp]assword:'] = lambda: self.send_line(self._password)
        expect_map['\[confirm\]'] = lambda: self.send_line('')

        self.hardware_expect('enable', re_string=re_string, expect_map=expect_map)

        output_str = self.hardware_expect('show hosts | i {0}'.format(self._console_port), re_string=re_string,
                                          expect_map=expect_map)

        pattern_str = '{0}\s+[\d][\d]([\d][\d])\s+\(.*\).*'.format(self._console_port)
        line_number = None
        for line_str in output_str.splitlines():
            result_match = re.search(pattern_str, line_str)
            if result_match:
                line_number = result_match.group(1)
                break

        if line_number:
            self.hardware_expect('clear line {0}'.format(line_number), re_string=re_string, expect_map=expect_map)

    def _connect_to_console(self, re_string=''):
        """Open console connection

        :param re_string:
        :return:
        """

        expect_map = OrderedDict()
        expect_map['[Ll]ogin:|[Uu]sername:'] = lambda: self.send_line(self._username)
        expect_map['[Pp]assword:'] = lambda: self.send_line(self._password)
        expect_map['[Cc]onnection refused'] = lambda: (self._clear_console(re_string),
                                                       self.send_line(self.console_port))

        self.hardware_expect(self._console_port, re_string=re_string)

    def connect(self, re_string=''):
        """Open ssh or telnet connection to device

        :param re_string: expected string
        :return:
        """

        try:
            self._session_handler.connect(re_string)
            if self._console_port:
                self._connect_to_console(re_string)
        except Exception as error_object:
            if re.search('incompatible version', str(error_object).lower()) is None:
                self._session_handler = TelnetSession(self._console_username, self._console_password,
                                                      self._console_host, port=23, logger=self._logger)
                self._session_handler.connect(re_string)

                if self._console_port:
                    self._connect_to_console(re_string)
            else:
                raise error_object

    def disconnect(self):
        """Disconnect from device

        :return:
        """

        self._session_handler.disconnect()

    def _send(self, command_string):
        """Send data to device

        :param command_string: command string
        :return:
        """

        self._session_handler._send(command_string)

    def _receive(self, timeout=None):
        """Read data from device

        :param timeout: time for waiting buffer
        :return: str
        """

        self._session_handler._receive(timeout=timeout)
 def _telnet_session(self):
     return TelnetSession(self.resource_address, self.username, self.password, self.port, self.on_session_start)
class TestTelnetSession(TestCase):
    def setUp(self):
        self._username = "******"
        self._password = "******"
        self._hostname = "hostname"
        self._port = 22
        self._on_session_start = Mock()

    @patch("cloudshell.cli.session.telnet_session.ExpectSession")
    @patch("cloudshell.cli.session.telnet_session.ConnectionParams")
    def test_init_attributes(self, connection_params, expect_session):
        self._instance = TelnetSession(
            self._hostname,
            self._username,
            self._password,
            port=self._port,
            on_session_start=self._on_session_start,
        )
        mandatory_attributes = ["username", "_handler", "password"]
        self.assertEqual(
            len(
                set(mandatory_attributes).difference(
                    set(self._instance.__dict__.keys()))),
            0,
        )

    @patch("cloudshell.cli.session.ssh_session.ExpectSession")
    def test_eq(self, expect_session):
        self._instance = TelnetSession(
            self._hostname,
            self._username,
            self._password,
            port=self._port,
            on_session_start=self._on_session_start,
        )
        self.assertTrue(
            self._instance.__eq__(
                TelnetSession(
                    self._hostname,
                    self._username,
                    self._password,
                    port=self._port,
                    on_session_start=self._on_session_start,
                )))
        self.assertFalse(
            self._instance.__eq__(
                TelnetSession(
                    self._hostname,
                    "incorrect_username",
                    self._password,
                    port=self._port,
                    on_session_start=self._on_session_start,
                )))
        self.assertFalse(
            self._instance.__eq__(
                TelnetSession(
                    self._hostname,
                    self._username,
                    "incorrect_password",
                    port=self._port,
                    on_session_start=self._on_session_start,
                )))

    @patch("cloudshell.cli.session.telnet_session.telnetlib")
    def test_intialize_session(self, telnet_lib):
        # Setup
        telnet_mock = Mock()
        telnet_lib.Telnet.return_value = telnet_mock
        hostname = "localhost"
        self._instance = TelnetSession(
            hostname,
            self._username,
            "incorrect_password",
            port=self._port,
            on_session_start=self._on_session_start,
        )

        # Act
        self._instance._initialize_session(">", logger=Mock())

        # Assert
        self.assertIsNotNone(self._instance._handler)
        self.assertEqual(telnet_mock, self._instance._handler)

    def test_connect_actions(self):
        # Setup
        hostname = "localhost"
        on_session_start = Mock()
        self._instance = TelnetSession(
            hostname,
            self._username,
            "password",
            port=self._port,
            on_session_start=on_session_start,
        )
        self._instance._timeout = 0
        self._instance.hardware_expect = Mock(return_value="Done")
        self._instance._handler = Mock()

        # Act
        self._instance._connect_actions(">", logger=Mock())

        # Assert
        self._instance.hardware_expect.assert_called_once()
        on_session_start.assert_called_once()