def invoke(self, mc, *ignored): caps = list(mc.server_capabilities) hello = new_ele("hello") xcaps = sub_ele(hello, "capabilities") for cap in caps: sub_ele(xcaps, "capability").text = cap return hello
def parseChild(parent, part): for key, value in part.iteritems(): if isinstance(value, dict): node = sub_ele(parent, key) # Need to go deeper -> recursion parseChild(node, value) elif value is not None: node = sub_ele(parent, key) node.text = str(value)
def main(): """main entry point for Ansible module """ argument_spec = dict( rpc=dict(required=True), args=dict(type='dict'), output=dict(default='xml', choices=['xml', 'json', 'text']), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) result = {'changed': False} rpc = str(module.params['rpc']).replace('_', '-') if all((module.check_mode, not rpc.startswith('get'))): module.fail_json(msg='invalid rpc for running in check_mode') args = module.params['args'] or {} xattrs = {'format': module.params['output']} element = new_ele(module.params['rpc'], xattrs) for key, value in iteritems(args): key = str(key).replace('_', '-') if isinstance(value, list): for item in value: child = sub_ele(element, key) if item is not True: child.text = item else: child = sub_ele(element, key) if value is not True: child.text = value reply = send_request(module, element) result['xml'] = str(to_xml(reply)) if module.params['output'] == 'text': reply = to_ele(reply) data = reply.xpath('//output') result['output'] = data[0].text.strip() result['output_lines'] = result['output'].split('\n') elif module.params['output'] == 'json': reply = to_ele(reply) data = reply.xpath('//rpc-reply') result['output'] = module.from_json(data[0].text.strip()) else: result['output'] = str(to_xml(reply)).split('\n') module.exit_json(**result)
def commit(self, confirmed=False, check=False, timeout=None, comment=None, synchronize=False, at_time=None): """Commit the candidate configuration as the device's new current configuration. Depends on the `:candidate` capability. A confirmed commit (i.e. if *confirmed* is `True`) is reverted if there is no followup commit within the *timeout* interval. If no timeout is specified the confirm timeout defaults to 600 seconds (10 minutes). A confirming commit may have the *confirmed* parameter but this is not required. Depends on the `:confirmed-commit` capability. :confirmed: whether this is a confirmed commit :timeout: specifies the confirm timeout in seconds """ obj = new_ele('commit-configuration') if confirmed: sub_ele(obj, 'confirmed') if check: sub_ele(obj, 'check') if synchronize: sub_ele(obj, 'synchronize') if at_time: subele = sub_ele(obj, 'at-time') subele.text = str(at_time) if comment: subele = sub_ele(obj, 'log') subele.text = str(comment) if timeout: subele = sub_ele(obj, 'confirm-timeout') subele.text = str(timeout) return self.rpc(obj)
def commit(self, confirmed=False, check=False, timeout=None, comment=None, synchronize=False, at_time=None): """ Commit the candidate configuration as the device's new current configuration. Depends on the `:candidate` capability. A confirmed commit (i.e. if *confirmed* is `True`) is reverted if there is no followup commit within the *timeout* interval. If no timeout is specified the confirm timeout defaults to 600 seconds (10 minutes). A confirming commit may have the *confirmed* parameter but this is not required. Depends on the `:confirmed-commit` capability. :param confirmed: whether this is a confirmed commit :param check: Check correctness of syntax :param timeout: specifies the confirm timeout in seconds :param comment: Message to write to commit log :param synchronize: Synchronize commit on remote peers :param at_time: Time at which to activate configuration changes :return: Received rpc response from remote host """ obj = new_ele('commit-configuration') if confirmed: sub_ele(obj, 'confirmed') if check: sub_ele(obj, 'check') if synchronize: sub_ele(obj, 'synchronize') if at_time: subele = sub_ele(obj, 'at-time') subele.text = str(at_time) if comment: subele = sub_ele(obj, 'log') subele.text = str(comment) if timeout: subele = sub_ele(obj, 'confirm-timeout') subele.text = str(timeout) return self.rpc(obj)
def map_obj_to_ele(want): element = new_ele('system') login = sub_ele(element, 'login', {'replace': 'replace'}) for item in want: if item['state'] != 'present': operation = 'delete' else: operation = 'replace' user = sub_ele(login, 'user', {'operation': operation}) sub_ele(user, 'name').text = item['name'] if operation == 'replace': sub_ele(user, 'class').text = item['role'] if item.get('full_name'): sub_ele(user, 'full-name').text = item['full_name'] if item.get('sshkey'): auth = sub_ele(user, 'authentication') ssh_rsa = sub_ele(auth, 'ssh-rsa') key = sub_ele(ssh_rsa, 'name').text = item['sshkey'] return element
def commit_configuration(module, confirm=False, check=False, comment=None, confirm_timeout=None): obj = new_ele('commit-configuration') if confirm: sub_ele(obj, 'confirmed') if check: sub_ele(obj, 'check') if comment: children(obj, ('log', str(comment))) if confirm_timeout: children(obj, ('confirm-timeout', int(confirm_timeout))) return send_request(module, obj)
def build_child_xml_node(parent, tag, text=None, attrib=None): element = sub_ele(parent, tag) if text: element.text = to_text(text) if attrib: element.attrib.update(attrib) return element
def conn(username, passwd, port): for router, n in zip(routers, range(1, 5)): with manager.connect(host=router, username=username, password=passwd, port=port, timeout=10, device_params={'name': 'junos'}, hostkey_verify=False) as dev: if dev: print(f'{router} - connected.') #configure hostname hostname = new_ele('system') sub_ele(hostname, 'host-name').text = f'router{n}' #lock config dev.lock() #load hostname configuration dev.load_configuration(config=hostname) #validate configuration dev.validate() #commit confirm configuration dev.commit(confirmed=True, timeout='300') #unlock configuration dev.unlock()
def query(self, *args): filter_node = new_ele("filter") conf = sub_ele(filter_node, "configuration") for arg in args: conf.append(arg()) return self.netconf.get_config( source="candidate" if self.in_transaction else "running", filter=filter_node)
def test_get_config(self): print ' ' print '********* ' + sys._getframe().f_code.co_name + ' *********' nc = NetconfClient(self.host, self.port, self.username, self.password) config = nc.get_config() self.assertTrue(config != None, 'Configuration must be set.') print 'Configuration obtained:\n'\ + etree.tostring(config, pretty_print=True, encoding=unicode) self.assertNotEquals(None, config) config_filter = new_ele('configuration') system_ele = sub_ele(config_filter, 'system') sub_ele(system_ele, 'license') config = nc.get_config(config_filter) self.assertTrue(config != None, 'Filtered configuration must be set.') print 'Filtered configuration obtained:\n'\ + etree.tostring(config, pretty_print=True, encoding=unicode)
def load_configuration(module, candidate=None, action='merge', rollback=None, format='xml'): if all((candidate is None, rollback is None)): module.fail_json(msg='one of candidate or rollback must be specified') elif all((candidate is not None, rollback is not None)): module.fail_json(msg='candidate and rollback are mutually exclusive') if format not in FORMATS: module.fail_json(msg='invalid format specified') if format == 'json' and action not in JSON_ACTIONS: module.fail_json(msg='invalid action for format json') elif format in ('text', 'xml') and action not in ACTIONS: module.fail_json(msg='invalid action format %s' % format) if action == 'set' and not format == 'text': module.fail_json(msg='format must be text when action is set') if rollback is not None: validate_rollback_id(rollback) xattrs = {'rollback': str(rollback)} else: xattrs = {'action': action, 'format': format} obj = new_ele('load-configuration', xattrs) if candidate is not None: lookup = { 'xml': 'configuration', 'text': 'configuration-text', 'set': 'configuration-set', 'json': 'configuration-json' } if action == 'set': cfg = sub_ele(obj, 'configuration-set') cfg.text = '\n'.join(candidate) else: cfg = sub_ele(obj, lookup[format]) cfg.append(candidate) return send_request(module, obj)
def request(self, config, format='xml', target='candidate', default_operation=None, test_option=None, error_option=None): """Loads all or part of the specified *config* to the *target* configuration datastore. *target* is the name of the configuration datastore being edited *config* is the configuration, which must be rooted in the `config` element. It can be specified either as a string or an :class:`~xml.etree.ElementTree.Element`. *default_operation* if specified must be one of { `"merge"`, `"replace"`, or `"none"` } *test_option* if specified must be one of { `"test_then_set"`, `"set"` } *error_option* if specified must be one of { `"stop-on-error"`, `"continue-on-error"`, `"rollback-on-error"` } The `"rollback-on-error"` *error_option* depends on the `:rollback-on-error` capability. """ node = new_ele("edit-config") # node.append(util.datastore_or_url("target", target, self._assert)) node.append( operations.util.datastore_or_url("target", target, self._assert)) if error_option is not None: if error_option == "rollback-on-error": self._assert(":rollback-on-error") sub_ele(node, "error-option").text = error_option if test_option is not None: self._assert(':validate') sub_ele(node, "test-option").text = test_option if default_operation is not None: # TODO: check if it is a valid default-operation sub_ele(node, "default-operation").text = default_operation # <<<<<<< HEAD # node.append(validated_element(config, ("config", qualify("config")))) # ======= if format == 'xml': # node.append(validated_element(config, ("config", qualify("config")))) _append(node, validated_element(config, ("config", qualify("config")))) if format == 'text': config_text = sub_ele(node, "config-text") sub_ele(config_text, "configuration-text").text = config # >>>>>>> juniper return self._request(node)
def connect(host, port, user, password, source): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=60, device_params={'name': 'junos'}, hostkey_verify=False) logging.info('locking configuration') lock_result = conn.lock() logging.info(lock_result) # build configuration element config = new_ele('system') sub_ele(config, 'host-name').text = 'spine02' sub_ele(config, 'domain-name').text = 'flyip.org' #print(to_xml(config)) load_config_result = conn.load_configuration(config=config) logging.info(load_config_result) validate_result = conn.validate() logging.info(validate_result) compare_config_result = conn.compare_configuration() logging.info(compare_config_result) logging.info('commit confirmed') commit_config = conn.commit(confirmed=True, timeout='300') logging.info(commit_config) logging.info('sleeping for 5 sec...') time.sleep(5) discard_changes_result = conn.discard_changes() logging.info(discard_changes_result) logging.info('unlocking configuration') unlock_result = conn.unlock() logging.info(unlock_result)
def connect(host, user, password): conn = manager.connect(host=host, username=user, password=password, timeout=10, hostkey_verify=False) conn.lock() root = new_ele('config') configuration = sub_ele(root, 'configuration') system = sub_ele(configuration, 'system') location = sub_ele(system, 'location') sub_ele(location, 'building').text = "Main Campus, A" sub_ele(location, 'floor').text = "5" sub_ele(location, 'rack').text = "27" send_config = conn.edit_config(config=root) print send_config.tostring check_config = conn.validate() print check_config.tostring compare_config = conn.compare_configuration() print compare_config.tostring conn.commit() conn.unlock() conn.close_session()
def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=60, device_params={'name': 'junos'}, hostkey_verify=False) conn.lock() root = new_ele('config') configuration = sub_ele(root, 'configuration') system = sub_ele(configuration, 'system') location = sub_ele(system, 'location') sub_ele(location, 'building').text = "Main Campus, A" sub_ele(location, 'floor').text = "5" sub_ele(location, 'rack').text = "27" #print(to_xml(root, pretty_print=True)) edit_config_result = conn.edit_config(config=root) logging.info(edit_config_result) validate_result = conn.validate() logging.info(validate_result) compare_config_result = conn.compare_configuration() logging.info(compare_config_result) conn.commit() conn.unlock() conn.close_session()
def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=60, device_params={'name': 'junos'}, hostkey_verify=False) conn.lock() root = new_ele('config') configuration = sub_ele(root, 'configuration') system = sub_ele(configuration, 'system') location = sub_ele(system, 'location') sub_ele(location, 'building').text = "Main Campus, A" sub_ele(location, 'floor').text = "5" sub_ele(location, 'rack').text = "27" edit_config_result = conn.edit_config(config=root) logging.info(edit_config_result) validate_result = conn.validate() logging.info(validate_result) compare_config_result = conn.compare_configuration() logging.info(compare_config_result) conn.commit() conn.unlock() conn.close_session()
def invoke(self, mc, ns, filename="-"): data = etree.parse(sys.stdin if filename == "-" else open(filename, "r")) copy = new_ele("copy-config") sub_ele(sub_ele(copy, "target"), ns.db) sub_ele(sub_ele(copy, "source"), "config").append(data.getroot()) reply = mc.rpc(copy) return reply._root[0]
class NetconfMethods (netconf_server.NetconfMethods): #build the config nc_config = new_ele('config') configuration = sub_ele(nc_config, 'configuration') system = sub_ele(configuration, 'system') location = sub_ele(system, 'location') sub_ele(location, 'building').text = "Main Campus, A" sub_ele(location, 'floor').text = "5" sub_ele(location, 'rack').text = "27" #<netconf-state xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring"> #<schemas/> #</netconf-state> @classmethod def rpc_get (cls, unused_session, rpc, *unused_params): #return etree.Element("ok") #return cls.nc_config root = etree.Element('data') child1 = etree.SubElement(root, 'device', xmlns="http://ipv6lab.beuth-hochschule.de/led") #for element in elementCollections: #listOfElements = ['1', '2', '3'] #for ele in listOfElements: #set for ele in uuid_set: child2 = etree.SubElement(child1, "device-id") child3 = etree.SubElement(child2, "uuid") child3.text = ele child4 = etree.SubElement(child1, "device-category") child4.text = device_category #newtree = etree.tostring(root, encoding='utf-8') #newtree = newtree.decode("utf-8") #print newtree return root def rpc_hubble (self, unused_session, rpc, *unused_params): return etree.Element("okidoki") def rpc_get_schema(self, unused_session, rpc, *unused_params): root = etree.Element("data", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") root.text = etree.CDATA(yangModel) print (command_dict) return root
def build_Netconf_Methods(method_Name, mqtt_Parameter): logger.info("build_Netconf_Methods called: " + method_Name + mqtt_Parameter) ld = {} string = 'self.extra = "Hello"' exec(""" def rpc_%s(self, unused_session, rpc, *unused_params): %s #print (locals().keys()) for k in unused_params: print ("Element: " + k.tag + "Text: " + k.text) #print(self.extra) topic = "LIFX/" + k.text mqtt_client.publish(topic, "%s") return etree.Element("%s") """ % (method_Name, string, mqtt_Parameter, method_Name), None, ld) print('locals got: {}'.format(ld)) for name, value in ld.items(): setattr(NetconfMethods, name, value) #attach RPC to configuration rpc = sub_ele(NetconfMethods.configuration,"""rpc_%s""" % (method_Name))
def children(root, iterable): for item in iterable: try: ele = sub_ele(ele, item) except NameError: ele = sub_ele(root, item)
def add_protocol(self, protocol): if self.protocols_root is None: self.protocols_root = sub_ele(self.root, "protocols") self.protocols_root.append(protocol)
def add_interface(self, interface): if self.interfaces_root is None: self.interfaces_root = sub_ele(self.root, "interfaces") self.interfaces_root.append(interface)
def add_vlan(self, vlan): if self.vlans_root is None: self.vlans_root = sub_ele(self.root, "vlans") self.vlans_root.append(vlan)
def query(self, *args): filter_node = new_ele("filter") conf = sub_ele(filter_node, "configuration") for arg in args: conf.append(arg()) return self.netconf.get_config(source="candidate" if self.in_transaction else "running", filter=filter_node)
from ncclient import manager from ncclient.xml_ import new_ele, sub_ele conn = manager.connect(host='192.168.24.252', port='830', username='******', password='******', timeout=10, device_params={'name': 'junos'}, hostkey_verify=False) # lock configuration and make configuration changes conn.lock() # build configuration config = new_ele('system') sub_ele(config, 'host-name').text = 'master' sub_ele(config, 'domain-name').text = 'python' # send, validate, and commit config conn.load_configuration(config=config) conn.validate() commit_config = conn.commit() print(commit_config.tostring) # unlock config conn.unlock() # close session conn.close_session()
platform = data['device'][key]['platform'] if platform == 'junos': conn = manager.connect( host = ip, port = 830, username = user, password = pw, timeout = 10, device_params = {'name' : 'junos'}, hostkey_verify = False ) #lock configuration. conn.lock #Build configration config = new_ele('system') sub_ele(config, 'host-name').text = 'vmx' #Upload , validate, and commit configuration conn.load_configuration(config=config) conn.validate() commit_config = conn.commit() print(commit_config.tostring) #unlock config #conn.unlock #result = conn.rpc(rpc) #print(result) # close session conn.close_session()
def add_vlan(self, vlan, root_ele): if self.vlans_root is None: self.vlans_root = sub_ele(self.root, root_ele) self.vlans_root.append(vlan)
def __interfaces_filter(): config_filter = new_ele('configuration') sub_ele(config_filter, 'interfaces') return config_filter
def __security_ipsec_filter(): config_filter = new_ele('configuration') sec = sub_ele(config_filter, 'security') sub_ele(sec, 'ipsec') return config_filter
def __security_policies_filter(): config_filter = new_ele('configuration') sec = sub_ele(config_filter, 'security') sub_ele(sec, 'policies') return config_filter
timeout=10, device_params={'name': 'junos'}, hostkey_verify=False) return connection # execute show commands def show_cmds(conn, cmd): result = conn.command(cmd, format='text') return result # push out configuration def config_cmds(conn, config): conn.lock() conn.load_configuration(config=config) commit_config = conn.commit() return commit_config.tostring if __name__ == '__main__': conn = connect('192.168.24.252', '830', 'netconf', 'juniper!') result = show_cmds(conn, 'show version') print('show version: ' + str(result)) new_config = new_ele('system') sub_ele(new_config, 'host-name').text = 'foo' sub_ele(new_config, 'domain-name').text = 'bar' result = config_cmds(conn, new_config) print('change id: ' + str(result)) conn.close_session()