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)
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]
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:]
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)
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)
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:]
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
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
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]
def prepare_config(commands): """ prepare_config """ prepared = list() prepared.extend(to_list(commands)) prepared.append('return') return prepared
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
def configure(self, commands, **kwargs): cmds = ['configure'] cmds.extend(to_list(commands)) cmds.append('end') responses = self.execute(cmds) return responses[1:-1]
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)
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)
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
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
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
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
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
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
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
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
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]
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]
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]
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
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
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
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
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
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
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
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))
def run_commands(self, commands): cmds = to_list(commands) responses = self.execute(cmds) return responses
def prepare_config(commands): prepared = ['config'] prepared.extend(to_list(commands)) prepared.append('end') return prepared
def run_commands(self, commands, **kwargs): return self.execute(to_list(commands))
def configure(self, commands): cmds = ['configure terminal'] cmds.extend(to_list(commands)) responses = self.execute(cmds) return responses[1:]
def prepare_config(commands): commands = to_list(commands) commands.insert(0, 'configure') commands.append('end') return commands
def run_commands(self, commands, **kwargs): output = kwargs.get('format') or 'xml' return self.execute(to_list(commands), format=output)
def run_commands(self, commands, **kwargs): commands = to_list(commands) response = self.execute([str(c) for c in commands]) return response
def run_commands(self, commands): cmds = to_list(commands) responses = self.execute(cmds) return responses
def configure(self, commands): commands = to_list(commands) return self.execute(commands, output='config')
def prepare_config(commands): prepared = ['config'] prepared.extend(to_list(commands)) prepared.append('end') return prepared
def run_commands(self, commands): commands = to_list(commands) return self.execute([str(c) for c in commands])
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)
def configure(self, commands): commands = to_list(commands) return self.execute(commands, output='config')
def configure(self, commands, **kwargs): cmds = to_list(commands) responses = self.execute(cmds) self.execute(['exit all']) return responses
def run_commands(self, commands, **kwargs): commands = to_list(commands) return self.execute([str(c) for c in commands])
def prepare_config(commands): commands = to_list(commands) commands.insert(0, 'configure terminal') commands.append('end') return commands