• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python manager.connect函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: reconnect

    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
开发者ID:gaberger,项目名称:pynos,代码行数:30,代码来源:device.py


示例2: demo

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)
开发者ID:alvinooo,项目名称:ncclient,代码行数:9,代码来源:nc09.py


示例3: connect

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()
开发者ID:davidhankins,项目名称:ncclient,代码行数:30,代码来源:edit-config-text-std.py


示例4: _get_connection

    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)
开发者ID:HybridCloud-dew,项目名称:hws,代码行数:28,代码来源:csr1kv_routing_driver.py


示例5: connect

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()
开发者ID:MrRagga-,项目名称:ncclient,代码行数:28,代码来源:edit-config-text-std.py


示例6: _do_connect

    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
开发者ID:gcgirish-radisys,项目名称:voltha,代码行数:35,代码来源:adtran_netconf.py


示例7: connect

 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
开发者ID:mirceaulinic,项目名称:ydk-py,代码行数:16,代码来源:_provider_plugin.py


示例8: __enter__

    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
开发者ID:21d5,项目名称:netbox,代码行数:7,代码来源:rpc.py


示例9: connect

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()
开发者ID:GIC-de,项目名称:ncclient,代码行数:31,代码来源:edit-config-jnpr-set.py


示例10: _connect

 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]
开发者ID:liaowenqi1,项目名称:neutron,代码行数:25,代码来源:mech_huawei_switch.py


示例11: demo

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()
开发者ID:GIC-de,项目名称:ncclient,代码行数:7,代码来源:nc08.py


示例12: push_configuration

 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
开发者ID:MounikaPandiri,项目名称:mybackup,代码行数:25,代码来源:generic_driver_backup.py


示例13: get_config

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)
开发者ID:javaos74,项目名称:networkprogram,代码行数:7,代码来源:netconf_ex.py


示例14: connect

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()
开发者ID:GIC-de,项目名称:ncclient,代码行数:25,代码来源:delete-config-jnpr.py


示例15: config_via_netconf

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"
开发者ID:aswanikumar90,项目名称:contrail-test,代码行数:28,代码来源:fabfile.py


示例16: connect

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
开发者ID:Kent1,项目名称:ncclient,代码行数:7,代码来源:nc01.py


示例17: run

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
开发者ID:tylerjordan,项目名称:jscan,代码行数:26,代码来源:utility.py


示例18: connect

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
开发者ID:valarmathip,项目名称:Terafast,代码行数:35,代码来源:test.py


示例19: send_netconf

 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))
开发者ID:naveen-n,项目名称:contrail-controller,代码行数:35,代码来源:physical_router_config.py


示例20: connect

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()
开发者ID:davidhankins,项目名称:ncclient,代码行数:27,代码来源:delete-config-jnpr.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python manager.make_device_handler函数代码示例发布时间:2022-05-27
下一篇:
Python i18n._LI函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap