本文整理汇总了Python中jnpr.junos.utils.config.Config.rollback方法的典型用法代码示例。如果您正苦于以下问题:Python Config.rollback方法的具体用法?Python Config.rollback怎么用?Python Config.rollback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jnpr.junos.utils.config.Config
的用法示例。
在下文中一共展示了Config.rollback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: JuniperObject
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [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
示例2: test_load_config
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [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()
示例3: main
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
def main():
'''
Exercise using Juniper's PyEZ to make changes to device in various ways
'''
pwd = getpass()
ip_addr = raw_input("Enter Juniper SRX IP: ")
ip_addr = ip_addr.strip()
juniper_srx = {
"host": ip_addr,
"user": "pyclass",
"password": pwd
}
print "\n\nConnecting to Juniper SRX...\n"
a_device = Device(**juniper_srx)
a_device.open()
cfg = Config(a_device)
print "Setting hostname using set notation"
cfg.load("set system host-name test1", format="set", merge=True)
print "Current config differences: "
print cfg.diff()
print "Performing rollback"
cfg.rollback(0)
print "\nSetting hostname using {} notation (external file)"
cfg.load(path="load_hostname.conf", format="text", merge=True)
print "Current config differences: "
print cfg.diff()
print "Performing commit"
cfg.commit()
print "\nSetting hostname using XML (external file)"
cfg.load(path="load_hostname.xml", format="xml", merge=True)
print "Current config differences: "
print cfg.diff()
print "Performing commit"
cfg.commit()
print
示例4: main
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
def main():
'''
Main function
'''
a_device = remote_conn(HOST, USER, PWD)
if not a_device:
sys.exit('Fix the above errors. Exiting...')
print a_device.facts
cfg = Config(a_device)
cfg.lock()
print 'Set hostname using set format'
set_hostname(cfg, 'pytest-gmaz', 'set')
print 'Show differences'
print cfg.diff()
print 'Rollback'
cfg.rollback(0)
print 'Check if rollback is ok'
print cfg.diff()
print 'Set hostname using cfg file'
set_hostname(cfg, 'hostname.conf', 'text')
print 'Show differences'
print cfg.diff()
print 'Commit'
cfg.commit(comment='Text hostname commit by gmazioli')
print 'Set hostname using external XML'
set_hostname(cfg, 'hostname.xml', 'xml')
print 'Show differences'
print cfg.diff()
print 'Commit'
cfg.commit(comment='XML hostname commit by gmazioli')
print 'Reverting changes and doing the final commit'
set_hostname(cfg, 'pynet-jnpr-srx1', 'set')
cfg.commit(comment='System commit by gmazioli')
cfg.unlock()
示例5: main
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
def main():
'''
I will test the case with applying config for 1 minute
'''
pwd = getpass()
ip_addr = raw_input('''Enter Juniper SRX IP"(184.105.247.76)": ''')
ip_addr = ip_addr.strip()
juniper_srx = {
"host": ip_addr,
"user": "pyclass",
"password": pwd
}
try:
a_device = Device(**juniper_srx)
a_device.open()
cfg = Config(a_device)
cfg.lock()
cfg.load(path="exercice4_config.xml" , format="xml", merge=True)
print "#"*80
print "Displaying the differences between the running config and the candidate config:"
print "#"*80
cfg.pdiff()
print "+"*80
print "Applying config"
print "+"*80
cfg.commit(comment="Applying config from exercice4_config.xml")
print "-"*80
print "reverting config back"
cfg.rollback(1)
cfg.pdiff()
cfg.commit()
print "-"*80
print "\n"*2
print
except:
print
print "Authentication Error"
print
示例6: main
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
def main():
pwd = getpass()
juniper = {
"host": "50.76.53.27",
"user": "pyclass",
"password": pwd
}
a_device = Device(**juniper)
a_device.open()
cfg = Config(a_device)
print "Changing hostname with set command"
cfg_load = cfg.load("set system host-name batz-jnpr-srx1", format ="set", merge=True)
print cfg.diff()
print
print "Doing rollback"
cfg.rollback(0)
print "Changing hostname with conf method "
cfg_load_conf = cfg.load(path='hostname.conf', format='text', merge=True)
print cfg.diff()
print
print "Doing rollback"
cfg.rollback(0)
print "Changing hostname with xml method"
cfg_load_xml = cfg.load(path='hostname.xml', format='xml', merge=True)
print cfg.diff()
print
print "Doing changes"
cfg.commit()
print
示例7: updateDeviceConfiguration
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [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))
示例8: updateDeviceConfiguration
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
def updateDeviceConfiguration(self):
'''
Device Connection should be open by now, no need to connect again
'''
logger.debug('updateDeviceConfiguration for %s' % (self.deviceLogStr))
config = self.getDeviceConfig()
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 DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), 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 DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), 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 DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), exc)
finally:
configurationUnit.unlock()
logger.debug('Unlock config for %s' % (self.deviceLogStr))
示例9: TestConfig
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
class TestConfig(unittest.TestCase):
def setUp(self):
self.dev = Device(host='1.1.1.1')
self.conf = Config(self.dev)
def test_config_constructor(self):
self.assertTrue(isinstance(self.conf._dev, Device))
def test_config_confirm(self):
self.conf.rpc.commit_configuration = MagicMock()
self.assertTrue(self.conf.commit(confirm=True))
def test_config_commit_confirm_timeout(self):
self.conf.rpc.commit_configuration = MagicMock()
self.conf.commit(confirm=10)
self.conf.rpc.commit_configuration\
.assert_called_with(**{'confirm-timeout': '10', 'confirmed': True})
def test_config_commit_comment(self):
self.conf.rpc.commit_configuration = MagicMock()
self.conf.commit(comment='Test')
self.conf.rpc.commit_configuration.assert_called_with(log='Test')
@patch('jnpr.junos.utils.config.JXML.remove_namespaces')
def test_config_commit_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.commit_configuration = \
MagicMock(side_effect=MyException)
self.assertRaises(AttributeError, self.conf.commit)
def test_config_commit_exception_RpcError(self):
ex = RpcError(rsp='ok')
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertTrue(self.conf.commit())
import xml.etree.ElementTree as ET
xmldata = """<data><company name="Juniper">
<code>pyez</code>
<year>2013</year>
</company></data>"""
root = ET.fromstring(xmldata)
el = root.find('company')
ex = RpcError(rsp=el)
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertRaises(CommitError, self.conf.commit)
def test_commit_check(self):
self.conf.rpc.commit_configuration = MagicMock()
self.assertTrue(self.conf.commit_check())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_commit_check_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.commit_configuration = MagicMock(side_effect=MyException)
# with self.assertRaises(AttributeError):
self.conf.commit_check()
def test_config_commit_check_exception_RpcError(self):
ex = RpcError(rsp='ok')
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertTrue(self.conf.commit_check())
import xml.etree.ElementTree as ET
xmldata = """<data><company name="Juniper">
<code>pyez</code>
<year>2013</year>
</company></data>"""
root = ET.fromstring(xmldata)
el = root.find('company')
ex = RpcError(rsp=el)
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertRaises(CommitError, self.conf.commit_check)
def test_config_diff(self):
self.conf.rpc.get_configuration = MagicMock()
self.conf.diff()
self.conf.rpc.get_configuration.\
assert_called_with({'compare': 'rollback', 'rollback': '0', 'format': 'text'})
def test_config_pdiff(self):
self.conf.diff = MagicMock(return_value='Stuff')
self.conf.pdiff()
print self.conf.diff.call_args
self.conf.diff.assert_called_once_with(0)
def test_config_load(self):
self.assertRaises(RuntimeError, self.conf.load)
def test_config_load_vargs_len(self):
self.assertRaises(RuntimeError, self.conf.load,
'test.xml')
def test_config_load_len_with_format(self):
self.conf.rpc.load_config = \
MagicMock(return_value='rpc_contents')
self.assertEqual(self.conf.load('test.xml', format='set'),
'rpc_contents')
@patch('__builtin__.open')
def test_config_load_lformat_byext_ValueError(self, mock_open):
#.........这里部分代码省略.........
示例10: apply_template
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
def apply_template(self, template):
print self.dev
conf_string = template.strip()
print conf_string
if re.search(r"^<", conf_string):
print "Found a encoded string"
conf_string = self.unescape(conf_string)
print conf_string
# try to determine the format of our config_string
config_format = "set"
if re.search(r"^\s*<.*>$", conf_string, re.MULTILINE):
print "found xml style config"
config_format = "xml"
elif re.search(r"^\s*(set|delete|replace|rename)\s", conf_string):
print "found set style config"
config_format = "set"
elif re.search(r"^[a-z:]*\s*\w+\s+{", conf_string, re.I) and re.search(r".*}\s*$", conf_string):
print "found a text style config"
config_format = "text"
print "using format: " + config_format
cu = Config(self.dev)
try:
cu.lock()
except LockError as le:
print "Could not lock database!"
print str(le)
self.dev.close()
return "Failed to lock configuration database! %s" % str(le)
try:
print "loading config"
cu.load(conf_string, format=config_format)
except Exception as e:
print "Could not load configuration"
print str(e)
try:
cu.unlock()
except UnlockError as ue:
print str(ue)
self.dev.close()
return "Failed, could not load the configuration template. %s" % str(e)
diff = cu.diff()
print diff
if diff is not None:
try:
cu.commit_check()
print "Committing config!"
cu.commit(comment="Commit via a_frame")
except CommitError as ce:
print "Could not load config! %s" % str(ce)
cu.rollback()
try:
print "Unlocking database!"
cu.unlock()
except UnlockError as ue:
print "Could not unlock database"
print str(ue)
print repr(ce)
self.dev.close()
return "Failed, commit check failed. %s" % str(ce)
else:
# nothing to commit
print "Nothing to commit - no diff found"
cu.unlock()
self.dev.close()
return "Nothing to commit!"
try:
print "Unlocking database!"
cu.unlock()
except UnlockError as ue:
print "Could not unlock database"
print str(ue)
self.dev.close()
return "Committed, but could not unlock db"
print "Closing device handle"
self.dev.close()
return "Completed with diff: %s" % diff
示例11: NetconfJuniperSess
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
class NetconfJuniperSess(SessBase):
"""netconfセッション用クラス
"""
def __init__(self, server, user_login, pass_login, logger_name, netconf_port=830, rpc_timeout=20):
self.server = server
self.user_login = user_login
self.pass_login = pass_login
self.logger = logging.getLogger(logger_name)
self.netconf_port = netconf_port
self.rpc_timeout = rpc_timeout
self.closed = True
self.acl_name = 'SNMP-ACCESS'
self.last_acl = list()
def open(self):
"""サーバに接続
"""
self.dev = Device(
host=self.server.ipaddr,
user=self.user_login,
password=self.pass_login,
)
self.dev.open(gather_facts=False)
if self.dev.connected:
# デフォルト30秒を更新
setattr(self.dev, 'timeout', self.rpc_timeout)
self.cu = Config(self.dev)
self.closed = False
self.write_log(self.logger, 'info', "%s (%s): 接続しました." % (self.server.ipaddr, self.server.model, ))
else:
raise RuntimeError("%s: %s: unable to connect." % (self.__class__.__name__, self.server.ipaddr))
def get_snmp_acl(self, **kw):
""" SNMPアクセスリストを取得
>>> for pl in PrefListTable(self.dev).get():
... if pl.name == 'SNMP-ACCESS':
... pp.pprint(json.loads(pl.entries.to_json()))
...
{ u'10.0.0.1/32': { u'prefix': u'10.0.0.1/32'},
u'172.25.8.0/24': { u'prefix': u'172.25.8.0/24'},
u'172.31.30.0/24': { u'prefix': u'172.31.30.0/24'},
u'192.168.11.0/24': { u'prefix': u'192.168.11.0/24'}}
"""
set_last_acl = kw.get('set_last_acl', True)
acl = list()
for pl in PrefListTable(self.dev).get():
if pl.name == self.acl_name:
# prefix-list name がマッチしたらエントリを取得
acl = map(IPv4Network, pl.entries.keys())
break
# 取得できなかった場合はカラのリストを返す
if set_last_acl: self.last_acl = acl
return acl
def update_snmp_acl(self, acl_diff_dict, **kw):
""" SNMPアクセスリストを更新
"""
if not os.access(template_path, os.R_OK):
self.close(error_msg="テンプレートファイルを開けません.: %s" % (template_path, ))
raise IOError('failed!')
if kw.get('prompt', False):
# 確認プロンプトを表示
reply = raw_input("変更しますか? ")
if not re.match('\s*(y|yes|)\s*$', reply.rstrip(), re.I):
self.write_log(self.logger, 'info', "%s: 更新をキャンセルします." % (self.server.ipaddr, ))
self.close()
return False
new_acl = list(set(self.last_acl) - set(acl_diff_dict['del'])) + acl_diff_dict['add']
template_vars = dict([
('acl_dict', dict([
(self.acl_name, [ n.with_prefixlen for n in new_acl ]),
])),
])
# 新しいACLを機器にロードする
self.cu.lock()
self.cu.load(template_path=template_path, template_vars=template_vars)
return self.get_snmp_acl(set_last_acl=False)
def save_exit_config(self, **kw):
""" コミット or ロールバック
"""
if kw.get('prompt', False):
# 確認プロンプトを表示
if not re.match('\s*(y|yes|)\s*$', raw_input("保存しますか? ").rstrip(), re.I):
self.write_log(self.logger, 'info', "%s: ロールバックします." % (self.server.ipaddr, ))
self.cu.rollback()
current_acl = self.get_snmp_acl(set_last_acl=False)
failed = set(current_acl) != set(self.last_acl)
if failed:
self.close(error_msg="正常にロールバックできませんでした.: %s%s" % (
self.last_acl,
current_acl, ))
raise RuntimeError('failed!')
self.close()
return
# コミット
self.cu.commit()
#.........这里部分代码省略.........
示例12: TestConfig
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
#.........这里部分代码省略.........
def test_commit_check(self):
self.conf.rpc.commit_configuration = MagicMock()
self.assertTrue(self.conf.commit_check())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_commit_check_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.commit_configuration = MagicMock(side_effect=MyException)
# with self.assertRaises(AttributeError):
self.conf.commit_check()
def test_config_commit_check_exception_RpcError(self):
ex = RpcError(rsp='ok')
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertTrue(self.conf.commit_check())
import xml.etree.ElementTree as ET
xmldata = """<data><company name="Juniper">
<code>pyez</code>
<year>2013</year>
</company></data>"""
root = ET.fromstring(xmldata)
el = root.find('company')
ex = RpcError(rsp=el)
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertRaises(CommitError, self.conf.commit_check)
def test_config_diff(self):
self.conf.rpc.get_configuration = MagicMock()
self.conf.diff()
self.conf.rpc.get_configuration.\
assert_called_with(
{'compare': 'rollback', 'rollback': '0', 'format': 'text'})
def test_config_pdiff(self):
self.conf.diff = MagicMock(return_value='Stuff')
self.conf.pdiff()
self.conf.diff.assert_called_once_with(0)
def test_config_load(self):
self.assertRaises(RuntimeError, self.conf.load)
def test_config_load_vargs_len(self):
self.assertRaises(RuntimeError, self.conf.load,
'test.xml')
def test_config_load_len_with_format_set(self):
self.conf.rpc.load_config = \
MagicMock(return_value='rpc_contents')
self.assertEqual(self.conf.load('test.xml', format='set'),
'rpc_contents')
def test_config_load_len_with_format_xml(self):
self.conf.rpc.load_config = \
MagicMock(return_value='rpc_contents')
xmldata = """<snmp>
<community>
<name>iBGP</name>
</community>
</snmp>"""
self.assertEqual(self.conf.load(xmldata, format='xml'),
'rpc_contents')
@patch('__builtin__.open')
示例13: Config
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
# Create a Config instance
cfg = Config(a_device)
# Lock the Juniper device while you are doing the config changes
cfg.lock()
# 1. Load config via load-set command
cfg.load("set system host-name juniper-test-name", format="set", merge=True)
# Show the differences between running-config and candidate config
print cfg.diff()
# cfg.commit()
# Rollback the candidate config changes
cfg.rollback(0)
# 2. Load new config via 'test_config.conf' file (using curly braces)
# Create test_config.conf file first in the currently-running Linux directory
cfg.load(path="test_config.conf", format="text", merge=True)
# Show the differences between running-config and candidate config
print cfg.diff()
cfg.rollback(0)
# 3. Load new config via 'test_config.xml' file (in XML format)
# Create test_config.xml file first in the currently-running Linux directory
cfg.load(path="test_config.xml", format="xml", merge=True)
示例14: TestConfig
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
#.........这里部分代码省略.........
def test_commit_check(self):
self.conf.rpc.commit_configuration = MagicMock()
self.assertTrue(self.conf.commit_check())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_commit_check_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.commit_configuration = MagicMock(side_effect=MyException)
# with self.assertRaises(AttributeError):
self.conf.commit_check()
def test_config_commit_check_exception_RpcError(self):
ex = RpcError(rsp='ok')
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertTrue(self.conf.commit_check())
import xml.etree.ElementTree as ET
xmldata = """<data><company name="Juniper">
<code>pyez</code>
<year>2013</year>
</company></data>"""
root = ET.fromstring(xmldata)
el = root.find('company')
ex = RpcError(rsp=el)
self.conf.rpc.commit_configuration = MagicMock(side_effect=ex)
self.assertRaises(CommitError, self.conf.commit_check)
def test_config_diff(self):
self.conf.rpc.get_configuration = MagicMock()
self.conf.diff()
self.conf.rpc.get_configuration.\
assert_called_with(
{'compare': 'rollback', 'rollback': '0', 'format': 'text'})
def test_config_diff_exception_severity_warning(self):
rpc_xml = '''
<rpc-error>
<error-severity>warning</error-severity>
<error-info><bad-element>bgp</bad-element></error-info>
<error-message>mgd: statement must contain additional statements</error-message>
</rpc-error>
'''
rsp = etree.XML(rpc_xml)
self.conf.rpc.get_configuration = MagicMock(
side_effect=RpcError(rsp=rsp))
self.assertEqual(self.conf.diff(),
"Unable to parse diff from response!")
def test_config_diff_exception_severity_warning_still_raise(self):
rpc_xml = '''
<rpc-error>
<error-severity>warning</error-severity>
<error-info><bad-element>bgp</bad-element></error-info>
<error-message>statement not found</error-message>
</rpc-error>
'''
rsp = etree.XML(rpc_xml)
self.conf.rpc.get_configuration = MagicMock(
side_effect=RpcError(rsp=rsp))
self.assertRaises(RpcError, self.conf.diff)
def test_config_pdiff(self):
self.conf.diff = MagicMock(return_value='Stuff')
self.conf.pdiff()
self.conf.diff.assert_called_once_with(0)
示例15: E
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import rollback [as 别名]
E('filter',
E('name', 'test'),
E('term',
E('name', 'term1'),
E('from',
E('source-address',
E('name', '1.1.1.1/32')
)
)
)
)
)
)
#cu.load(data, format='xml')
cu.load(data)
print "\nconfig# show | compare"
cu.pdiff()
if cu.commit_check():
print "\nCommiting..\n"
# cu.commit(comment="Configuring ge-1/0/1 interfaces")
cu.commit(sync=True)
else:
cu.rollback()
print "Rolling back the configuration"
cu.rollback(rb_id=1)
cu.commit(detail=True)