コード例 #1
0
 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)
コード例 #2
0
 def __init__(self,
              resource_config,
              pool_timeout=DEFAULT_SESSION_POOL_TIMEOUT):
     session_pool_size = int(resource_config.sessions_concurrency_limit)
     session_pool = SessionPoolManager(max_pool_size=session_pool_size,
                                       pool_timeout=pool_timeout)
     self.cli = CLI(session_pool=session_pool)
コード例 #3
0
    def DeleteInstance(self, context, ports):
        """
        Called during sandbox's teardown or when removing a deployed App from the sandbox

        Method deletes the VM from the cloud provider.

        If the operation fails, method should raise an exception.

        :param ResourceRemoteCommandContext context:
        :param ports:
        """
        with LoggingSessionContext(context) as logger:
            api = CloudShellSessionContext(context).get_api()
            resource_config = JuniperCPResourceConfig.from_context(
                self.SHELL_NAME, context, api, self.SUPPORTED_OS)
            cli_configurator = JuniperCliConfigurator(CLI(self._session_pool),
                                                      resource_config, logger)

            ls_flow = CreateRemoveLSFlow(cli_configurator, logger)

            for endpoint in context.remote_endpoints:
                res_details = api.GetResourceDetails(endpoint.name)
                ls_name = self._extract_attribute(
                    res_details.VmDetails.InstanceData, self.ATTRIBUTE.LS_NAME)
                ls_flow.remove_ls(ls_name)
コード例 #4
0
 def set_up(self):
     ConfigCommandMode.ENTER_CONFIG_RETRY_TIMEOUT = 0.5
     api = MagicMock(DecryptPassword=lambda password: MagicMock(Value=password))
     cli_conf = GenericCLIConfig("Cisco Shell", api=api)
     cli_conf.cli_tcp_port = "22"
     cli_conf.cli_connection_type = "SSH"
     return CiscoCliHandler(CLI(), cli_conf, Mock())
    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)
コード例 #6
0
    def initialize(self, context):
        """Initialize the driver session.

        :param context: the context the command runs on
        :rtype: str
        """
        resource_config = FirewallResourceConfig.from_context(self.SHELL_NAME, context)
        session_pool_size = int(resource_config.sessions_concurrency_limit)
        self._cli = CLI(
            SessionPoolManager(max_pool_size=session_pool_size, pool_timeout=100)
        )
        return "Finished initializing"
コード例 #7
0
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
コード例 #8
0
    def __init__(self,
                 resource_config,
                 logger,
                 cli=None,
                 registered_sessions=None):
        """Initialize CLI service configurator.

        :param cloudshell.shell.standards.resource_config_generic_models.GenericCLIConfig resource_config:  # noqa: E501
        :param logging.Logger logger:
        :param cloudshell.cli.service.cli.CLI cli:
        :param registered_sessions: Session types and order
        """
        self._cli = cli or CLI()
        self._resource_config = resource_config
        self._logger = logger
        self._registered_sessions = registered_sessions or self.REGISTERED_SESSIONS
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
コード例 #10
0
    def _setUp(self, attrs=None):
        if attrs is None:
            attrs = {}
        self.logger = MagicMock()
        self.api = MagicMock(DecryptPassword=lambda password: MagicMock(Value=password))

        self.resource_config = NetworkingResourceConfig.from_context(
            self.SHELL_NAME,
            self.create_context(attrs),
            self.api,
            self.SUPPORTED_OS,
        )
        self._cli = CLI(
            SessionPoolManager(
                max_pool_size=int(self.resource_config.sessions_concurrency_limit)
            )
        )

        self.cli_configurator = AristaCLIConfigurator(
            self.resource_config, self.api, self.logger, self._cli
        )
コード例 #11
0
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
    def setUp(self):
        AristaConfigCommandMode.ENTER_CONFIG_RETRY_TIMEOUT = 0.5

        self.api = MagicMock()
        self.api.DecryptPassword().Value.return_value = "password"
        self._cli = CLI()
コード例 #13
0
    def Deploy(self, context, request, cancellation_context=None):
        """
        Called when reserving a sandbox during setup, a call for each app in the sandbox.

        Method creates the compute resource in the cloud provider - VM instance or container.

        If App deployment fails, return a "success false" action result.

        :param ResourceCommandContext context:
        :param str request: A JSON string with the list of requested deployment actions
        :param CancellationContext cancellation_context:
        :return:
        :rtype: str
        """
        '''
        # parse the json strings into action objects
        actions = self.request_parser.convert_driver_request_to_actions(request)
        
        # extract DeployApp action
        deploy_action = single(actions, lambda x: isinstance(x, DeployApp))
        
        # if we have multiple supported deployment options use the 'deploymentPath' property 
        # to decide which deployment option to use. 
        deployment_name = deploy_action.actionParams.deployment.deploymentPath
                
        deploy_result = _my_deploy_method(context, actions, cancellation_context)
        return DriverResponse(deploy_result).to_driver_response_json()
        '''
        with LoggingSessionContext(context) as logger:
            logger.info(request)
            api = CloudShellSessionContext(context).get_api()
            resource_config = JuniperCPResourceConfig.from_context(
                self.SHELL_NAME, context, api, self.SUPPORTED_OS)
            cli_configurator = JuniperCliConfigurator(CLI(self._session_pool),
                                                      resource_config, logger)

            ls_flow = CreateRemoveLSFlow(cli_configurator, logger)

            actions = DriverRequestParser().convert_driver_request_to_actions(
                request)
            reservation_details = api.GetReservationDetails(
                context.reservation.reservation_id,
                disableCache=True).ReservationDescription

            results = []
            for deploy_action in actions:
                app_name = deploy_action.actionParams.appName
                int_list = self._get_int_names(reservation_details, app_name)
                logger.info("{}:{}".format(app_name, str(int_list)))
                if not int_list:
                    raise Exception(
                        "Failed to deploy Logical System without interfaces. "
                        "Please create appropriate connections")
                vm_uuid = self._build_uuid(app_name,
                                           context.reservation.reservation_id)
                ls_name = "VR-{}".format(vm_uuid)
                vm_name = "{}-{}".format(app_name, ls_name)
                int_list = ls_flow.create_ls(ls_name, int_list)
                vm_instance_data = [
                    VmDetailsProperty(self.ATTRIBUTE.INST_UUID, vm_uuid),
                    VmDetailsProperty(self.ATTRIBUTE.LS_NAME, ls_name),
                ]
                vm_interfaces_data = [
                    VmDetailsProperty("vNIC {} Name".format(i), int_list[i])
                    for i in range(len(int_list))
                ]
                vm_instance_data.extend(vm_interfaces_data)

                deploy_result = DeployAppResult(
                    actionId=deploy_action.actionId,
                    infoMessage="Deployment Completed Successfully",
                    vmUuid=vm_uuid,
                    vmName=vm_name,
                    deployedAppAddress="",
                    deployedAppAttributes=[],
                    vmDetailsData=VmDetailsData(vm_instance_data))

                results.append(deploy_result)
            return DriverResponse(results).to_driver_response_json()
コード例 #14
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)
コード例 #15
0
 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 set_up(self):
     ConfigCommandMode.ENTER_CONFIG_RETRY_TIMEOUT = 0.5
     cli_conf = MagicMock()
     cli_conf.cli_tcp_port = "22"
     cli_conf.cli_connection_type = "SSH"
     return CiscoCliHandler(CLI(), cli_conf, Mock())