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


Python Config.load方法代码示例

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


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

示例1: deployConfig

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
def deployConfig(my_device_list_dict, my_username, my_password, my_config_template_file):
	my_hostname=""
	try:
		my_hostname=my_device_list_dict["mgmt_ip"]
		printProgress("INFO",my_hostname,"Connecting to device through netconf.")
		dev=Device(my_hostname,user=my_username,password=my_password)
		dev.open()
		dev.timeout=3*60
		cu = Config(dev)
		printProgress("INFO",my_hostname,"Going to load template the config now.")
		
		# Determine if template file is in "set" or "bracketed" format
		if isSet(my_config_template_file):
			rsp=cu.load(template_path=my_config_template_file,format='set',template_vars=my_device_list_dict)
		else:
			rsp=cu.load(template_path=my_config_template_file,template_vars=my_device_list_dict)
		
		printProgress("INFO",my_hostname,"Performing diff between active and candidate config.")
		cu.pdiff()
		printProgress("INFO",my_hostname,"Performing commit check")
		if cu.commit_check():
			printProgress("INFO",my_hostname,"commit check was successfull.")
			printProgress("INFO",my_hostname,"performing commit now.")
			commit_status=cu.commit()
			printProgress("INFO",my_hostname,"disconnecting from device.")
			dev.close()
			return commit_status
		else:
			return False
	except Exception,err:
		printProgress("ERROR",my_hostname,"Encountered exception while deploying config")
		printProgress("ERROR",my_hostname,str(err))
		return False
开发者ID:tylerjordan,项目名称:jload,代码行数:35,代码来源:jload.py

示例2: edit_config

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
    def edit_config(self,dev,ip):
        conf='set policy-options prefix-list blacklisted-ips'
        _conf=''
        #print p,dev
        ips=ip.split()
        for i in ips:
            print "ip=",i
            if IPAddress(i) in IPNetwork("116.197.188.0/23") or IPAddress(i) in IPNetwork("116.197.190.0/23") or IPAddress(i) in IPNetwork("193.110.49.0/23") or IPAddress(i) in IPNetwork("193.110.55.0/23") or IPAddress(i) in IPNetwork("66.129.239.0/23") or IPAddress(i) in IPNetwork("66.129.241.0/23"):

                print "Internal IP"
                continue
            _conf=_conf+conf+' '+i+'\n'
            print "conf", _conf
        try:
            cu=Config(dev)
            #print '1'
            cu.load(_conf,format='set')
            #fp.write(str(datetime.now())+"the conf has been added to "+p[0]+" \n"+_conf+" \n")
            print dev.facts['hostname']
            cu.pdiff()
            cu.commit(confirm=3)
            print "Waiting for 2 mins before final commit..."
            cu.commit()
            #fp.write(str(datetime.now())+" the commit has been done "+" \n")
            print "the config has been committed for",dev.facts['hostname']
        except Exception as e:
            print "commit failed:",e
开发者ID:ssupratik,项目名称:cns-dashboard,代码行数:29,代码来源:models.py

示例3: test_load_console

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
    def test_load_console(self, mock_read_until, mock_select, mock_write):
        mock_select.return_value = ([self.dev._tty._rx], [], [])
        xml = """<policy-options>
                  <policy-statement>
                    <name>F5-in</name>
                    <term>
                        <name>testing</name>
                        <then>
                            <accept/>
                        </then>
                    </term>
                    <from>
                        <protocol>mpls</protocol>
                    </from>
                </policy-statement>
                </policy-options>"""

        mock_read_until.return_value = six.b("""
        <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/15.2I0/junos">
            <load-configuration-results>
            <ok/>
            </load-configuration-results>
            </rpc-reply>
            ]]>]]>""")
        cu = Config(self.dev)
        cu.load(xml, format='xml')
        cu.commit()
开发者ID:djadhav76,项目名称:py-junos-eznc,代码行数:29,代码来源:test_console.py

示例4: _normal_device

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
def _normal_device(dev):

    x=loadyaml(site.getsitepackages()[1]+'/jnpr/junos/op/phyport.yml')
    table=x['PhyPortTable'](dev)
    table.get()
    ke=table.keys()
    cu=Config(dev)
    print cu
    for i in ke:
        sw = dev.rpc.get_config(filter_xml=etree.XML('<configuration><interfaces><interface><name>'+i+'</name></interface></interfaces></configuration>'))
        s=etree.tostring(sw)
        #print s
        e = ET.XML(s)
        x=etree_to_dict(e)
        #print x

        if(x['configuration']==''):
            print 'Unused port '+i+ ' disabled'
            set_cmd='set interfaces '+i+' disable description "unused port"'
            cu.load(set_cmd, format='set')
        else:
            try:
                if(x['configuration']['interfaces']['interface']['unit']['family']['inet']==''):
                    #print 'Unused port '+i+ ' disabled'
                    set_cmd='set interfaces '+i+' disable description "unused port"'
                    cu.load(set_cmd, format='set')
            except:
                pass
    cu.pdiff()
    cu.commit(confirm=1)
    print "the config has been committed"
开发者ID:ssupratik,项目名称:cns-dashboard,代码行数:33,代码来源:models.py

示例5: create_port

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
 def create_port(self, port_name, port_description):
     """Configures port_name as an access port with port_description configured on IFD
     """
     port_vars={}
     port_vars['port_name'] = port_name
     port_vars['port_description'] = port_description
     cu = Config(self.connection)
     cu.load(template_path='service-templates/junos/ex/dot1ad-port.conf', template_vars=port_vars, merge=True)  
开发者ID:dfex,项目名称:lattice,代码行数:10,代码来源:junosconnect.py

示例6: JuniperObject

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
class JuniperObject(object):
    def __init__(self, jnp_dev):
        self.conn = jnp_dev
        self.config = None
        self.ports = {}
        self.routes = {}

    def __get_ports(self):
        self.ports = EthPortTable(self.conn)
        self.ports.get()

    def __get_routes(self):
        self.routes = RouteTable(self.conn)
        self.routes.get()
   
    def config_mode(self):
        self.config = Config(self.conn)
        self.config.lock()

    def send_command(self, command, cmd_format, cmd_merge):
        self.config.load(command, format=cmd_format, merge=cmd_merge)

    def file_command(self, file_path, file_format, file_merge):
        self.config.load(path=file_path, format=file_format, merge=file_merge)
   
    def get_diff(self):
        return self.config.diff()

    def commit(self, comment=None):
        self.config.commit(comment=comment)
   
    def rollback(self):
        self.config.rollback(0)

    def unlock(self):
        self.config.unlock()

    def show_all_interfaces(self):
        self.__get_ports()
        print "Juniper SRX Interface Statistics"
        for my_key in self.ports.keys():
            print "---------------------------------"
            print my_key + ":"
            print "Operational Status: " + self.ports[my_key]['oper']
            print "Packets In: " + self.ports[my_key]['rx_packets']
            print "Packets Out: " + self.ports[my_key]['tx_packets']

    def show_all_routes(self):
        self.__get_routes()
        print "Juniper SRX Routing Table"
        for my_key in self.routes.keys():
            print "---------------------------------"
            print my_key + ":"
            print "  Next Hop: {}".format(self.routes[my_key]['nexthop'])
            print "  Age: {}".format(self.routes[my_key]['age'])
            print "  via: {}".format(self.routes[my_key]['via'])
            print "  Protocol: {}".format(self.routes[my_key]['protocol'])
开发者ID:pmusolino-rms,项目名称:Network-Automation-with-Python-and-Ansible-class,代码行数:59,代码来源:juniper_connection.py

示例7: bind_service

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
 def bind_service(self, cvlan_id, svlan_name, port_name):
     """Binds cvlan_id from port_name to svlan_name (one-to-one bundling)
     """
     bind_service_vars={}
     bind_service_vars['cvlan_id'] = cvlan_id
     bind_service_vars['svlan_name'] = svlan_name
     bind_service_vars['port_name'] = port_name
     cu = Config(self.connection)
     cu.load(template_path='service-templates/junos/ex/dot1ad-service.conf', template_vars=bind_service_vars, merge=True)  
开发者ID:dfex,项目名称:lattice,代码行数:11,代码来源:junosconnect.py

示例8: create_svlan

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
 def create_svlan(self, vlan_id, svlan_name, vlan_description):
     """Create Service VLAN on switch
     """
     svlan_vars={}
     svlan_vars['vlan_stag'] = vlan_id
     svlan_vars['svlan_name'] = svlan_name
     svlan_vars['vlan_description'] = vlan_description
     cu = Config(self.connection)
     cu.load(template_path='service-templates/junos/ex/dot1ad-vlan.conf', template_vars=svlan_vars, merge=True)  
开发者ID:dfex,项目名称:lattice,代码行数:11,代码来源:junosconnect.py

示例9: run

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
    def run(self):
        self.logfile = open(os.getcwd() + '/' + 'linkfailure_log', 'a')
        while True:
            while self.failed() == False:
                time.sleep(1)
            # select a router
            r_number = random.randint(1,len(self.rtr)) - 1
            # select a random interface 
            i_number = random.randint(1, len(self.rtr[r_number]['interfaces'])) - 1

            #set interfaces ge-1/0/3 disable 

            cmd = 'set interfaces ' + self.rtr[r_number]['interfaces'][i_number]['name'] + ' disable'

            dev = Device(host=self.rtr[r_number]['ip'], user='root', password='juniper123')
            dev.open()
            dev.timeout = 60
            cu = Config(dev)
            cu.lock()
            cu.load(cmd, format='set', merge=True)
            cu.commit()
            cu.unlock()
            dev.close()
            link__data = { 'status': 'failed', 'timestamp': datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S'), 
                                'router_id': self.rtr[r_number]['router_id'], 'router_name': self.rtr[r_number]['name'],
                                'interface_address': self.rtr[r_number]['interfaces'][i_number]['address'],
                                'interface_name': self.rtr[r_number]['interfaces'][i_number]['name']
                         }
            jd = json.dumps(link__data)
            self.redis.publish('link_event', jd)
            self.logfile.write("Link failed: " + datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S') + " " +
                               self.rtr[r_number]['name'] + " " +  self.rtr[r_number]['ip'] + " " + self.rtr[r_number]['interfaces'][i_number]['name'] + "\n")
            self.logfile.flush()
            # now repair the link
            while self.repaired() == False:
                time.sleep(1)

            cmd = 'delete interfaces ' + self.rtr[r_number]['interfaces'][i_number]['name'] + ' disable'
            dev = Device(host=self.rtr[r_number]['ip'], user='root', password='juniper123')
            dev.open()
            dev.timeout = 60
            cu = Config(dev)
            cu.lock()
            cu.load(cmd, format='set', merge=True)
            cu.commit()
            cu.unlock()
            dev.close()
            link__data = { 'status': 'healed', 'timestamp': datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S'), 
                                'router_id': self.rtr[r_number]['router_id'], 'router_name': self.rtr[r_number]['name'],
                                'interface_address': self.rtr[r_number]['interfaces'][i_number]['address'],
                                'interface_name': self.rtr[r_number]['interfaces'][i_number]['name']
                         }
            jd = json.dumps(link__data)
            self.redis.publish('link_event', jd)
            self.logfile.write("Link healed: " + datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S') + " " +
                               self.rtr[r_number]['name'] + " " +  self.rtr[r_number]['ip'] + " " + self.rtr[r_number]['interfaces'][i_number]['name'] + "\n")
            self.logfile.flush()
开发者ID:azaringhalam,项目名称:hackathon,代码行数:59,代码来源:link_failure.py

示例10: test_ignore_warning_list_3warn_no_match

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
 def test_ignore_warning_list_3warn_no_match(self):
     self.dev._conn.rpc = MagicMock(side_effect=
                                    self._mock_manager_3foobar_warnings)
     cu = Config(self.dev)
     config = """
         delete interfaces ge-0/0/0
         delete protcols ospf
         delete policy-options prefix-list foo
     """
     with self.assertRaises(ConfigLoadError):
         cu.load(config, ignore_warning=['foo', 'foo bar'])
开发者ID:GIC-de,项目名称:py-junos-eznc,代码行数:13,代码来源:test_decorators.py

示例11: test_ignore_warning_string_1snf_warning_1err

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
 def test_ignore_warning_string_1snf_warning_1err(self):
     self.dev._conn.rpc = MagicMock(side_effect=
                                    self._mock_manager_1snf_warning_1err)
     cu = Config(self.dev)
     config = """
         delete interfaces ge-0/0/0
         delete protcols ospf
         delete policy-options prefix-list foo
     """
     with self.assertRaises(ConfigLoadError):
         cu.load(config, ignore_warning='statement not found')
开发者ID:GIC-de,项目名称:py-junos-eznc,代码行数:13,代码来源:test_decorators.py

示例12: __init__

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
class Jconfig:

    def __init__(self, host, user='rancid', password='xxxxx', t_vars={}):
        self.host = host
        self.user = user
        self.password = password
        self.t_vars = t_vars

        self.dev = Device(host=self.host, user=self.user, password=self.password, gather_facts=False)
        try:
            self.dev.open()
            self.dev.timeout = 300
            self.cfg = Config(self.dev)
        except Exception as err:
            print err
            sys.exit(1)

    def loadconf(self, t_file):
        try:
            print "=> Loading file %s on %s" % (t_file, self.host)
            self.cfg.load(template_path=t_file, template_vars=self.t_vars, overwrite=False, merge=True)
        except Exception as err:
            print err

    def askcommit(self):
        try:
            print "== Configuration diff on %s" % (self.host)
            self.cfg.pdiff()
            answer = raw_input('Do you want to commit change ? [y/n]')
            if answer[0] == 'y':
                self.cfg.commit()
        except Exception as err:
            print err

    def commit(self):
        try:
            print "== Configuration diff on %s" % (self.host)
            self.cfg.pdiff()
            self.cfg.commit()
        except Exception as err:
            print err
    
    def getconf(self):
        try:
            conf = self.dev.rpc.get_configuration(dict(format='text'))
            return etree.tostring(conf, method="text")
        except Exception as err:
            print err
开发者ID:ut0mt8,项目名称:junos-netconf,代码行数:50,代码来源:jconfig.py

示例13: test_load_config

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
 def test_load_config(self):
     from jnpr.junos.utils.config import Config
     cu = Config(self.dev)
     data = """interfaces {
        ge-1/0/0 {
           description "MPLS interface";
           unit 0 {
              family mpls;
           }
       }
     }
     """
     cu.load(data, format='text')
     self.assertTrue(cu.commit_check())
     if cu.commit_check():
         cu.rollback()
开发者ID:dattamiruke,项目名称:py-junos-eznc,代码行数:18,代码来源:test_core.py

示例14: NetconfConnection

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
class NetconfConnection(AbstractConnection):
    ''' Netconf connection class
    '''
    def __init__(self, host, username='root', password='c0ntrail123',
        logger=None, **kwargs):
        self.host = host
        self.username = username
        self.password = password
        self.handle = None
        self.logger = kwargs.get('logger', contrail_logging.getLogger(__name__))
        self.config_handle = None

        
    def connect(self):
        self.handle = Device(host=self.host, user=self.username, 
            password=self.password)
        try:
            self.handle.open(gather_facts=False)
            self.config_handle = Config(self.handle)
        except (ConnectAuthError,ConnectRefusedError, ConnectTimeoutError,
            ConnectError) as e:
            self.logger.exception(e)
        return self.handle 
    # end connect

    def disconnect(self):
        self.handle.close()

    def show_version(self):
        return self.handle.show_version()

    def config(self, stmts=[], commit=True, ignore_errors=False, timeout = 30):
        for stmt in stmts:
            try:
                self.config_handle.load(stmt, format='set', merge=True)
            except ConfigLoadError,e:
                if ignore_errors:
                    self.logger.debug('Exception %s ignored' % (e))
                    self.logger.exception(e)
                else:
                    raise e
        if commit:
            try:
                self.config_handle.commit(timeout = timeout)
            except CommitError,e:
                self.logger.exception(e)
                return (False,e)
开发者ID:Ankitja,项目名称:contrail-test,代码行数:49,代码来源:device_connection.py

示例15: updateDeviceConfiguration

# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import load [as 别名]
    def updateDeviceConfiguration(self):
        '''
        Device Connection should be open by now, no need to connect again 
        '''
        logger.debug('updateDeviceConfiguration for %s' % (self.deviceLogStr))
        l3ClosMediation = L3ClosMediation(conf = self._conf)
        config = l3ClosMediation.createLeafConfigFor2Stage(self.device)
        # l3ClosMediation used seperate db sessions to create device config
        # expire device from current session for lazy load with committed data
        self._session.expire(self.device)
        
        configurationUnit = Config(self.deviceConnectionHandle)

        try:
            configurationUnit.lock()
            logger.debug('Lock config for %s' % (self.deviceLogStr))

        except LockError as exc:
            logger.error('updateDeviceConfiguration failed for %s, LockError: %s, %s, %s' % (self.deviceLogStr, exc, exc.errs, exc.rpc_error))
            raise DeviceError(exc)

        try:
            # make sure no changes are taken from CLI candidate config left over
            configurationUnit.rollback() 
            logger.debug('Rollback any other config for %s' % (self.deviceLogStr))
            configurationUnit.load(config, format='text')
            logger.debug('Load generated config as candidate, for %s' % (self.deviceLogStr))

            #print configurationUnit.diff()
            #print configurationUnit.commit_check()
            configurationUnit.commit()
            logger.info('Committed twoStage config for %s' % (self.deviceLogStr))
        except CommitError as exc:
            #TODO: eznc Error handling is not giving helpful error message
            logger.error('updateDeviceConfiguration failed for %s, CommitError: %s, %s, %s' % (self.deviceLogStr, exc, exc.errs, exc.rpc_error))
            configurationUnit.rollback() 
            raise DeviceError(exc)
        except Exception as exc:
            logger.error('updateDeviceConfiguration failed for %s, %s' % (self.deviceLogStr, exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            configurationUnit.rollback() 
            raise DeviceError(exc)

        finally:
            configurationUnit.unlock()
            logger.debug('Unlock config for %s' % (self.deviceLogStr))
开发者ID:codyrat,项目名称:OpenClos,代码行数:48,代码来源:devicePlugin.py


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