def send_any_cmd(self, context, sendcmd): """ :param InitCommandContext context : passed in by cloudshell :param str sendcmd: the command to send to the CLI """ cli = CLI() mode = CommandMode(r'#') # for example r'%\s*$' session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) address = context.resource.address user = context.resource.attributes['LinuxServerShell.User'] password = session.DecryptPassword( context.resource.attributes['LinuxServerShell.Password']).Value session_types = [ SSHSession(host=address, username=user, password=password) ] with cli.get_session(session_types, mode) as default_session: out = default_session.send_command(sendcmd) print(out) return out
def __init__(self, host, username, password): self.cli = CLI() self.mode = CommandMode(r'#') # for example r'%\s*$' self.session_types = [ SSHSession(host=host, username=username, password=password) ] self.session = self.cli.get_session(command_mode=self.mode, new_sessions=self.session_types)
def __init__(self, host, username, password): self.cli = CLI() self.mode = CommandMode(r'#')# for example r'%\s*$' self.clish_mode = CommandMode(r'>', enter_command='clish', exit_command='exit')# for example r'%\s*$' self.mode.add_child_node(self.clish_mode) self.session_types = [SSHSession(host=host, username=username, password=password)] self.session = self.cli.get_session(command_mode=self.mode, new_sessions=self.session_types)
def create_my_session(self): cli = CLI() mode = CommandMode(r'%\s*$#') # for example r'%\s*$' ip_address = '192.16.42.235' user_name = 'root' password = '******' session_types = [SSHSession(host=ip_address, username=user_name, password=password)] with cli.get_session(session_types, mode) as default_session: out = default_session.send_command('my command') print(out)
def __init__(self, host, username, password, logger=None): self.cli = CLI() self.logger = logger # the mode is the termination string - code will expect a"$" sign in this case to mark an end of input. self.mode = CommandMode(r'$') # 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.elevated_mode, new_sessions=self.session_types) self.session = self.cli.get_session(command_mode=self.mode, new_sessions=self.session_types)
def __init__(self, logger): self._logger = logger self._cli = CLI(session_pool=SessionPoolManager(max_pool_size=1)) self._defined_session_types = { "SSH": RomeSSHSession, "TELNET": RomeTelnetSession, } self._session_types = (RuntimeConfiguration().read_key("CLI.TYPE") or self._defined_session_types.keys()) self._ports = RuntimeConfiguration().read_key("CLI.PORTS") self._host = None self._username = None self._password = None
def __init__(self, logger): self._logger = logger self._cli = CLI(session_pool=SessionPoolManager(max_pool_size=1)) self._defined_session_types = { 'SSH': SSHSession, 'TELNET': FiberzoneTelnetSession } self._session_types = RuntimeConfiguration().read_key( 'CLI.TYPE') or self._defined_session_types.keys() self._ports = RuntimeConfiguration().read_key('CLI.PORTS') self._host = None self._username = None self._password = None
def set_up(self): ConfigCommandMode.ENTER_CONFIG_RETRY_TIMEOUT = 0.5 resource_config = MagicMock() resource_config.cli_connection_type = "SSH" api = MagicMock() api.DecryptPassword().Value.return_value = "password" return CiscoCliHandler(cli=CLI(), resource_config=resource_config, logger=MagicMock(), api=api)
class CreateSession(): def __init__(self, host, username, password): self.cli = CLI() self.mode = CommandMode(r'#') # for example r'%\s*$' self.session_types = [ SSHSession(host=host, username=username, password=password) ] self.session = self.cli.get_session(command_mode=self.mode, new_sessions=self.session_types) def send_terminal_command(self, command): with self.session as my_session: out = my_session.send_command(command) return out def config_license(self): outp = [] outp.append(self.send_terminal_command('\r\n')) outp.append( self.send_terminal_command('config log syslogd setting\r\n')) outp.append(self.send_terminal_command('set status enable\r\n')) outp.append( self.send_terminal_command('set server {}\r\n'.format( self.splunk_address))) outp.append(self.send_terminal_command('end\r\n')) return outp
def __init__(self, logger): self._logger = logger self._cli = CLI(session_pool=SessionPoolManager(max_pool_size=1)) self.modes = CommandModeHelper.create_command_mode() self._defined_session_types = { 'SSH': VWSSHSession, 'TELNET': TelnetSession } self._session_types = RuntimeConfiguration().read_key( 'CLI.TYPE', ['SSH']) or self._defined_session_types.keys() self._ports = RuntimeConfiguration().read_key('CLI.PORTS', '22') self._host = None self._username = None self._password = None
def _get_device_session(self, context): """ :param context: :return: """ session = get_api(context) config = Linuxshell( name=context.resource.name).create_from_context(context) host = context.resource.address username = config.user password = session.DecryptPassword(config.password).Value cli = CLI() mode = CommandMode(prompt=r'.*\$') session_types = [ SSHSession(host=host, username=username, password=password) ] device_session = cli.get_session(session_types, mode) return device_session
class TestCli(TestCase): def setUp(self): self._cli = CLI(mock.MagicMock()) @mock.patch('cloudshell.cli.cli.SessionPoolContextManager') def test_create_instance(self, context_manager): with self._cli.get_session(mock.Mock(), mock.Mock(), mock.Mock()) as session: pass context_manager.assert_called_once()
def __init__(self, host, username, password, logger=None): self.cli = CLI() self.logger = logger self.mode = CommandMode(r'$') # 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.elevated_mode, new_sessions=self.session_types)
def __init__(self, logger, runtime_config): """ :param logger: :param cloudshell.layer_one.core.helper.runtime_configuration.RuntimeConfiguration runtime_config: """ self._logger = logger self._runtime_config = runtime_config self._cli = CLI(session_pool=SessionPoolManager(max_pool_size=1)) self.modes = CommandModeHelper.create_command_mode() self._defined_session_types = { VWSSHSession.SESSION_TYPE: VWSSHSession, TelnetSession.SESSION_TYPE: TelnetSession } self._session_types = self._runtime_config.read_key( 'CLI.TYPE', [VWSSHSession.SESSION_TYPE]) or self._defined_session_types.keys() self._ports = RuntimeConfiguration().read_key('CLI.PORTS', {}) self._host = None self._username = None self._password = None
class L1CliHandler(object): def __init__(self, logger): self._logger = logger self._cli = CLI(session_pool=SessionPoolManager(max_pool_size=1)) self._defined_session_types = { "SSH": RomeSSHSession, "TELNET": RomeTelnetSession, } self._session_types = (RuntimeConfiguration().read_key("CLI.TYPE") or self._defined_session_types.keys()) self._ports = RuntimeConfiguration().read_key("CLI.PORTS") self._host = None self._username = None self._password = None def _new_sessions(self): sessions = [] for session_type in self._session_types: session_class = self._defined_session_types.get(session_type) if not session_class: raise LayerOneDriverException( self.__class__.__name__, "Session type {} is not defined".format(session_type), ) port = self._ports.get(session_type) sessions.append( session_class(self._host, self._username, self._password, port)) return sessions def define_session_attributes(self, address, username, password): """Define session attributes.""" address_list = address.split(":") if len(address_list) > 1: raise LayerOneDriverException(self.__class__.__name__, "Incorrect resource address") self._host = address self._username = username self._password = password def get_cli_service(self, command_mode): """Create new cli service or get it from pool.""" if not self._host or not self._username or not self._password: raise LayerOneDriverException( self.__class__.__name__, "Cli Attributes is not defined, call Login command first", ) return self._cli.get_session(self._new_sessions(), command_mode, self._logger)
class CreateSession(): def __init__(self, host, username, password, logger=None): self.cli = CLI() self.logger = logger self.mode = CommandMode(r'$') # 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.elevated_mode, new_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(): def __init__(self, host, username, password, logger=None): self.cli = CLI() self.logger = logger # the mode is the termination string - code will expect a"$" sign in this case to mark an end of input. self.mode = CommandMode(r'$') # 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.elevated_mode, new_sessions=self.session_types) self.session = self.cli.get_session(command_mode=self.mode, new_sessions=self.session_types) def send_terminal_command(self, command): outp = [] out = None with self.session as my_session: if isinstance(command, list): for single_command in command: single_command = '{command}'.format(command=single_command) # 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: command = '{command}'.format(command=command) out = my_session.send_command(command) return out def send_admin_termianl_command(self): pass
def initialize(self, context): self.cli = CLI()
def get_cli(session_pool_size, pool_timeout=100): session_pool = SessionPoolManager(max_pool_size=session_pool_size, pool_timeout=pool_timeout) return CLI(session_pool=session_pool)
class L1CliHandler(object): def __init__(self, logger): self._logger = logger self._cli = CLI(session_pool=SessionPoolManager(max_pool_size=1)) self._defined_session_types = { 'SSH': SSHSession, 'TELNET': FiberzoneTelnetSession } self._session_types = RuntimeConfiguration().read_key( 'CLI.TYPE') or self._defined_session_types.keys() self._ports = RuntimeConfiguration().read_key('CLI.PORTS') self._host = None self._username = None self._password = None def _new_sessions(self): sessions = [] for session_type in self._session_types: session_class = self._defined_session_types.get(session_type) if not session_class: raise LayerOneDriverException( self.__class__.__name__, 'Session type {} is not defined'.format(session_type)) port = self._ports.get(session_type) sessions.append( session_class(self._host, self._username, self._password, port)) return sessions def define_session_attributes(self, address, username, password): """ Define session attributes :param address: :type address: str :param username: :param password: :return: """ address_list = address.split(':') if len(address_list) > 1: raise LayerOneDriverException(self.__class__.__name__, 'Incorrect resource address') self._host = address self._username = username self._password = password def get_cli_service(self, command_mode): """ Create new cli service or get it from pool :param command_mode: :return: """ if not self._host or not self._username or not self._password: raise LayerOneDriverException( self.__class__.__name__, "Cli Attributes is not defined, call Login command first") return self._cli.get_session(self._new_sessions(), command_mode, self._logger)
context = ResourceCommandContext() context.resource = ResourceContextDetails() context.resource.name = "Switch for Demo" context.resource.address = "<IP>" context.resource.attributes = {} context.resource.attributes["CLI Connection Type"] = "SSH" context.resource.attributes["User"] = "******" context.resource.attributes["AdminUser"] = "******" context.resource.attributes["Console Password"] = "******" context.resource.attributes["Password"] = "******" context.resource.attributes["Enable Password"] = "******" context.resource.attributes["Sessions Concurrency Limit"] = 2 return context if __name__ == "__main__": context = create_context() pool = SessionPoolManager(max_pool_size=1) cli = CLI(session_pool=pool) cli_handler = SwitchCliHandler(cli, context, logger) with cli_handler.get_cli_service(cli_handler.enable_mode) as session: out = session.send_command("echo checking switch") with session.enter_mode(cli_handler.config_mode) as config_session: out = config_session.send_command("echo checking switch") print(out) # noqa: T001 out = config_session.send_command("echo checking switch") print(out) # noqa: T001
def __init__(self, context): CommandMode.__init__( self, CliCommandMode.PROMPT, CliCommandMode.ENTER_COMMAND, CliCommandMode.EXIT_COMMAND, ) LOGGER = get_qs_logger() CommandMode.RELATIONS_DICT = {CliCommandMode: {}} if __name__ == "__main__": pool = SessionPoolManager(max_pool_size=1) cli = CLI(session_pool=pool) context = type( "context", (object, ), {"resource": type("resource", (object, ), {"name": "test name"})}, ) host = "<IP>" username = "******" password = "******" session = SSHSession(host, username, password) modes = CommandModeHelper.create_command_mode(context) default_mode = modes[CliCommandMode]
def get_cli_handler(self, connection_type='SSH'): resource_config = MagicMock() resource_config.cli_connection_type = connection_type return AristaCliHandler(CLI(), resource_config, MagicMock(), self.api)
def get_session(self): return CLI().get_session(self.session_types, self.mode, self.logger)
class GenericResourceDriver(ResourceDriverInterface): class UnImplementedCliConnectionType(Exception): pass class UnSupportedCliConnectionType(Exception): pass def cleanup(self): """ Destroy the driver session, this function is called everytime a driver instance is destroyed This is a good place to close any open sessions, finish writing to log files """ pass def __init__(self): self.address = None self.cli = None self.cli_connection_type = None self.cli_prompt_regex = None self.cli_session = None self.cs_session = None self.mode = None self.password_hash = None self.session_types = None self.user = None def initialize(self, context): self.cli = CLI() def get_inventory(self, context): self.run_command(context, 'hostname') return AutoLoadDetails() def run_command(self, context, command): logger = LogHelper.get_logger(context) self._cli_session_handler(context) with self.cli.get_session(self.session_types, self.mode, logger) as default_session: output = default_session.send_command(command) return sub(self.cli_prompt_regex, '', output) def _cs_session_handler(self, context): self.address = context.resource.address self.user = context.resource.attributes['User'] self.password_hash = context.resource.attributes['Password'] domain = None try: domain = context.reservation.domain except AttributeError: domain = 'Global' self.cs_session = CloudShellAPISession(host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=domain) 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)
def setUp(self): self._cli = CLI(mock.MagicMock())
class VWCliHandler(object): def __init__(self, logger, runtime_config): """ :param logger: :param cloudshell.layer_one.core.helper.runtime_configuration.RuntimeConfiguration runtime_config: """ self._logger = logger self._runtime_config = runtime_config self._cli = CLI(session_pool=SessionPoolManager(max_pool_size=1)) self.modes = CommandModeHelper.create_command_mode() self._defined_session_types = { VWSSHSession.SESSION_TYPE: VWSSHSession, TelnetSession.SESSION_TYPE: TelnetSession } self._session_types = self._runtime_config.read_key( 'CLI.TYPE', [VWSSHSession.SESSION_TYPE]) or self._defined_session_types.keys() self._ports = RuntimeConfiguration().read_key('CLI.PORTS', {}) self._host = None self._username = None self._password = None def _new_sessions(self): sessions = [] for session_type in self._session_types: session_class = self._defined_session_types.get(session_type) if not session_class: raise LayerOneDriverException( self.__class__.__name__, 'Session type {} is not defined'.format(session_type)) port = self._ports.get(session_type) sessions.append( session_class(self._host, self._username, self._password, port)) return sessions def define_session_attributes(self, address, username, password): """ Define session attributes :param address: :type address: str :param username: :param password: :return: """ address_list = address.split(':') if len(address_list) > 1: raise LayerOneDriverException(self.__class__.__name__, 'Incorrect resource address') self._host = address self._username = username self._password = password self._default_mode.set_credentials(username, password) def get_cli_service(self, command_mode): """ Create new cli service or get it from pool :param command_mode: :return: """ if not self._host or not self._username or not self._password: raise LayerOneDriverException( self.__class__.__name__, "Cli Attributes is not defined, call Login command first") return self._cli.get_session(self._new_sessions(), command_mode, self._logger) @property def _default_mode(self): """ :rtype: DefaultCommandMode """ return self.modes[DefaultCommandMode] def default_mode_service(self): """ Default mode session :return: :rtype: cloudshell.cli.cli_service.CliService """ return self.get_cli_service(self._default_mode)