Python ncclient.manager.connect() Examples

The following are 30 code examples of ncclient.manager.connect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ncclient.manager , or try the search function .
Example #1
Source File: device_api_test.py    From sbx_iosxe with MIT License 7 votes vote down vote up
def test_ssh(self):
        """ Verify device reachable through SSH """

        for dev in self.parent.parameters["dev"]:
            log.info(
                banner("Testing SSH Access to {}".format(dev.name))
            )

            # Retry loop, number of tries controlled by variable.
            for _ in range(MAX_RETRIES):
                try:
                    dev.connect(alias="admin", via="admin", learn_hostname=True)
                except Exception as e:
                    log.error("Attempt number {} to connect with SSH failed.".format(_ + 1))
                    log.error(e)
                else:
                    break
            # If unable to connect, fail test
            else:
                self.failed(
                    "Failed to establish SSH connection to '{}'".format(
                        dev.name
                    )
                ) 
Example #2
Source File: get_hostname.py    From sbx_iosxe with MIT License 6 votes vote down vote up
def main():
    """
    Main method that retrieves the hostname from config via NETCONF.
    """
    with manager.connect(host=HOST, port=PORT, username=USER,
                         password=PASS, hostkey_verify=False,
                         device_params={'name': 'default'},
                         allow_agent=False, look_for_keys=False) as m:

        # XML filter to issue with the get operation
        # IOS-XE pre-16.2     YANG model called urn:ios
        # IOS-XE 16.2 - 16.4  YANG model called http://cisco.com/ns/yang/ned/ios
        # IOS-XE 16.5+        YANG model called http://cisco.com/ns/yang/Cisco-IOS-XE-native
        hostname_filter = '''
                          <filter>
                              <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
                                  <hostname></hostname>
                              </native>
                          </filter>
                          '''
        result = m.get_config('running', hostname_filter)
        xml_doc = xml.dom.minidom.parseString(result.xml)
        hostname = xml_doc.getElementsByTagName("hostname")
        print(hostname[0].firstChild.nodeValue) 
Example #3
Source File: ce.py    From CloudEngine-Ansible with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, module):

        self._module = module

        if not HAS_NCCLIENT:
            self._module.fail_json(msg='Error: The ncclient library is required.')

        try:
            self.mc = manager.connect(host=module.params["host"], port=module.params["port"],
                                      username=module.params["username"],
                                      password=module.params["password"],
                                      unknown_host_cb=ce_unknown_host_cb,
                                      allow_agent=False,
                                      look_for_keys=False,
                                      hostkey_verify=False,
                                      device_params={'name': 'huawei'},
                                      timeout=30)
        except AuthenticationError:
            self._module.fail_json(msg='Error: Authentication failed while connecting to device.')
        except Exception:
            err = get_exception()
            self._module.fail_json(msg='Error: %s' % str(err).replace("\r\n", ""))
            raise 
Example #4
Source File: 08_cmd-add-mpls-lsp-full.py    From netconf-yang-training with Apache License 2.0 6 votes vote down vote up
def demo(host=nc_host, port=nc_port, user=nc_user, password=nc_password):
    with manager.connect(host=host, port=port, username=user, password=password,
                         hostkey_verify=False, look_for_keys=False, allow_agent=False) as mgr:
        # Persist-id for the confirmed commit
        pid = "IQ,d4668"
        assert ':candidate' in mgr.server_capabilities
        assert ':validate'  in mgr.server_capabilities
        with mgr.locked(target='candidate'):
            mgr.discard_changes()
            print("Editing config")
            mgr.edit_config(config=CONFIG, target="candidate")
            mgr.validate()
            mgr.commit(confirmed=True, timeout="10", persist=pid)
            print ("Running the tests (5s)")
            time.sleep(5)
            # Could cancel the commit during the timeout
            # res = mgr.cancel_commit(persist_id=pid)
            print("Committing")
            res = mgr.commit(confirmed=True)
            print(res) 
Example #5
Source File: get_serial.py    From sbx_nxos with MIT License 6 votes vote down vote up
def main():
    """
    Main method that prints netconf capabilities of remote device.
    """
    serial_number = """
    <System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
    <serial/>
    </System>
    """

    
    
    for device in DEVICES:
        with manager.connect(host=device, port=PORT, username=USER,
                             password=PASS, hostkey_verify=False,
                             device_params={'name': 'nexus'},
                             look_for_keys=False, allow_agent=False) as m:

            # Collect the NETCONF response
            netconf_response = m.get(('subtree', serial_number))
            # Parse the XML and print the data
            xml_data = netconf_response.data_ele
            serial =  xml_data.find(".//{http://cisco.com/ns/yang/cisco-nx-os-device}serial").text

            print("The serial number for {} {} is {}".format(DEVICE_NAMES[device], device, serial)) 
Example #6
Source File: 08_cmd-add-mpls-lsp-full.py    From netconf-yang-training with Apache License 2.0 6 votes vote down vote up
def demo(host=nc_host, port=nc_port, user=nc_user, password=nc_password):
    with manager.connect(host=host, port=port, username=user, password=password, hostkey_verify=False, look_for_keys=False, allow_agent=False) as m:
        # Persist-id for the confirmed commit
        pid = "IQ,d4668"
        assert(":candidate" in m.server_capabilities)
        assert(":validate"  in m.server_capabilities)
        with m.locked(target='candidate'):
            m.discard_changes()
            m.edit_config(config=config_snippet, target="candidate")
            m.validate()
            m.commit(confirmed=True, timeout="10", persist=pid)
            print "Running the tests"
            time.sleep(5)
            # Could cancel the commit during the timeout
            # res = m.cancel_commit(persist_id=pid)
            print "Committing"
            res = m.commit(confirmed=True)
            print res 
Example #7
Source File: runner.py    From yang-explorer with Apache License 2.0 6 votes vote down vote up
def connect(self):
        """ Establish netconf session """

        if self.handle is not None:
            return True

        try:
            # timeout is configurable as environment variable
            timeout = int(os.getenv("NCCLIENT_TIMEOUT", 90))
            self.handle = manager.connect(host=self.host,
                                          port=self.port,
                                          username=self.username,
                                          password=self.password,
                                          device_params=self.params,
                                          unknown_host_cb=self._unknown_host_cb,
                                          look_for_keys=False,
                                          timeout=timeout)
        except:
            logging.exception("Failed to create netconf session:")
            self.handle = None
            return False

        logging.debug("Connected: %s" % self.__str__())
        return True 
Example #8
Source File: runner.py    From yang-explorer with Apache License 2.0 6 votes vote down vote up
def get_capability(self):
        """ Returns device capabilities """

        logging.debug('get_capability ..')
        reply = ET.Element('reply')
        if not self.connect():
            reply.text = 'NetConf Session could not be established {%s}' % str(self)
            return reply
        self.disconnect()
        if self.handle.server_capabilities:
            caps = sorted(self.handle.server_capabilities)
            reply.text = '\n'.join((c for c in caps if c.startswith('urn:ietf:params:netconf:')))
            reply.text += '\n\n'
            reply.text += '\n'.join((c for c in caps if not c.startswith('urn:ietf:params:netconf:')))
            logging.info('Received device capabilities ..')
        return reply 
Example #9
Source File: get_hostname.py    From netconf-examples with Apache License 2.0 5 votes vote down vote up
def main():
    """Main method that retrieves the hostname from config via NETCONF (NXOS)."""
    with manager.connect(host=HOST, port=PORT, username=USER, password=PASS,
                         hostkey_verify=False, device_params={'name': 'nexus'},
                         allow_agent=False, look_for_keys=False) as m:

        # XML filter to issue with the get operation
        hostname_filter = '''
                          <show xmlns="http://www.cisco.com/nxos:1.0">
                              <hostname>
                              </hostname>
                          </show>
                          '''

        result = m.get(('subtree', hostname_filter))
        # Pass the XML result as a string to the parseString function
        xml_doc = xml.dom.minidom.parseString(result.xml)
        hostname = xml_doc.getElementsByTagName("mod:hostname")
        print(hostname[0].firstChild.nodeValue) 
Example #10
Source File: add_loopbacks.py    From sbx_nxos with MIT License 5 votes vote down vote up
def main():
    """
    Main method that adds loopback interface 99 to both the spine switches.
    """

    loopback_add = """
    <config>
    <System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
    <intf-items>
    <lb-items>
    <LbRtdIf-list>
    <id>lo99</id>
    <adminSt>up</up>
    <descr>Interface added via NETCONF</descr>
    </LbRtdIf-list>
    </lb-items>
    </intf-items>
    </System>
    </config>"""


    for device in DEVICES:
        with manager.connect(host=device, port=PORT, username=USER,
                             password=PASS, hostkey_verify=False,
                             device_params={'name': 'nexus'},
                             look_for_keys=False, allow_agent=False) as m:
            
            # Add the loopback interface 
            print("\nNow adding Loopback99 device {} {}...\n".format(DEVICE_NAMES[device], device))
            netconf_response = m.edit_config(target='running', config=loopback_add)
            # Parse the XML response
            print(netconf_response) 
Example #11
Source File: add_nxos_bgp_prefixes.py    From sbx_nxos with MIT License 5 votes vote down vote up
def main():
    """
    Main method that collects the BGP router-id from the spine switches using the native model
    """
    add_prefix = """ <config>
<System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
    <bgp-items>
        <inst-items>
            <dom-items>
                <Dom-list>
                    <name>default</name>
                    <af-items>
                        <DomAf-list>
                            <type>ipv4-ucast</type>
                            <prefix-items>
                                <AdvPrefix-list>
                                    <addr>{}</addr>
                                </AdvPrefix-list>
                            </prefix-items>
                        </DomAf-list>
                    </af-items>
                </Dom-list>
            </dom-items>
        </inst-items>
    </bgp-items>
</System>
</config>"""
      

    for device in DEVICES:
        with manager.connect(host=device, port=PORT, username=USER,
                             password=PASS, hostkey_verify=False,
                             device_params={'name': 'nexus'},
                             look_for_keys=False, allow_agent=False) as m:
            
            # Add the prefix to BGP
            print("\nNow adding prefix {} to device {} {}..\n".format(PREFIX[device], DEVICE_NAMES[device], device))
            new_prefix = add_prefix.format(PREFIX[device])
            netconf_response = m.edit_config(target='running', config=new_prefix)
            # Parse the XML response
            print(netconf_response) 
Example #12
Source File: junos_netconf_3.py    From Mastering-Python-Networking with MIT License 5 votes vote down vote up
def connect(host, port, user, password):
    connection = manager.connect(host=host, port=port, username=user,
            password=password, timeout=10, device_params={'name':'junos'},
            hostkey_verify=False)
    return connection

# execute show commands 
Example #13
Source File: junos_netconf_3.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def connect(host, port, user, password):
    connection = manager.connect(host=host, port=port, username=user,
            password=password, timeout=10, device_params={'name':'junos'},
            hostkey_verify=False)
    return connection

# execute show commands 
Example #14
Source File: __init__.py    From fake-switches with Apache License 2.0 5 votes vote down vote up
def create_client(self):
        return manager.connect(
            host="127.0.0.1",
            port=self.conf["ssh"],
            username="root",
            password="root",
            hostkey_verify=False,
            device_params={'name': 'junos'}
        ) 
Example #15
Source File: adtran_netconf.py    From voltha with Apache License 2.0 5 votes vote down vote up
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.warn('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 
Example #16
Source File: get_oc_bgp.py    From sbx_nxos with MIT License 5 votes vote down vote up
def main():
    """
    Main method that collects the ASN from the spine switches using the OpenConfig model
    """
    get_oc_bgp = """
<bgp xmlns="http://openconfig.net/yang/bgp">
    <global>
        <state/>
    </global>
</bgp>
"""   

    for device in DEVICES:
        with manager.connect(host=device, port=PORT, username=USER,
                             password=PASS, hostkey_verify=False,
                             device_params={'name': 'nexus'},
                             look_for_keys=False, allow_agent=False) as m:
            
            # Add the loopback interface 
            netconf_response = m.get(('subtree', get_oc_bgp))
            # Parse the XML response
            xml_data = netconf_response.data_ele
            asn = xml_data.find(".//{http://openconfig.net/yang/bgp}as").text

            router_id = xml_data.find(".//{http://openconfig.net/yang/bgp}router-id").text

            print("ASN number:{}, Router ID: {} for {} {}".format(asn, router_id, DEVICE_NAMES[device], device)) 
Example #17
Source File: get_bgp_asn.py    From sbx_nxos with MIT License 5 votes vote down vote up
def main():
    """
    Main method that collects the ASN from the spine switches using the native model
    """

    asn_filter = """
    <System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
    <bgp-items>
    <inst-items>
    <asn/>
    </inst-items>
    </bgp-items>
    </System>
    """
   

    for device in DEVICES:
        with manager.connect(host=device, port=PORT, username=USER,
                             password=PASS, hostkey_verify=False,
                             device_params={'name': 'nexus'},
                             look_for_keys=False, allow_agent=False) as m:
            
            # Add the loopback interface 
            netconf_response = m.get(('subtree', asn_filter))
            # Parse the XML response
            xml_data = netconf_response.data_ele
            asn = xml_data.find(".//{http://cisco.com/ns/yang/cisco-nx-os-device}asn").text

            print("The ASN number for {} {} is {}".format(DEVICE_NAMES[device], device, asn)) 
Example #18
Source File: get_capabilities.py    From sbx_nxos with MIT License 5 votes vote down vote up
def main():
    """
    Main method that prints netconf capabilities of remote device.
    """
    for device in DEVICES:
        with manager.connect(host=device, port=PORT, username=USER,
                             password=PASS, hostkey_verify=False,
                             device_params={'name': 'nexus'},
                             look_for_keys=False, allow_agent=False) as m:

            # print all NETCONF capabilities
            print('\n***Remote Devices Capabilities for device {} {}***\n'.format(DEVICE_NAMES[device], device))
            for capability in m.server_capabilities:
                print(capability.split('?')[0]) 
Example #19
Source File: create_subinterface.py    From netconf-examples with Apache License 2.0 5 votes vote down vote up
def create_vlan(host, port, user, password, interface, int_id, vlan, ip, mask, template, config):
    """Function to create a subinterface on CSR1000V."""
    intfc = re.compile(r'^(\D+)(\d+)$')
    m = intfc.match(interface + int_id)
    if m is None:
        print("Invalid interface name. Valid example: ", BASE)
        sys.exit()

    # create the XML configuration issued via NETCONF
    create_xml_config(template, config, interface, int_id, vlan, ip, mask)

    # open the NETCONF session
    with manager.connect(host=host, port=port, username=user, password=password,
                         hostkey_verify=False, device_params={'name': 'default'},
                         allow_agent=False, look_for_keys=False) as m:
        with open(config) as f:
            try:
                # issue the edit-config operation with the XML config
                rpc_reply = m.edit_config(target='running', config=f.read())
            except Exception as e:
                print("Encountered the following RPC error!")
                print(e)
                sys.exit()

            # validate the RPC Reply returns "ok"
            if rpc_reply.ok is not True:
                print("Encountered a problem when configuring the device!")
                sys.exit() 
Example #20
Source File: adtran_netconf.py    From voltha with Apache License 2.0 5 votes vote down vote up
def lock(self, source, lock_timeout):
        """
        Lock the configuration system
        :return: (deferred) for RpcReply
        """
        log.info('lock', source=source, timeout=lock_timeout)

        if not self._session or not self._session.connected:
            raise NotImplementedError('TODO: Support auto-connect if needed')

        return threads.deferToThread(self._do_lock, source, lock_timeout) 
Example #21
Source File: get_config_csr1000V.py    From netconf-examples with Apache License 2.0 5 votes vote down vote up
def get_configured_interfaces():
    """Main method that retrieves the interfaces from config via NETCONF."""
    with manager.connect(host=HOST, port=PORT, username=USER, password=PASS,
                         hostkey_verify=False, device_params={'name': 'default'},
                         allow_agent=False, look_for_keys=False) as m:

        with open(FILE) as f:
            return(m.get_config('running', f.read())) 
Example #22
Source File: get_capabilities.py    From netconf-examples with Apache License 2.0 5 votes vote down vote up
def main():
    """Main method that prints NETCONF capabilities of remote device."""
    with manager.connect(host=HOST, port=PORT, username=USER, password=PASS,
                         hostkey_verify=False, device_params={'name': 'nexus'},
                         look_for_keys=False, allow_agent=False) as m:

        # print all NETCONF capabilities
        print('***Here are the Remote Devices Capabilities***')
        for capability in m.server_capabilities:
            print(capability) 
Example #23
Source File: junos_netconf_3.py    From Mastering-Python-Networking-Third-Edition with MIT License 5 votes vote down vote up
def connect(host, port, user, password):
    connection = manager.connect(host=host, port=port, username=user,
            password=password, timeout=10, device_params={'name':'junos'},
            hostkey_verify=False)
    return connection

# execute show commands 
Example #24
Source File: base.py    From netman with Apache License 2.0 5 votes vote down vote up
def _connect(self):
        params = dict(
            host=self.switch_descriptor.hostname,
            username=self.switch_descriptor.username,
            password=self.switch_descriptor.password,
            hostkey_verify=False,
            device_params={'name': 'junos'},
            timeout=self.timeout
        )

        if self.switch_descriptor.port:
            params["port"] = self.switch_descriptor.port

        self.netconf = manager.connect(**params) 
Example #25
Source File: get_capabilities.py    From sbx_iosxe with MIT License 5 votes vote down vote up
def main():
    """
    Main method that prints netconf capabilities of remote device.
    """
    with manager.connect(host=HOST, port=PORT, username=USER,
                         password=PASS, hostkey_verify=False,
                         device_params={'name': 'default'},
                         look_for_keys=False, allow_agent=False) as m:

        # print all NETCONF capabilities
        print('***Here are the Remote Devices Capabilities***')
        for capability in m.server_capabilities:
            print(capability.split('?')[0]) 
Example #26
Source File: adtran_netconf.py    From voltha with Apache License 2.0 5 votes vote down vote up
def unlock(self, source):
        """
        Get the requested data from the server
        :param source: RPC request

        :return: (deferred) for RpcReply
        """
        log.info('unlock', source=source)

        if not self._session or not self._session.connected:
            raise NotImplementedError('TODO: Support auto-connect if needed')

        return threads.deferToThread(self._do_unlock, source) 
Example #27
Source File: device_api_test.py    From sbx_iosxe with MIT License 5 votes vote down vote up
def test_netconf(self):
        """ Verify device reachable through NETCONF """

        for dev in self.parent.parameters["dev"]:
            if "netconf" in dev.connections:
                log.info(
                    banner("Testing NETCONF Access to {}".format(dev.name))
                )
                # Retry loop
                for _ in range(MAX_RETRIES):
                    try:
                        with manager.connect(
                                host = str(dev.connections.netconf.ip),
                                port = str(dev.connections.netconf.port),
                                username = dev.tacacs.username,
                                password = dev.passwords.tacacs,
                                hostkey_verify = False,
                                look_for_keys=False
                        ) as m:
                            log.info("NETCONF Connected is {}".format(m.connected))

                    # If unable to connect, fail test
                    except Exception as e:
                        log.error("Attempt number {} to connect with NETCONF failed.".format(_ + 1))
                        log.error(e)
                    else:
                        break
                # If unable to connect, fail test
                else:
                    self.failed(
                        "Failed to establish NETCONF connection to '{}'".format(
                            dev.name
                        )
                    ) 
Example #28
Source File: get_netconf_running_HPN.py    From HPN-Scripting with MIT License 5 votes vote down vote up
def connect(host, username, password):
    # Set-up NETCONF connection
    with manager.connect(host=host,
                        port=830,
                        username=username,
                        password=password,
                        hostkey_verify=False,
                        allow_agent=False,
                        look_for_keys=False
                        ) as netconf_manager:
            data = netconf_manager.get_config(source='running')
    return data 
Example #29
Source File: junos_netconf_3.py    From Mastering-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def connect(host, port, user, password):
    connection = manager.connect(host=host, port=port, username=user,
            password=password, timeout=10, device_params={'name':'junos'},
            hostkey_verify=False)
    return connection

# execute show commands 
Example #30
Source File: get_capabilities.py    From netconf-examples with Apache License 2.0 5 votes vote down vote up
def main():
    """Main method that prints netconf capabilities of remote device."""
    with manager.connect(host=HOST, port=PORT, username=USER, password=PASS,
                         hostkey_verify=False, device_params={'name': 'default'},
                         look_for_keys=False, allow_agent=False) as m:

        # print all NETCONF capabilities
        print('***Here are the Remote Devices Capabilities***')
        for capability in m.server_capabilities:
            print(capability)