def reconnect(self): """ Reconnect session with device. Args: None Returns: bool: True if reconnect succeeds, False if not. Raises: None """ if self._auth_method is "userpass": self._mgr = manager.connect(host=self._conn[0], port=self._conn[1], username=self._auth[0], password=self._auth[1], hostkey_verify=self._hostkey_verify) elif self._auth_method is "key": self._mgr = manager.connect(host=self._conn[0], port=self._conn[1], username=self._auth[0], key_filename=self._auth_key, hostkey_verify=self._hostkey_verify) else: raise ValueError("auth_method incorrect value.") self._mgr.timeout = 600 return True
def demo(host, user, password): session = manager.connect(host=host, port=830, username=user, password=password, hostkey_verify=False, look_for_keys=False, allow_agent=False) subscribe = manager.connect(host=host, port=830, username=user, password=password, hostkey_verify=False, look_for_keys=False, allow_agent=False) subscribe.create_subscription(callback, errback, manager=subscribed_manager, filter=('xpath', '/*')) session.edit_config(target='running', config=snippet)
def configure_service(self, *args, **kwargs): """configure the service """ #self._check_connection() LOG.debug(_("Ellis configure service")) LOG.debug(_(self.hsip)) LOG.debug(_(self.homerip)) conf_dict = {"private_ip": self.localip , "public_ip": self.publicip , "chronos_ip": self.localip,"homer_ip": self.homerip, "homestead_ip": self.hsip , "service_name": "ellis"} confstr = templates.ellis_settings.format(**conf_dict) configuration_done = False while not configuration_done: try: with manager.connect(host=self.mgmtip, username=self.username, password=self.password, port=830, hostkey_verify=False) as m: print "VM is UP" LOG.debug(_("VM is UP")) configuration_done = True c = m.get_config(source='running').data_xml LOG.debug(_("config %s"), c) #c1 = m.edit_config(target='candidate', config=confstr1) #m.commit() c2 = m.edit_config(target='candidate', config=confstr) m.commit(confirmed=False, timeout=300) except Exception as e: LOG.debug(_("VM is DOWN %s"), e) LOG.debug(_("VM is DOWN")) print e print "VM is down" time.sleep(5)
def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params={'name': 'junos'}, hostkey_verify=False) junos_dev_handler = JunosDeviceHandler( device_params={'name': 'junos', 'local': False}) conn.async_mode = True rpc = new_ele('get-software-information') obj = conn.rpc(rpc) # for demo purposes, we just wait for the result while not obj.event.is_set(): print('waiting for answer ...') time.sleep(.3) result = NCElement(obj.reply, junos_dev_handler.transform_reply() ).remove_namespaces(obj.reply.xml) print 'Hostname: ', result.findtext('.//host-name')
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) template = """<system><scripts><commit> <file delete="delete"><name>test.slax</name></file> </commit></scripts></system>""" conn.lock() config = to_ele(template) 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) conn.commit() conn.unlock() conn.close_session()
def connect(host, port, user, password, source): global now try: show_command = sys.argv[1] except IndexError: print "please specify show command as first argument." sys.exit(1) try: xpath_expr = sys.argv[2] except IndexError: xpath_expr='' conn = manager.connect(host=host, port=port, username=user, password=password, timeout=3, device_params = {'name':'junos'}, hostkey_verify=False) curr_time = now.isoformat() #t = """<system-restart xmlns="http://www.polatis.com/yang/optical-switch"/>""" #t = """<set-current-datetime xmlns="http://www.polatis.com/yang/optical-switch"><current-datetime>2015-02-18T09:08:15.949336</current-datetime></set-current-datetime>""" t = """<set-current-datetime xmlns="http://www.polatis.com/yang/optical-switch"><current-datetime>%s</current-datetime></set-current-datetime>""" % curr_time try: #result = conn.command(command=show_command, format='xml') result = conn.rpc(t) print "result is : %s" % result except Exception, e: print "ncclient_demo.py: Encountered critical error" print e
def _connect(self, host): """Create SSH connection to the Huawei switch.""" if getattr(self.connections.get(host), 'connected', None): return self.connections[host] port = self.port user = self.user password = self.password msg = _('Connect to Huawei switch successful.' 'host:%s, user:%s, password:%s') % (host, user, password) LOG.debug(msg) try: conn = manager.connect(host=host, port=port, username=user, password=password, hostkey_verify=False, device_params={'name': "huawei"}, timeout=30) self.connections[host] = conn except HuaweiSwitchConfigError: LOG.info("Failed to connect to switch.") raise ml2_except.MechanismDriverError return self.connections[host]
def demo(host, user, password): with manager.connect(host=host, port=830, username=user, password=password, hostkey_verify=False, device_params={'name':'default'}, look_for_keys=False, allow_agent=False) as m: with m.locked(target="candidate"): m.edit_config(config=config_e, default_operation="merge", target="candidate") m.commit()
def push_configuration(self, instance, mgmt_ip, configuration_event): try: LOG.debug(_("***** CONFIGURATION EVENT *****:%s"),configuration_event) LOG.debug(_("***** LIFECYCLE EVENTS *****:%s"),self.lifecycle_events) config_xml = '<config>'+self.lifecycle_events[configuration_event]+'</config>' LOG.debug(_("DRIVER CODE RECEIVED IP**:%s"),mgmt_ip) self._check_connection(mgmt_ip) import pdb;pdb.set_trace() time.sleep(5) mgr = manager.connect(host=mgmt_ip, port=self.port, username=self.username, password=self.password, hostkey_verify=False) LOG.debug(_("Driver nc client manager instantiated: %s"), mgr) mgr.lock() LOG.debug(_("Configuration XML is: %s"), config_xml) mgr.edit_config(target='candidate', config=config_xml) mgr.commit() mgr.unlock() mgr.close_session() status = "COMPLETE" except KeyError: LOG.debug(_("Configuration Event not in Lifecycle Events")) status = "ERROR" except Exception: status = "ERROR" finally: return status
def get_config(host,user,passwd): with manager.connect(host=host, port=22, username=user, password=passwd, hostkey_verify=False, device_params={'name':'nexus'}) as m: # c = m.get_config(source='running').data_xml c = m.get(filter=('subtree', '<cmd>show running-config</cmd>')).data_xml with open("%s.xml" % host, 'w') as f: f.write(c)
def connect(host, port, user, password, source): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) template = """<system><scripts><commit><file delete="delete"><name>test.slax</name></file></commit></scripts></system>""" conn.lock() config = to_ele(template) send_config = conn.load_configuration(config=config) 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 config_via_netconf(cmd_string, timeout=10, device='junos', hostkey_verify="False"): if hostkey_verify == 'False': hostkey_verify = bool(False) timeout = int(timeout) if device == 'junos': device_params = {'name': 'junos'} cmdList = cmd_string.split(';') ip = env.host from ncclient import manager try: conn = manager.connect(host=str(ip), username=env.user, password=env.password, timeout=timeout, device_params=device_params, hostkey_verify=hostkey_verify) conn.lock() send_config = conn.load_configuration(action='set', config=cmdList) print send_config.tostring check_config = conn.validate() print check_config.tostring compare_config = conn.compare_configuration() print compare_config.tostring conn.commit() if 'family mpls mode packet-based' in cmd_string: conn.reboot() conn.unlock() conn.close_session() print compare_config.tostring return "True" except Exception, e: return "False"
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(self, host, username, password): """Connect via SSH and initialize the NETCONF session.""" # Use the persisted NETCONF connection if self.mgr and self.mgr.connected: return self.mgr # check if someone forgot to edit the conf file with real values if host == '': raise Exception(_("Brocade Switch IP address is not set, " "check config ml2_conf_brocade.ini file")) # Open new NETCONF connection try: self.mgr = manager.connect(host=host, port=SSH_PORT, username=username, password=password, unknown_host_cb=nos_unknown_host_cb) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("Connect failed to switch")) LOG.debug("Connect success to host %(host)s:%(ssh_port)d", dict(host=host, ssh_port=SSH_PORT)) return self.mgr
def send_netconf(self, new_config, default_operation="merge", operation="replace"): if (self.vendor is None or self.product is None or self.vendor.lower() != "juniper" or self.product.lower() != "mx"): self._logger.info("auto configuraion of physical router is not supported \ on the configured vendor family, ip: %s, not pushing netconf message" % (self.management_ip)) self.commit_stats['netconf_enabled'] = False self.commit_stats['netconf_enabled_status'] = "netconf configuraion is not supported on this vendor/product family" return if (self.vnc_managed is None or self.vnc_managed == False): self._logger.info("vnc managed property must be set for a physical router to get auto \ configured, ip: %s, not pushing netconf message" % (self.management_ip)) self.commit_stats['netconf_enabled'] = False self.commit_stats['netconf_enabled_status'] = "netconf auto configuraion is not enabled on this physical router" return self.commit_stats['netconf_enabled'] = True self.commit_stats['netconf_enabled_status'] = '' start_time = None try: with manager.connect(host=self.management_ip, port=22, username=self.user_creds['username'], password=self.user_creds['password'], unknown_host_cb=lambda x, y: True) as m: add_config = etree.Element( "config", nsmap={"xc": "urn:ietf:params:xml:ns:netconf:base:1.0"}) config = etree.SubElement(add_config, "configuration") config_group = etree.SubElement(config, "groups", operation=operation) contrail_group = etree.SubElement(config_group, "name") contrail_group.text = "__contrail__" if isinstance(new_config, list): for nc in new_config: config_group.append(nc) else: config_group.append(new_config) if operation == "delete": apply_groups = etree.SubElement(config, "apply-groups", operation=operation) else: apply_groups = etree.SubElement(config, "apply-groups") apply_groups.text = "__contrail__" self._logger.info("\nsend netconf message: %s\n" % (etree.tostring(add_config, pretty_print=True))) m.edit_config( target='candidate', config=etree.tostring(add_config), test_option='test-then-set', default_operation=default_operation) self.commit_stats['total_commits_sent_since_up'] += 1 start_time = time.time() m.commit() end_time = time.time() self.commit_stats['commit_status_message'] = 'success' self.commit_stats['last_commit_time'] = datetime.datetime.fromtimestamp(end_time).strftime('%Y-%m-%d %H:%M:%S') self.commit_stats['last_commit_duration'] = str(end_time - start_time) except Exception as e: if self._logger: self._logger.error("Router %s: %s" % (self.management_ip, e.message)) self.commit_stats['commit_status_message'] = 'failed to apply config, router response: ' + e.message if start_time is not None: self.commit_stats['last_commit_time'] = datetime.datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S') self.commit_stats['last_commit_duration'] = str(time.time() - start_time)
def __nc_connect(self): if self.debug: self.logger.info("netconf connecting to {}".format(self.target)) if self.target is None or self.user is None: return False try: if self.private_key is not None: pass # handle keys later else: self.nc = netconf_ssh.connect( host=self.target, port=self.__netconf_port, username=self.user, password=self.password, ) # self.nc.open() except Exception as e: self.__errors = "Unknown error occurred" return False if self.debug: self.logger.info("connected to {}".format(self.target)) # set custom timeout for connection # self.nc.timeout = self.timeout return True
def _get_connection(self): """Make SSH connection to the CSR. The external ncclient library is used for creating this connection. This method keeps state of any existing connections and reuses them if already connected. Also CSR1kv's interfaces (except management) are disabled by default when it is booted. So if connecting for the first time, driver will enable all other interfaces and keep that status in the `_intfs_enabled` flag. """ try: if self._csr_conn and self._csr_conn.connected: return self._csr_conn else: self._csr_conn = manager.connect(host=self._csr_host, port=self._csr_ssh_port, username=self._csr_user, password=self._csr_password, device_params={'name': "csr"}, timeout=self._timeout) if not self._intfs_enabled: self._intfs_enabled = self._enable_intfs(self._csr_conn) return self._csr_conn except Exception as e: conn_params = {'host': self._csr_host, 'port': self._csr_ssh_port, 'user': self._csr_user, 'timeout': self._timeout, 'reason': e.message} raise cfg_exc.CSR1kvConnectionException(**conn_params)
def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, hostkey_verify=False) print 'opening private configuration' lock = conn.open_configuration() # build configuration element config = new_ele('system') sub_ele(config, 'host-name').text = 'bar' send_config = conn.load_configuration(config=config) print send_config.tostring check_config = conn.validate() print check_config.tostring compare_config = conn.compare_configuration() print compare_config.tostring print 'commit confirmed 300' commit_config = conn.commit(confirmed=True, timeout='300') print commit_config.tostring print 'sleeping for 5 sec...' time.sleep(5) print 'closing configuration' close_config = conn.close_configuration() print close_config.tostring
def connect(host, user, password): conn = manager.connect(host=host, username=user, password=password, timeout=10, hostkey_verify=False) conn.lock() # configuration as a text string host_name = """ system { host-name foo-bar; } """ send_config = conn.edit_config(format='text', config=host_name) 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() # configuration as a string load_config_result = conn.load_configuration(action='set', config='set system host-name foo') logging.info(load_config_result) # configuration as a list location = [] location.append('set system location building "Main Campus, C"') location.append('set system location floor 15') location.append('set system location rack 1117') load_config_result = conn.load_configuration(action='set', config=location) logging.info(load_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 _do_connect(self, timeout): try: self._session = manager.connect(host=self._ip, port=self._port, username=self._username, password=self._password, allow_agent=False, look_for_keys=False, hostkey_verify=False, timeout=timeout) except SSHError as e: # Log and rethrow exception so any errBack is called log.exception('SSHError-during-connect', e=e) raise e except Exception as e: # Log and rethrow exception so any errBack is called log.exception('Connect-failed: {}', e=e) raise e # If debug logging is enabled, decrease the level, DEBUG is a significant # performance hit during response XML decode if log.isEnabledFor('DEBUG'): log.setLevel('INFO') # TODO: ncclient also supports RaiseMode:NONE to limit exceptions. To set use: # # self._session.raise_mode = RaiseMode:NONE # # and the when you get a response back, you can check 'response.ok' to see if it is 'True' # if it is not, you can enumerate the 'response.errors' list for more information return self._session
def open(self): allow_agent = self._password is None and self._ssh_private_key_file is None try: self._conn = netconf_ssh.connect(host=self._hostname, port=self._port, username=self._username, password=self._password, timeout=self._timeout, hostkey_verify=False, key_filename=self._ssh_private_key_file, allow_agent=allow_agent, ssh_config=self._ssh_config, device_params={'name': 'iosxr'}) except NcAuthErr as auth_err: raise iosxr_eznc.exception.ConnectAuthError(dev=self) except socket.gaierror as host_err: raise iosxr_eznc.exception.ConnectError(dev=self, msg='Unknown host.') except Exception as err: raise iosxr_eznc.exception.ConnectError(dev=self, msg=err.message) # original error # looking good self.connected = True self.rpc = RPC(self) self._namespaces = Namespaces(self) if self._preload_schemas: while not self._namespaces.fetched(): pass # wait here till done retrieving delta namespaces self._facts = Facts(self, fetch=self._gather_facts) # fetch facts return self
def connect(self, session_config): if (session_config.transportMode == _SessionTransportMode.SSH): self._nc_manager = manager.connect( host=session_config.hostname, port=session_config.port, username=session_config.username, password=session_config.password, look_for_keys=False, allow_agent=False, hostkey_verify=False) elif (session_config.transportMode == _SessionTransportMode.TCP): self._nc_manager = manager.connect( host=session_config.hostname, port=session_config.port, transport='tcp') return self._nc_manager
def send_netconf(self, new_config, default_operation="merge", operation=None): try: with manager.connect(host=self.management_ip, port=22, username=self.user_creds['username'], password=self.user_creds['password'], unknown_host_cb=lambda x, y: True) as m: add_config = etree.Element( "config", nsmap={"xc": "urn:ietf:params:xml:ns:netconf:base:1.0"}) config = etree.SubElement(add_config, "configuration") config_group = etree.SubElement(config, "groups") if operation: contrail_group = etree.SubElement(config_group, "name", operation=operation) else: contrail_group = etree.SubElement(config_group, "name") contrail_group.text = "__contrail__" if isinstance(new_config, list): for nc in new_config: config_group.append(nc) else: config_group.append(new_config) if operation != 'delete': apply_groups = etree.SubElement(config, "apply-groups") apply_groups.text = "__contrail__" m.edit_config( target='candidate', config=etree.tostring(add_config), test_option='test-then-set', default_operation=default_operation) m.commit() except Exception as e: if self._logger: self._logger.error("Router %s: %s" % (self.management_ip, e.message))
def __enter__(self): # Initiate a connection to the device self.manager = manager.connect(host=self.host, username=self.username, password=self.password, hostkey_verify=False, timeout=CONNECT_TIMEOUT) return self
def run(ip, username, password, port): """ Purpose: To open an NCClient manager session to the device, and run the appropriate function against the device. Parameters: ip - String of the IP of the device, to open the connection, and for logging purposes. username - The string username used to connect to the device. password - The string password used to connect to the device. """ output = '' try: #print "{0}: Establishing connection...".format(ip) connection = manager.connect(host=ip, port=port, username=username, password=password, timeout=15, device_params={'name':'junos'}, hostkey_verify=False) connection.timeout = 300 except errors.SSHError: output = '*' * 45 + '\n\nUnable to connect to device: %s on port: %s\n' % (ip, port) print output except errors.AuthenticationError: output = '*' * 45 + '\n\nBad username or password for device: %s\n' % ip print output else: return connection
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) result_xml = conn.get_configuration(format='xml') logging.info("xpath starts-with") ge_configs = result_xml.xpath('configuration/interfaces/interface/name[starts-with(text(), "ge-")]') for i in ge_configs: logging.info("%s %s", i.tag, i.text) logging.info("xpath re:match") ge_configs = result_xml.xpath('configuration/interfaces/interface/name[re:match(text(), "ge")]') for i in ge_configs: logging.info("%s %s", i.tag, i.text) logging.info("xpath contains") ge_configs = result_xml.xpath('configuration/interfaces/interface/name[contains(text(), "ge-")]') for i in ge_configs: logging.info("%s %s", i.tag, i.text) logging.info("xpath match on text") ge_configs = result_xml.xpath('configuration/interfaces/interface/name[text()="ge-0/0/0"]') for i in ge_configs: logging.info("%s %s", i.tag, i.text) logging.info("xpath match on text - alternative (wildcards not permitted)") ge_configs = result_xml.xpath('configuration/interfaces/interface[name="ge-0/0/0"]') for i in ge_configs: logging.info("%s %s", i.xpath('name')[0].tag, i.xpath('name')[0].text)
def connect(host, port, user, password): with manager.connect( host=host, port=port, username=user, password=password ) as m: for c in m.server_capabilities: print c
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() # configuration as a text string host_name = """ system { host-name foo-bar; } """ edit_config_result = conn.edit_config(format='text', config=host_name) 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, user, password): conn = manager.connect(host=host, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) conn.lock() # configuration as a string send_config = conn.load_configuration(action='set', config='set system host-name foo') # configuration as a list location = [] location.append('set system location building "Main Campus, C"') location.append('set system location floor 15') location.append('set system location rack 1117') send_config = conn.load_configuration(action='set', config=location) 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()
from ncclient import manager import json from pprint import pprint import xmltodict import xml.dom.minidom netconf_manager = manager.connect(host='ios-xe-mgmt-latest.cisco.com', port=10000, username='******', password='******', hostkey_verify=False, allow_agent=False, look_for_keys=False) running_config = netconf_manager.get_config('running') # pprint(xml.dom.minidom.parseString(str(running_config)).toprettyxml()) responsejson = xmltodict.parse(str(running_config)) pprint(responsejson['rpc-reply']['data']['native']['interface']) netconf_manager.close_session()
from ncclient import manager import xml.dom.minidom # IOS XE Settings ios_xe_host = "192.168.255.127" ios_xe_port = 830 ios_xe_username = "******" ios_xe_password = "******" m = manager.connect(host=ios_xe_host, port=ios_xe_port, username=ios_xe_username, password=ios_xe_password, hostkey_verify=False, look_for_keys=False) netconf_filter = """ <filter> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <ip><access-list></access-list></ip> </native> </filter>""" netconf_reply = m.get_config("running", filter=netconf_filter) print(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml()) m.close_session()
from ncclient import manager import xmltodict from pprint import pprint m = manager.connect( host = "10.0.15.177", port = 830, username = "******", password = "******", hostkey_verify = False ) def getcapabilities(): print("#Supported Capabilities (YANG modles): ") for capability in m.server_capabilities: print(capability) # getcapabilities() def get_running_cfg(): netconf_filter = """ <filter> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native" /> </filter> """ netconf_reply = m.get_config(source="running", filter=netconf_filter) pprint(xmltodict.parse(str(netconf_reply)), indent=2) # get_running_cfg()
from ncclient import manager import xmltodict from xml.dom import minidom # import credentials from credentials import iosxe # credentials from external file iosxe_manager = manager.connect( host=iosxe["address"], port=iosxe["netconf_port"], username=iosxe["username"], password=iosxe["password"], hostkey_verify=False, ) print(iosxe_manager.connected) # create filter for interfaces filter_interfaces = """ <filter> <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces"> <interface> </interface> </interfaces> </filter> """ # print response ok iosxe_interfaces = iosxe_manager.get_config("running", filter_interfaces)
<nc:edit-config xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"> <target> <running/> </target> <commands> <command>interface ethernet %s</command> <command>description %s</command> <command>switchport access vlan %s</command> </commands> </nc:edit-config> """ % (interface, description, vlan) return (interface_rpc) eos = manager.connect(host="10.83.28.203", port="830", timeout=30, username="******", password="******", hostkey_verify=False) rpc = vlan_rpc(vlan_id, vlan_name) rpcreply = eos.dispatch(to_ele(rpc)) print(rpcreply) rpc = interface_rpc(interface, interface_description, vlan_id) rpcreply = eos.dispatch(to_ele(rpc)) print(rpcreply) eos.close_session()
# Apache License 2.0 # from webexteamsbot import TeamsBot import json from ncclient import manager import xmltodict # Retrieve required details from environment variables bot_email = "*****@*****.**" bot_token = "" bot_url = "" #try with ngrok.io bot_app_name = "" m = manager.connect(host="", port=830, username="", password="", hostkey_verify=False) # Create a Bot Object bot = TeamsBot( bot_app_name, teams_bot_token=bot_token, teams_bot_url=bot_url, teams_bot_email=bot_email, ) # The bot returns the hostname and IOS version of the device def getinfo(incoming_msg): netconf_reply = m.get_config(source='running')
def _connect(self): if not HAS_NCCLIENT: raise AnsibleError( 'ncclient is required to use the netconf connection type.\n' 'Please run pip install ncclient') self.queue_message('log', 'ssh connection done, starting ncclient') allow_agent = True if self._play_context.password is not None: allow_agent = False setattr(self._play_context, 'allow_agent', allow_agent) self.key_filename = self._play_context.private_key_file or self.get_option( 'private_key_file') if self.key_filename: self.key_filename = str(os.path.expanduser(self.key_filename)) if self._network_os == 'default': for cls in netconf_loader.all(class_only=True): network_os = cls.guess_network_os(self) if network_os: self.queue_message('log', 'discovered network_os %s' % network_os) self._network_os = network_os device_params = { 'name': NETWORK_OS_DEVICE_PARAM_MAP.get(self._network_os) or self._network_os } ssh_config = self.get_option('netconf_ssh_config') if ssh_config in BOOLEANS_TRUE: ssh_config = True elif ssh_config in BOOLEANS_FALSE: ssh_config = None try: port = self._play_context.port or 830 self.queue_message( 'vvv', "ESTABLISH NETCONF SSH CONNECTION FOR USER: %s on PORT %s TO %s" % (self._play_context.remote_user, port, self._play_context.remote_addr)) self._manager = manager.connect( host=self._play_context.remote_addr, port=port, username=self._play_context.remote_user, password=self._play_context.password, key_filename=self.key_filename, hostkey_verify=self.get_option('host_key_checking'), look_for_keys=self.get_option('look_for_keys'), device_params=device_params, allow_agent=self._play_context.allow_agent, timeout=self._play_context.timeout, ssh_config=ssh_config) except SSHUnknownHostError as exc: raise AnsibleConnectionFailure(to_native(exc)) except ImportError as exc: raise AnsibleError( "connection=netconf is not supported on {0}".format( self._network_os)) if not self._manager.connected: return 1, b'', b'not connected' self.queue_message('log', 'ncclient manager object created successfully') self._connected = True super(Connection, self)._connect() return 0, to_bytes(self._manager.session_id, errors='surrogate_or_strict'), b''
###Redistribute BGP on EIGRP and vice-versa from ncclient import manager from jinja2 import Template m = manager.connect(host='10.10.0.20', port=830, username='******', password='******', hostkey_verify='False', look_for_keys='False') # Render our Jinja template eigrp_template = Template(open('eigrp.xml').read()) eigrp_rendered = eigrp_template.render( AS_eigrp='200', AS_bgp='64512', VRF_NAME_2='TWO', BW='1500', Delay='100', RELIABILITY='255', LOAD='1', MTU='1500', NET_ADD='10.255.20.0', WILD_CARD_MASK='0.0.0.3', ) # Execute the edit-config RPC result = m.edit_config(target='running', config=eigrp_rendered) print(result)
from ncclient import manager import xml.dom.minidom eos = manager.connect(host="10.81.108.236", port="22", timeout=30, username="******", password="******", hostkey_verify=False) ################################################################################### # # # This example will assign and ingress and egress ACL to an L3 interface # # # # interface Ethernet2/1 # # no switchport # # ip access-group IPv4_ACL_NETCONF_INGRESS in # # ip access-group IPv4_ACL_NETCONF_EGRESS out # # # # # # ################################################################################### conf = ''' <config> <acl xmlns="http://arista.com/yang/openconfig/acl"> <interfaces> <interface> <id>Ethernet2/1</id> <config> <id>Ethernet2/1</id> </config> <interface-ref>
from ncclient import manager from getpass import getpass #from modules.utilities.settings import get_config host = "100.127.0.6" user = "******" password = getpass() with manager.connect(host=host, port=22, username=user, password=password, hostkey_verify=False, device_params={'name': 'iosxe'}) as m: c = m.get_config(source='running').data_xml with open("%s.xml" % host, 'w') as f: f.write(c)
def connect(node): try: device_connection = manager.connect(host = node, port = '2222', username = '******', password = '******', hostkey_verify = False, device_params={'name':'nexus'}) return device_connection except: print("Unable to connect " + node)
def _connect(self): super(Connection, self)._connect() display.display('ssh connection done, starting ncclient', log_only=True) allow_agent = True if self._play_context.password is not None: allow_agent = False setattr(self._play_context, 'allow_agent', allow_agent) key_filename = None if self._play_context.private_key_file: key_filename = os.path.expanduser( self._play_context.private_key_file) if self._network_os == 'default': for cls in netconf_loader.all(class_only=True): network_os = cls.guess_network_os(self) if network_os: display.display('discovered network_os %s' % network_os, log_only=True) self._network_os = network_os device_params = { 'name': NETWORK_OS_DEVICE_PARAM_MAP.get(self._network_os) or self._network_os } ssh_config = os.getenv('ANSIBLE_NETCONF_SSH_CONFIG', False) if ssh_config in BOOLEANS_TRUE: ssh_config = True else: ssh_config = None try: self._manager = manager.connect( host=self._play_context.remote_addr, port=self._play_context.port or 830, username=self._play_context.remote_user, password=self._play_context.password, key_filename=str(key_filename), hostkey_verify=self.get_option('host_key_checking'), look_for_keys=self.get_option('look_for_keys'), device_params=device_params, allow_agent=self._play_context.allow_agent, timeout=self._play_context.timeout, ssh_config=ssh_config) except SSHUnknownHostError as exc: raise AnsibleConnectionFailure(str(exc)) except ImportError as exc: raise AnsibleError( "connection=netconf is not supported on {0}".format( self._network_os)) if not self._manager.connected: return 1, b'', b'not connected' display.display('ncclient manager object created successfully', log_only=True) self._connected = True netconf = netconf_loader.get(self._network_os, self) if netconf: display.display('loaded netconf plugin for network_os %s' % self._network_os, log_only=True) else: netconf = netconf_loader.get("default", self) display.display( 'unable to load netconf plugin for network_os %s, falling back to default plugin' % self._network_os) self._implementation_plugins.append(netconf) return 0, to_bytes(self._manager.session_id, errors='surrogate_or_strict'), b''
from ncclient import manager from pprint import pprint import xmltodict import xml.dom.minidom from router_info import router # import logging # logging.basicConfig(level=logging.DEBUG) netconf_filter = open( "D:/Google Drive/Repositories/CodeSamples/Python/Networking/IOS-XE/netconf-filter.xml" ).read() with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m: for capability in m.server_capabilities: print('*' * 50) print(capability) # get the running config on the filtered out interface print('Connected') interface_netconf = m.get(netconf_filter) print('getting running config') # below, xml is a property of interface_conf # XMLDOM for formatting output to xml xmlDom = xml.dom.minidom.parseString(str(interface_netconf)) print(xmlDom.toprettyxml(indent=" ")) print('*' * 25 + 'Break' + '*' * 50) # XMLTODICT for converting xml output to a python dictionary
def main(): """ Execution begins here. """ # Dictionary containing keyword arguments (kwargs) for connecting # via NETCONF. Because SSH is the underlying transport, there are # several minor options to set up. connect_params = { "host": "sbx-nxos-mgmt.cisco.com", "port": 10000, "username": "******", "password": "******", "hostkey_verify": False, "allow_agent": False, "look_for_keys": False, "device_params": { "name": "nexus" }, } # Unpack the connect_params dict and use them to connect inside # of a "with" context manager. The variable "conn" represents the # NETCONF connection to the device. with manager.connect(**connect_params) as conn: print("NETCONF session connected") # To save time, only capture 3 switchports. Less specific filters # will return more information, but take longer to process/transport. # Note: In this sandbox, it can take ~30 seconds to get all interfaces # and several minutes to get the whole config, so be aware! nc_filter = """ <interfaces xmlns="http://openconfig.net/yang/interfaces"> <interface> <name>eth1/24</name> </interface> <interface> <name>eth1/23</name> </interface> </interfaces> """ # Execute a "get-config" RPC using the filter defined above resp = conn.get_config(source="running", filter=("subtree", nc_filter)) # Uncomment line below to see raw RPC XML reply; great for learning #print(resp.xml) resp_dict = xmltodict.parse(resp.xml) for int in resp_dict['rpc-reply']['data']['interfaces']['interface']: #print(int) status = int['config']['enabled'] if status: print("Status of interface {0} is {1}".format( int['name'], status)) else: print("Status of interface {0} is {1}".format( int['name'], status)) print("NETCONF session disconnected")
sbx_iosxr_ao = { "host": "sbx-iosxr-mgmt.cisco.com", "port": 10000, "username": "******", "password": "******", "hostkey_verify": False, "allow_agent": False, "look_for_keys": False, "device_params": { "name": "iosxr" }, } if __name__ == "__main__": with manager.connect(**sbx_iosxr_ao) as device: nc_filter = """ <interface-configurations xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg"> <interface-configuration> <interface-name>MgmtEth0/0/CPU0/0</interface-name> </interface-configuration> </interface-configurations> """ nc_get_reply = device.get(("subtree", nc_filter)) print(nc_get_reply) nc_filter = """ <config> <interface-configurations xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg"> <interface-configuration>
This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of the material herein must be in accordance with the terms of the License. All rights not expressly granted by the License are reserved. Unless required by applicable law or agreed to separately in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ from ncclient import manager #import sys m = manager.connect(host="198.18.134.11", port="830", username="******", password="******", hostkey_verify=False) print("This remote network device supports the following capabilities:\n") for capability in m.server_capabilities: print(capability.split('?')[0]) m.close_session()
# testing # targetdir = '.' + '/' + args.git_path # if not exists(targetdir): # makedirs(targetdir) # # Connect to the router # def unknown_host_cb(host, fingerprint): return True mgr = manager.connect(host=args.host, port=args.port, username=args.username, password=args.password, timeout=args.timeout, allow_agent=False, look_for_keys=False, hostkey_verify=False, unknown_host_cb=unknown_host_cb) # # Attempt to get the ietf-yang-library if available. # If not, fall back to capabilities. # do_caps = False try: response = mgr.get(('xpath', '/modules-state')).xml lib_data = etree.fromstring(response) lib_tags = lib_data.findall( './/{urn:ietf:params:xml:ns:yang:ietf-yang-library}modules-state')
from ncclient import manager from tabulate import tabulate import xml.dom.minidom,xmltodict,json #N me funciona del todo bien porque me ha sido imposible poder hacerlo funcionar, si conseguia que funcionara con una ruta y varias #redes dentro de esta luego no me funcionaba con varias rutas y varias redes o viceversa username="******" password="******" conexion=manager.connect(host="192.168.1.202",port=830,username=username,password=password,hostkey_verify=False) filter_request=""" <filter> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> <router> <ospf xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ospf"/> </router> </native> </filter> """ netconf_request=conexion.get(filter=filter_request) formatoxml1=xmltodict.parse(netconf_request.xml) filtro=formatoxml1['rpc-reply']['data']['native']['router']['ospf'] print(filtro) try: network=filtro['network'] try: redis=filtro['redistribute']['static']['redist-options'] except: redis=None
from pprint import pprint import xmltodict from ncclient import manager from device_configs.csr_1000_devnet import router with manager.connect(host=router['host'], port=router['port'], username=router['username'], password=router['password'], hostkey_verify=False) as m: containers = m.server_capabilities for container in containers: search = 'interface' if search in str(container): print(container)
from string import Template from ncclient import manager template = Template(''' <filter type="subtree"> <bgp xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <bgpcomm> </bgpcomm> </bgp> </filter> ''') config = template.substitute() # print(config) # print(config) huawei_connect = manager.connect(host='192.168.100.200', port=22, username='******', password='******', hostkey_verify=False, device_params={'name': "huawei"}, allow_agent=False, look_for_keys=False) rpc_obj = None with huawei_connect as m: rpc_obj = m.get_config(source='running', filter=config) print(rpc_obj)
#!/usr/bin/env python from ncclient import manager device = manager.connect(host='vmx', port=830, username='******', password='******', hostkey_verify=False, device_params={}, allow_agent=False, look_for_keys=False) get_filter = """ <configuration> <system> <login> </login> </system> </configuration> """ nc_get_reply = device.get(('subtree', get_filter)) user_list = [] xmlns
#!/usr/bin/env python3 from ncclient import manager from ncclient.operations import RPCError m = manager.connect(host='localhost', port=830, username='******', password='******', hostkey_verify=False, allow_agent=False, look_for_keys=False) try: response = m.copy_config(source='running', target='startup').xml except RPCError as e: response = e.message finally: print(response) m.close_session()
from lxml import etree from ncclient import manager if __name__ == "__main__": with manager.connect(host='192.168.10.80', port=830, username='******', password='******', hostkey_verify=False, device_params={'name': 'csr'}, allow_agent=False, look_for_keys=False) as device: nc_filter = """ <config> <native xmlns="http://cisco.com/ns/yang/ned/ios"> <interface> <Loopback> <name>700</name> <ip> <address> <primary> <address>10.200.20.1</address> <mask>255.255.255.0</mask> </primary> <secondary> <address>9.9.9.9</address> <mask>255.255.255.0</mask> <secondary/> </secondary>
</cli-config-data> </config> """ #pushing config to the routers for i in range(0, 5): #generating the configuration from the template config_str = configuration % (hostname[i], interface, ip[i], mask, networks[i], wildcard, area) #opening the NETCONF connection conn = manager.connect(host=ssh_ip[i], port=22, username="******", password="******", hostkey_verify=False, device_params={'name': 'iosxr'}, allow_agent=False, look_for_keys=True) print("Connected to {} and configuring.".format(routers[i])) #pushing the configuration rpc_sent = conn.edit_config(target="running", config=config_str) print("Configuration done on {}".format(routers[i])) #polling the configuration and printing in a table format table = PrettyTable( ["Router", "Hostname", "Loopback 99 IP", "OSPF networks"]) for i in range(0, 5): print("Fetching data from {}".format(routers[i]))
from ncclient import manager import xml.dom.minidom data = ''' <config> <native xmlns="http://cisco.com/ns/yang/ned/ios"> <hostname>NC-WAS-HERE</hostname> </native> </config> ''' if __name__ == '__main__': parser = ArgumentParser(description='Select options.') # Input parameters parser.add_argument('--host', type=str, required=True, help="The device IP or DN") parser.add_argument('-u', '--username', type=str, default='cisco', help="Go on, guess!") parser.add_argument('-p', '--password', type=str, default='cisco', help="Yep, this one too! ;-)") parser.add_argument('--port', type=int, default=830, help="Specify this if you want a non-default port") args = parser.parse_args() m = manager.connect(host=args.host, port=args.port, username=args.username, password=args.password, device_params={'name':"csr"}) # Pretty print the XML reply xmlDom = xml.dom.minidom.parseString( str( m.edit_config(data, target='running') ) ) print xmlDom.toprettyxml( indent = " " )
# Ask for the Interface Details to Add new_loopback = {} new_loopback["name"] = "Loopback" + raw_input("What loopback number to add? ") new_loopback["desc"] = raw_input("What description to use? ") #new_loopback["type"] = IETF_INTERFACE_TYPES["loopback"] new_loopback["status"] = "true" new_loopback["ip_address"] = raw_input("What IP address? ") new_loopback["mask"] = raw_input("What network mask? ") # Create the NETCONF data payload for this interface netconf_data = netconf_interface_template.format( name = new_loopback["name"], desc = new_loopback["desc"], #type = new_loopback["type"], status = new_loopback["status"], ip_address = new_loopback["ip_address"], mask = new_loopback["mask"] ) with manager.connect( host=IOS_XE_1["host"], port=IOS_XE_1["netconf_port"], username=IOS_XE_1["username"], password=IOS_XE_1["password"], hostkey_verify=False ) as m: netconf_reply = m.edit_config(netconf_data, target = 'running') print netconf_reply
from device_info import csr from ncclient import manager f = open("template.xml") netconf_template = f.read() f.close() netconf_payload = netconf_template.format(ip_address="202.100.100.0/24", next_hop_ip="10.10.10.1") print("Configuration Payload:") print("-" * 30) print(netconf_payload) with manager.connect( host=csr["address"], port=csr["port"], username=csr["username"], password=csr["password"], hostkey_verify=False, ) as m: netconf_reply = m.edit_config(netconf_payload, target="running") print(netconf_reply)
# Added function to remove namspaces def remove_namespaces(xml): for elem in xml.getiterator(): split_tag = elem.tag.split('}') if len(split_tag) > 1: elem.tag = split_tag[1] return xml if __name__ == '__main__': with manager.connect(host='nxosv', port=22, username='******', password='******', hostkey_verify=False, device_params={'name': 'nexus'}, allow_agent=False, look_for_keys=False) as device: get_filter = """ <show> <version> </version> </show> """ nc_get_reply = device.get(('subtree', get_filter)) # Added a no namespace variable nc_get_reply_no_ns = remove_namespaces(nc_get_reply.data_ele) print 'Response as XML String: ' print nc_get_reply.xml
__copyright__ = "Copyright (c) 2016 Cisco Systems, Inc." __license__ = "MIT" from device_info import ios_xe1 from ncclient import manager import xmltodict import xml.dom.minidom from pprint import pprint # NETCONF filter to use netconf_filter = open("filter-ietf-interfaces.xml").read() if __name__ == '__main__': with manager.connect(host=ios_xe1["address"], port=ios_xe1["port"], username=ios_xe1["username"], password=ios_xe1["password"], hostkey_verify=False) as m: # Get Configuration and State Info for Interface interface_netconf = m.get(netconf_filter) # Process the XML and store in useful dictionaries """ xmlDom = xml.dom.minidom.parseString(str(interface_netconf)) print(xmlDom.toprettyxml(indent=" ")) print('*' * 25 + 'Break' + '*' * 50) """ # Converting xml to python option
from ncclient import manager with manager.connect(host="192.168.33.56", port=830, username="******", hostkey_verify=False, password="******", device_params={'name': 'csr'}) as m: c = m.get_config(source='running').data_xml print(c)