Exemple #1
0
    def replace(self,
                patterns,
                repl,
                parents=None,
                add_if_missing=False,
                ignore_whitespace=True):

        match = None

        parents = to_list(parents) or list()
        patterns = [re.compile(r, re.I) for r in to_list(patterns)]

        for item in self.items:
            for regexp in patterns:
                text = item.text
                if not ignore_whitespace:
                    text = item.raw
                if regexp.search(text):
                    if item.text != repl:
                        if parents == [p.text for p in item.parents]:
                            match = item
                            break

        if match:
            match.text = repl
            indent = len(match.raw) - len(match.raw.lstrip())
            match.raw = repl.rjust(len(repl) + indent)

        elif add_if_missing:
            self.add(repl, parents=parents)
    def replace(self, patterns, repl, parents=None, add_if_missing=False,
                ignore_whitespace=True):

        match = None

        parents = to_list(parents) or list()
        patterns = [re.compile(r, re.I) for r in to_list(patterns)]

        for item in self.items:
            for regexp in patterns:
                text = item.text
                if not ignore_whitespace:
                    text = item.raw
                if regexp.search(text):
                    if item.text != repl:
                        if parents == [p.text for p in item.parents]:
                            match = item
                            break

        if match:
            match.text = repl
            indent = len(match.raw) - len(match.raw.lstrip())
            match.raw = repl.rjust(len(repl) + indent)

        elif add_if_missing:
            self.add(repl, parents=parents)
Exemple #3
0
 def load_config(self, commands, session_name='ansible_temp_session', **kwargs):
     commands = to_list(commands)
     commands.insert(0, 'configure session %s' % session_name)
     commands.append('show session-config diffs')
     commands.append('end')
     responses = self.execute(commands)
     return responses[-2]
Exemple #4
0
 def configure(self, commands):
     cmds = ['configure terminal']
     cmds.extend(to_list(commands))
     if cmds[-1] != 'end':
         cmds.append('end')
     responses = self.execute(cmds)
     return responses[1:]
Exemple #5
0
    def replace(self, replace, text=None, regex=None, parents=None,
            add_if_missing=False, ignore_whitespace=False):
        match = None

        parents = parents or list()
        if text is None and regex is None:
            raise ValueError('missing required arguments')

        if not regex:
            regex = ['^%s$' % text]

        patterns = [re.compile(r, re.I) for r in to_list(regex)]

        for item in self.items:
            for regexp in patterns:
                string = ignore_whitespace is True and item.text or item.raw
                if regexp.search(item.text):
                    if item.text != replace:
                        if parents == [p.text for p in item.parents]:
                            match = item
                            break

        if match:
            match.text = replace
            indent = len(match.raw) - len(match.raw.lstrip())
            match.raw = replace.rjust(len(replace) + indent)

        elif add_if_missing:
            self.add(replace, parents=parents)
Exemple #6
0
    def replace(self,
                replace,
                text=None,
                regex=None,
                parents=None,
                add_if_missing=False,
                ignore_whitespace=False):
        match = None

        parents = parents or list()
        if text is None and regex is None:
            raise ValueError('missing required arguments')

        if not regex:
            regex = ['^%s$' % text]

        patterns = [re.compile(r, re.I) for r in to_list(regex)]

        for item in self.items:
            for regexp in patterns:
                string = ignore_whitespace is True and item.text or item.raw
                if regexp.search(item.text):
                    if item.text != replace:
                        if parents == [p.text for p in item.parents]:
                            match = item
                            break

        if match:
            match.text = replace
            indent = len(match.raw) - len(match.raw.lstrip())
            match.raw = replace.rjust(len(replace) + indent)

        elif add_if_missing:
            self.add(replace, parents=parents)
Exemple #7
0
 def configure(self, commands, **kwargs):
     cmds = ['configure terminal']
     cmds.extend(to_list(commands))
     if cmds[-1] != 'end':
         cmds.append('end')
     responses = self.execute(cmds)
     return responses[1:]
Exemple #8
0
 def run_commands(self, commands):
     responses = list()
     for cmd in to_list(commands):
         if str(cmd).startswith('show '):
             cmd = str(cmd)[4:]
         responses.append(self.execute(str(cmd)))
     return responses
Exemple #9
0
 def run_commands(self, commands):
     responses = list()
     for cmd in to_list(commands):
         if str(cmd).startswith('show '):
             cmd = str(cmd)[4:]
         responses.append(self.execute(str(cmd)))
     return responses
Exemple #10
0
 def load_config(self, commands, session_name='ansible_temp_session', **kwargs):
     commands = to_list(commands)
     commands.insert(0, 'configure session %s' % session_name)
     commands.append('show session-config diffs')
     commands.append('end')
     responses = self.execute(commands)
     return responses[-2]
Exemple #11
0
def prepare_config(commands):
    """ prepare_config """

    prepared = list()
    prepared.extend(to_list(commands))
    prepared.append('return')
    return prepared
Exemple #12
0
 def configure(self, commands, **kwargs):
     cmds = ['configure terminal']
     cmds.extend(to_list(commands))
     cmds.append('end')
     responses = self.execute(cmds)
     responses.pop(0)
     return responses
Exemple #13
0
    def configure(self, commands, **kwargs):
        cmds = ['configure']
        cmds.extend(to_list(commands))
        cmds.append('end')

        responses = self.execute(cmds)
        return responses[1:-1]
Exemple #14
0
    def add(self, lines, parents=None):
        """Adds one or lines of configuration
        """

        ancestors = list()
        offset = 0
        obj = None

        ## global config command
        if not parents:
            for line in to_list(lines):
                item = ConfigLine(line)
                item.raw = line
                if item not in self.items:
                    self.items.append(item)

        else:
            for index, p in enumerate(parents):
                try:
                    i = index + 1
                    obj = self.get_section_objects(parents[:i])[0]
                    ancestors.append(obj)

                except ValueError:
                    # add parent to config
                    offset = index * self.indent
                    obj = ConfigLine(p)
                    obj.raw = p.rjust(len(p) + offset)
                    if ancestors:
                        obj.parents = list(ancestors)
                        ancestors[-1].children.append(obj)
                    self.items.append(obj)
                    ancestors.append(obj)

            # add child objects
            for line in to_list(lines):
                # check if child already exists
                for child in ancestors[-1].children:
                    if child.text == line:
                        break
                else:
                    offset = len(parents) * self.indent
                    item = ConfigLine(line)
                    item.raw = line.rjust(len(line) + offset)
                    item.parents = ancestors
                    ancestors[-1].children.append(item)
                    self.items.append(item)
Exemple #15
0
    def add(self, lines, parents=None):
        """Adds one or lines of configuration
        """

        ancestors = list()
        offset = 0
        obj = None

        ## global config command
        if not parents:
            for line in to_list(lines):
                item = ConfigLine(line)
                item.raw = line
                if item not in self.items:
                    self.items.append(item)

        else:
            for index, p in enumerate(parents):
                try:
                    i = index + 1
                    obj = self.get_section_objects(parents[:i])[0]
                    ancestors.append(obj)

                except ValueError:
                    # add parent to config
                    offset = index * self.indent
                    obj = ConfigLine(p)
                    obj.raw = p.rjust(len(p) + offset)
                    if ancestors:
                        obj.parents = list(ancestors)
                        ancestors[-1].children.append(obj)
                    self.items.append(obj)
                    ancestors.append(obj)

            # add child objects
            for line in to_list(lines):
                # check if child already exists
                for child in ancestors[-1].children:
                    if child.text == line:
                        break
                else:
                    offset = len(parents) * self.indent
                    item = ConfigLine(line)
                    item.raw = line.rjust(len(line) + offset)
                    item.parents = ancestors
                    ancestors[-1].children.append(item)
                    self.items.append(item)
Exemple #16
0
 def configure(self, commands):
     cmds = ['configure terminal']
     if commands[-1] == 'end':
         commands.pop()
     cmds.extend(to_list(commands))
     cmds.extend(['commit', 'end'])
     responses = self.execute(cmds)
     return responses[1:]
def prepare_commands(commands):
    jsonify = lambda x: '%s | json' % x
    for cmd in to_list(commands):
        if cmd.output == 'json':
            cmd = jsonify(cmd)
        else:
            cmd = str(cmd)
        yield cmd
Exemple #18
0
def prepare_commands(commands):
    jsonify = lambda x: '%s | json' % x
    for cmd in to_list(commands):
        if cmd.output == 'json':
            cmd.command_string = jsonify(cmd)
        if cmd.command.endswith('| json'):
            cmd.output = 'json'
        yield cmd
Exemple #19
0
def prepare_commands(commands):
    jsonify = lambda x: '%s | json' % x
    for cmd in to_list(commands):
        if cmd.output == 'json':
            cmd.command_string = jsonify(cmd)
        if cmd.command.endswith('| json'):
            cmd.output = 'json'
        yield cmd
Exemple #20
0
 def configure(self, commands):
     cmds = ['configure terminal']
     if commands[-1] == 'end':
         commands.pop()
     cmds.extend(to_list(commands))
     cmds.extend(['commit', 'end'])
     responses = self.execute(cmds)
     return responses[1:]
Exemple #21
0
def prepare_commands(commands):
    jsonify = lambda x: '%s | json' % x
    for cmd in to_list(commands):
        if cmd.output == 'json':
            cmd = jsonify(cmd)
        else:
            cmd = str(cmd)
        yield cmd
Exemple #22
0
 def configure(self, commands, commit=True, **kwargs):
     """Called by Config.__call__
     """
     cmds = ['configure']
     cmds.extend(to_list(commands))
     response = self.execute(cmds)
     if commit:
         self.commit_config()
     return response
Exemple #23
0
 def configure(self, commands, commit=True, **kwargs):
     """Called by Config.__call__
     """
     cmds = ['configure']
     cmds.extend(to_list(commands))
     response = self.execute(cmds)
     if commit:
         self.commit_config()
     return response
Exemple #24
0
    def configure(self, commands, **kwargs):
        cmds = ['configure terminal']
        cmds.extend(to_list(commands))
        cmds.append('end')
        cmds.append('commit')

        responses = self.execute(cmds)
        responses.pop(0)
        return responses
Exemple #25
0
    def execute(self, commands, output=None, **kwargs):
        commands = collections.deque(commands)
        output = output or self.default_output

        # only 10 commands can be encoded in each request
        # messages sent to the remote device
        stack = list()
        requests = list()

        while commands:
            stack.append(commands.popleft())
            if len(stack) == 10:
                body = self._get_body(stack, output)
                data = self._jsonify(body)
                requests.append(data)
                stack = list()

        if stack:
            body = self._get_body(stack, output)
            data = self._jsonify(body)
            requests.append(data)

        headers = {'Content-Type': 'application/json'}
        result = list()

        for req in requests:
            if self._nxapi_auth:
                headers['Cookie'] = self._nxapi_auth

            response, headers = fetch_url(self.url_args,
                                          self.url,
                                          data=data,
                                          headers=headers,
                                          method='POST')
            self._nxapi_auth = headers.get('set-cookie')

            if 'Connection failure: timed out' == headers.get('msg'):
                pass
            else:
                if headers['status'] != 200:
                    self._error(**headers)

                try:
                    response = json.loads(response.read())
                except ValueError:
                    raise NetworkError(
                        msg='unable to load response from device')

                output = response['ins_api']['outputs']['output']
                for item in to_list(output):
                    if item['code'] != '200':
                        self._error(output=output, **item)
                    else:
                        result.append(item['body'])

        return result
Exemple #26
0
    def configure(self, commands, **kwargs):
        cmds = ['configure']
        cmds.extend(to_list(commands))

        if kwargs.get('comment'):
            cmds.append('commit and-quit comment "%s"' % kwargs.get('comment'))
        else:
            cmds.append('commit and-quit')

        responses = self.execute(cmds)
        return responses[1:-1]
Exemple #27
0
    def configure(self, commands, comment=None):
        cmds = ['configure']
        cmds.extend(to_list(commands))

        if comment:
            cmds.append('commit and-quit comment "%s"' % comment)
        else:
            cmds.append('commit and-quit')

        responses = self.execute(cmds)
        return responses[1:-1]
Exemple #28
0
    def configure(self, commands, comment=None):
        cmds = ['configure']
        cmds.extend(to_list(commands))

        if comment:
            cmds.append('commit and-quit comment "%s"' % comment)
        else:
            cmds.append('commit and-quit')

        responses = self.execute(cmds)
        return responses[1:-1]
Exemple #29
0
def prepare_commands(commands):
    jsonify = lambda x: '%s | json' % x
    for item in to_list(commands):
        if item.output == 'json':
            cmd = jsonify(item)
        elif item.command.endswith('| json'):
            item.output = 'json'
            cmd = str(item)
        else:
            cmd = str(item)
        yield cmd
Exemple #30
0
def prepare_commands(commands):
    jsonify = lambda x: '%s | json' % x
    for item in to_list(commands):
        if item.output == 'json':
            cmd = jsonify(item)
        elif item.command.endswith('| json'):
            item.output = 'json'
            cmd = str(item)
        else:
            cmd = str(item)
        yield cmd
Exemple #31
0
    def configure(self, commands, **kwargs):
        cmds = ['configure terminal']
        cmdlist = list()
        for c in to_list(commands):
            cmd = Command(c, prompt=self.WARNING_PROMPTS_RE, response='yes')
            cmdlist.append(cmd)
        cmds.extend(cmdlist)
        cmds.append('end')

        responses = self.execute(cmds)
        responses.pop(0)
        return responses
Exemple #32
0
def prepare_commands(commands):
    """ prepare_commands """

    def jsonify(x):
        return '%s | json' % x

    for cmd in to_list(commands):
        if cmd.output == 'json':
            cmd.command_string = jsonify(cmd)
        if cmd.command.endswith('| json'):
            cmd.output = 'json'
        yield cmd
    def execute(self, commands, output=None, **kwargs):
        commands = collections.deque(commands)
        output = output or self.default_output

        # only 10 commands can be encoded in each request
        # messages sent to the remote device
        stack = list()
        requests = list()

        while commands:
            stack.append(commands.popleft())
            if len(stack) == 10:
                body = self._get_body(stack, output)
                data = self._jsonify(body)
                requests.append(data)
                stack = list()

        if stack:
            body = self._get_body(stack, output)
            data = self._jsonify(body)
            requests.append(data)

        headers = {'Content-Type': 'application/json'}
        result = list()

        for req in requests:
            if self._nxapi_auth:
                headers['Cookie'] = self._nxapi_auth

            response, headers = fetch_url(
                self.url_args, self.url, data=data, headers=headers, method='POST'
            )
            self._nxapi_auth = headers.get('set-cookie')

            if 'Connection failure: timed out' == headers.get('msg'):
                pass
            else:
                if headers['status'] != 200:
                    self._error(**headers)

                try:
                    response = json.loads(response.read())
                except ValueError:
                    raise NetworkError(msg='unable to load response from device')

                output = response['ins_api']['outputs']['output']
                for item in to_list(output):
                    if item['code'] != '200':
                        self._error(output=output, **item)
                    else:
                        result.append(item['body'])

        return result
Exemple #34
0
    def execute(self, commands, output=None, **kwargs):
        """Send commands to the device.
        """
        commands = to_list(commands)
        output = output or self.default_output

        data = self._get_body(commands, output)
        data = self._jsonify(data)

        headers = {'Content-Type': 'application/json'}
        if self._nxapi_auth:
            headers['Cookie'] = self._nxapi_auth

        response, headers = fetch_url(self.url_args,
                                      self.url,
                                      data=data,
                                      headers=headers,
                                      method='POST')
        self._nxapi_auth = headers.get('set-cookie')

        if headers['status'] != 200:
            self._error(**headers)

        try:
            response = json.loads(response.read())
        except ValueError:
            raise NetworkError(msg='unable to load repsonse from device')

        result = list()

        output = response['ins_api']['outputs']['output']
        for item in to_list(output):
            if item['code'] != '200':
                self._error(**item)
            else:
                result.append(item['body'])

        return result
Exemple #35
0
def prepare_commands(commands):
    """ transforms a list of Command objects to dict

    :param commands: list of Command objects

    :returns: list of dict objects
    """
    jsonify = lambda x: '%s | json' % x
    for cmd in to_list(commands):
        if cmd.output == 'json':
            cmd = jsonify(cmd)
        else:
            cmd = str(cmd)
        yield cmd
Exemple #36
0
    def execute(self, commands, output=None, **kwargs):
        """Send commands to the device.
        """
        commands = to_list(commands)
        output = output or self.default_output

        data = self._get_body(commands, output)
        data = self._jsonify(data)

        headers = {'Content-Type': 'application/json'}
        if self._nxapi_auth:
            headers['Cookie'] = self._nxapi_auth

        response, headers = fetch_url(
            self.url_args, self.url, data=data, headers=headers, method='POST'
        )
        self._nxapi_auth = headers.get('set-cookie')

        if headers['status'] != 200:
            self._error(**headers)

        try:
            response = json.loads(response.read())
        except ValueError:
            raise NetworkError(msg='unable to load repsonse from device')

        result = list()

        output = response['ins_api']['outputs']['output']
        for item in to_list(output):
            if item['code'] != '200':
                self._error(**item)
            else:
                result.append(item['body'])

        return result
Exemple #37
0
def prepare_commands(commands):
    """ transforms a list of Command objects to dict

    :param commands: list of Command objects

    :returns: list of dict objects
    """
    jsonify = lambda x: '%s | json' % x
    for item in to_list(commands):
        if item.output == 'json':
            cmd = jsonify(cmd)
        elif item.command.endswith('| json'):
            item.output = 'json'
            cmd = str(item)
        else:
            cmd = str(item)
        yield cmd
 def run_commands(self, commands):
     return self.execute(to_list(commands))
Exemple #39
0
 def run_commands(self, commands):
     cmds = to_list(commands)
     responses = self.execute(cmds)
     return responses
Exemple #40
0
def prepare_config(commands):
    prepared = ['config']
    prepared.extend(to_list(commands))
    prepared.append('end')
    return prepared
Exemple #41
0
 def run_commands(self, commands, **kwargs):
     return self.execute(to_list(commands))
Exemple #42
0
 def configure(self, commands):
     cmds = ['configure terminal']
     cmds.extend(to_list(commands))
     responses = self.execute(cmds)
     return responses[1:]
Exemple #43
0
def prepare_config(commands):
    commands = to_list(commands)
    commands.insert(0, 'configure')
    commands.append('end')
    return commands
Exemple #44
0
 def run_commands(self, commands, **kwargs):
     output = kwargs.get('format') or 'xml'
     return self.execute(to_list(commands), format=output)
Exemple #45
0
 def run_commands(self, commands, **kwargs):
     commands = to_list(commands)
     response = self.execute([str(c) for c in commands])
     return response
Exemple #46
0
 def run_commands(self, commands):
     cmds = to_list(commands)
     responses = self.execute(cmds)
     return responses
Exemple #47
0
 def configure(self, commands):
     commands = to_list(commands)
     return self.execute(commands, output='config')
Exemple #48
0
def prepare_config(commands):
    prepared = ['config']
    prepared.extend(to_list(commands))
    prepared.append('end')
    return prepared
Exemple #49
0
 def run_commands(self, commands):
     commands = to_list(commands)
     return self.execute([str(c) for c in commands])
Exemple #50
0
def load_config(module, commands, nodiff=False):
    contents = '\n'.join(to_list(commands))
    candidate = NetworkConfig(contents=contents, indent=1)
    return load_candidate(module, candidate, nodiff)
Exemple #51
0
 def configure(self, commands):
     commands = to_list(commands)
     return self.execute(commands, output='config')
Exemple #52
0
 def configure(self, commands, **kwargs):
     cmds = to_list(commands)
     responses = self.execute(cmds)
     self.execute(['exit all'])
     return responses
Exemple #53
0
 def run_commands(self, commands, **kwargs):
     commands = to_list(commands)
     return self.execute([str(c) for c in commands])
Exemple #54
0
def prepare_config(commands):
    commands = to_list(commands)
    commands.insert(0, 'configure terminal')
    commands.append('end')
    return commands