当前位置: 首页>>代码示例>>Python>>正文


Python manager.connect方法代码示例

本文整理汇总了Python中ncclient.manager.connect方法的典型用法代码示例。如果您正苦于以下问题:Python manager.connect方法的具体用法?Python manager.connect怎么用?Python manager.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ncclient.manager的用法示例。


在下文中一共展示了manager.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: connect

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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 
开发者ID:CiscoDevNet,项目名称:yang-explorer,代码行数:26,代码来源:runner.py

示例2: get_capability

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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 
开发者ID:CiscoDevNet,项目名称:yang-explorer,代码行数:18,代码来源:runner.py

示例3: demo

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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 
开发者ID:cmoberg,项目名称:netconf-yang-training,代码行数:20,代码来源:08_cmd-add-mpls-lsp-full.py

示例4: demo

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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) 
开发者ID:cmoberg,项目名称:netconf-yang-training,代码行数:22,代码来源:08_cmd-add-mpls-lsp-full.py

示例5: test_ssh

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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
                    )
                ) 
开发者ID:DevNetSandbox,项目名称:sbx_iosxe,代码行数:26,代码来源:device_api_test.py

示例6: main

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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) 
开发者ID:DevNetSandbox,项目名称:sbx_iosxe,代码行数:26,代码来源:get_hostname.py

示例7: __init__

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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 
开发者ID:HuaweiSwitch,项目名称:CloudEngine-Ansible,代码行数:25,代码来源:ce.py

示例8: main

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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) 
开发者ID:CiscoDevNet,项目名称:netconf-examples,代码行数:21,代码来源:get_hostname.py

示例9: main

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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)) 
开发者ID:DevNetSandbox,项目名称:sbx_nxos,代码行数:27,代码来源:get_serial.py

示例10: connect

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
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 
开发者ID:PacktPublishing,项目名称:Mastering-Python-Networking-Second-Edition,代码行数:9,代码来源:junos_netconf_3.py

示例11: main

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
def main():
    with manager.connect(**CONNECTION_PARAMS) as nc_connection:
        get_config(nc_connection)
        configure_device(
            nc_connection,
            config_data=CONFIG_DATA,
            template_name='loopbacks.j2'
        ) 
开发者ID:dmfigol,项目名称:network-programmability-stream,代码行数:10,代码来源:example.py

示例12: __init__

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
def __init__(self, host, username, password,
                 verbose=False):
        self.host = host
        self.username = username
        self.password = password
        if verbose:
            self.logging()
        # self.connect()
        # self.kafka_connect()
        self.nc_conn = None
        self.producer = None
        self.sub = None 
开发者ID:dmfigol,项目名称:network-programmability-stream,代码行数:14,代码来源:nc_dial_in_subscribe.py

示例13: nc_connect

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
def nc_connect(self):
        self.nc_conn = manager.connect(
            host=self.host,
            username=self.username,
            password=self.password,
            device_params={'name':'csr'},
            hostkey_verify=False,
            allow_agent=False,
            unknown_host_cb=self.unknown_host_cb
        ) 
开发者ID:dmfigol,项目名称:network-programmability-stream,代码行数:12,代码来源:nc_dial_in_subscribe.py

示例14: main

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
def main():
    with manager.connect(**constants.NC_CONN_PARAMS) as m:
        nc_reply = m.get(filter=('xpath', XPATH_FILTER))
        print(utils.prettify_xml(nc_reply.xml)) 
开发者ID:dmfigol,项目名称:network-programmability-stream,代码行数:6,代码来源:test_xpath.py

示例15: main

# 需要导入模块: from ncclient import manager [as 别名]
# 或者: from ncclient.manager import connect [as 别名]
def main():
    """Test code that is testing NETCONF."""
    conn = manager.connect(
        host="srx2.lasthop.io",
        username="pyclass",
        password=getpass(),
        device_params={"name": "junos"},
        hostkey_verify=False,
        allow_agent=False,
        look_for_keys=False,
        port=830,
        timeout=60,
    )

    ipdb.set_trace()
    rpc = new_ele("get-software-information")
    nc_out = conn.rpc(rpc)

    # It is an XML like thing
    print(nc_out.tostring.decode())
    print(nc_out.find(".//product-name"))
    print(nc_out.find(".//product-name").text)
    print(nc_out.find(".//product-model").text)

    config = conn.get_config(source="running")
    config_xml = config.data_xml
    print(config_xml) 
开发者ID:ktbyers,项目名称:pyplus_course,代码行数:29,代码来源:ncclient3.py


注:本文中的ncclient.manager.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。