本文整理汇总了Python中jnpr.junos.utils.config.Config类的典型用法代码示例。如果您正苦于以下问题:Python Config类的具体用法?Python Config怎么用?Python Config使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Config类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_load_console
def test_load_console(
self, mock_read_until, mock_select, mock_write, mock_parse):
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)
op = cu.load(xml, format='xml')
cu.commit()
示例2: main
def main():
"""Simple main method to change port status."""
routers = ['10.11.12.1', '10.11.12.2']
pyez_user = 'netconf'
pyez_pass = 'test123'
sessions = [Device(host=router, user=pyez_user, password=pyez_pass) for router in routers]
for session in sessions:
session.open()
port = PhyPortClassic(session, namevar='ge-0/0/3')
# Step 1.1
# print(port.properties)
# print(port.admin)
# Step 1.2
port.admin = False
port.write()
print("Disabling interfaces!")
cfg = Config(session)
cfg.commit()
time.sleep(10)
port.admin = True
port.write()
print("Enabling interfaces!")
cfg.commit()
session.close()
示例3: create_port
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)
示例4: create_svlan
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)
示例5: bind_service
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)
示例6: test_ignore_warning_string_3snf_warnings
def test_ignore_warning_string_3snf_warnings(self):
self.dev._conn.rpc = MagicMock(side_effect=
self._mock_manager_3snf_warnings)
cu = Config(self.dev)
config = """
delete interfaces ge-0/0/0
delete protocols ospf
delete policy-options prefix-list foo
"""
self.assertTrue(cu.load(config, ignore_warning='statement not found'))
示例7: edit_config
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
示例8: _normal_device
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"
示例9: test_ignore_warning_list_3warn_no_match
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'])
示例10: test_ignore_warning_string_1snf_warning_1err
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')
示例11: update_configuration
def update_configuration(dev, cfg, ticket, nwadmin):
"""
It carries out the configuration procedure , i.e. Lock-Load-Diff-Commit-Unlock
This function is NOT intended to be used with Jinja2 templates but with Configuration Tables
"""
# Instantiate Class Config to get user friendly junos like diff output --------------
cu = Config(dev)
cprint("Review the configuration changes to be applied on %s" % dev, 'yellow')
agree = 'N'
try:
cfg.lock()
cfg.load()
# rather than cfg.diff() use cu.diff() - it creates more user friendly outputs
print(cu.diff())
agree = input("Do you want to apply these changes? y/n[N]: " or 'N')
except LockError as err:
print("Unable to lock configuration: {0}".format(err))
except (ConfigLoadError, Exception) as err:
print("Unable to load configuration changes: {0}".format(err))
print("Unlocking the configuration")
try:
cfg.unlock()
except UnlockError:
print("Unable to unlock configuration: {0}".format(err))
# Proceed with updating configuration -----------------------------------------------
if agree == "Y" or agree == "y":
print("Committing the configuration")
try:
cfg.commit(comment=ticket + "/" + nwadmin)
except CommitError as err:
print("Unable to commit configuration: {0}".format(err))
print("Unlocking the configuration")
try:
print("Unlocking the configuration")
cfg.rollback()
cfg.unlock()
except UnlockError as err:
print("Unable to unlock configuration: {0}".format(err))
else:
# Discard changes
try:
print("Discarding changes")
cfg.rollback()
cfg.unlock()
except UnlockError as err:
print("Unable to unlock configuration: {0}".format(err))
示例12: __init__
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
示例13: connect
def connect(self, params, **kwargs):
host = params['host']
kwargs = dict()
kwargs['port'] = params.get('port') or 830
kwargs['user'] = params['username']
if params['password']:
kwargs['passwd'] = params['password']
if params['ssh_keyfile']:
kwargs['ssh_private_key_file'] = params['ssh_keyfile']
kwargs['gather_facts'] = False
try:
self.device = Device(host, **kwargs)
self.device.open()
except ConnectError:
exc = get_exception()
self.raise_exc('unable to connect to %s: %s' % (host, str(exc)))
self.config = Config(self.device)
self._connected = True
示例14: setUp
def setUp(self, mock_connect):
mock_connect.side_effect = self._mock_manager
self.dev = Device(host='1.1.1.1', user='test', password='test123',
gather_facts=False)
self.dev.open()
self.conf = Config(self.dev)
示例15: NetconfConnection
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)