本文整理汇总了Python中jnpr.junos.utils.config.Config.lock方法的典型用法代码示例。如果您正苦于以下问题:Python Config.lock方法的具体用法?Python Config.lock怎么用?Python Config.lock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jnpr.junos.utils.config.Config
的用法示例。
在下文中一共展示了Config.lock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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()
示例2: JuniperObject
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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
示例3: process_device
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [as 别名]
def process_device(ip, **kwargs):
dev = Device(host=ip, **kwargs)
cu = Config(dev)
print "Searching for active sessions on Device:", ip, "matching the following criteria" + '\n\n\t' + "Destination IP-Address:" + '\t' + destip + '\n\t' + "Destination-Port:" + '\t' + dport + '\n\t' + "Application:" + '\t\t' + application + '\n'
try:
dev.open()
cluster_status = ClusterStatus(dev)
cluster_status.get()
session_table = SessionTable(dev)
session_table.get()
found = 'f'
cluster = 'a'
cu.lock()
for c in cluster_status:
if cluster_status.keys():
print "SRX Cluster has redundancy-group", c.redundancy_group_id
if not cluster_status.keys():
print "Clustering is not Enabled"
for s in session_table:
if session_table.keys() and s.in_destination_address == destip and s.in_destination_port == dport and s.in_session_protocol == application:
found = 't'
print "Found Session on", ip, s.re_name + '\n\n\t' + "Source-Address:" + '\t' + s.in_source_address +'\n\t' + "Session-Id:" + '\t' + s.session_identifier + '\n\n' + "Creating Address-entry on Device:", ip + '\n\n' + "Clearing active session" + '\n\t' + "Session-Id:" + '\t' + s.session_identifier + '\n\t' + "Cluster-Node:" + '\t' + s.re_name + '\n'
block_src = {'Address': s.in_source_address}
jinja_data = open("jinjafile.conf", "wb")
jinja_data.write(JinjaTemplate.render(**block_src))
jinja_data.close()
rsp = cu.load( template_path="jinjafile.conf", merge=True )
clearflow = dev.rpc.clear_flow_session(destination_prefix=s.in_destination_address, source_prefix=s.in_source_address, destination_port=s.in_destination_port, protocol=s.in_session_protocol)
cu.commit()
cu.unlock()
if found == 'f':
print "No Active Sessions were found with the following criteria:" + '\n\n\t' + "Destination IP-Address:" + '\t' + destip + '\n\t' + "Destination Port:" + '\t' + dport +'\n\t' + "Application:" + '\t\t' + application + '\n'
except RpcError:
msg = "{0} was Skipped due to RPC Error. Device is not a Juniper SRX Series".format(ip.rstrip())
print msg
dev.close()
except Exception as err:
msg = "{0} was skipped due to unhandled exception.\n{1}".format(ip.rstrip(), err)
print msg
traceback.print_exc(file=sys.stdout)
dev.close()
示例4: updateDeviceConfiguration
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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))
示例5: updateDeviceConfiguration
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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))
示例6: main
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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()
示例7: main
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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
示例8: TestConfig
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [as 别名]
#.........这里部分代码省略.........
self.assertEqual(self.conf.load('test.xml', format='set'),
'rpc_contents')
@patch('__builtin__.open')
def test_config_load_lformat_byext_ValueError(self, mock_open):
self.conf.rpc.load_config = \
MagicMock(return_value='rpc_contents')
self.assertRaises(ValueError, self.conf.load, path='test.jnpr')
def test_config_load_lset_format_ValueError(self):
self.conf.rpc.load_config = \
MagicMock(return_value='rpc_contents')
self.assertRaises(ValueError, self.conf.load,
'test.xml', format='set', overwrite=True)
@patch('__builtin__.open')
@patch('jnpr.junos.utils.config.etree.XML')
def test_config_load_path_xml(self, mock_etree, mock_open):
self.conf.dev.Template = MagicMock()
mock_etree.return_value = 'rpc_contents'
self.conf.rpc.load_config = \
MagicMock(return_value=mock_etree.return_value)
self.assertEqual(self.conf.load(path='test.xml'), 'rpc_contents')
@patch('__builtin__.open')
def test_config_load_path_text(self, mock_open):
self.conf.rpc.load_config = MagicMock()
self.conf.load(path='test.conf')
self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'],
'text')
@patch('__builtin__.open')
def test_config_load_path_set(self, mock_open):
self.conf.rpc.load_config = MagicMock()
self.conf.load(path='test.set')
self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'],
'set')
def test_config_load_template_path(self):
self.conf.rpc.load_config = MagicMock()
self.conf.dev.Template = MagicMock()
self.conf.load(template_path='test.xml')
self.conf.dev.Template.assert_called_with('test.xml')
def test_config_load_template(self):
class Temp:
filename = 'abc.xml'
render = MagicMock()
self.conf.rpc.load_config = MagicMock()
self.conf.load(template=Temp)
self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'],
'xml')
def test_config_diff_exception(self):
self.conf.rpc.get_configuration = MagicMock()
self.assertRaises(ValueError, self.conf.diff, 51)
self.assertRaises(ValueError, self.conf.diff, -1)
def test_config_lock(self):
self.conf.rpc.lock_configuration = MagicMock()
self.assertTrue(self.conf.lock())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_config_lock_LockError(self, mock_jxml):
ex = RpcError(rsp='ok')
self.conf.rpc.lock_configuration = MagicMock(side_effect=ex)
self.assertRaises(LockError, self.conf.lock)
@patch('jnpr.junos.utils.config.JXML.remove_namespaces')
def test_config_lock_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.lock_configuration = MagicMock(side_effect=MyException)
self.assertRaises(LockError, self.conf.lock)
def test_config_unlock(self):
self.conf.rpc.unlock_configuration = MagicMock()
self.assertTrue(self.conf.unlock())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_config_unlock_LockError(self, mock_jxml):
ex = RpcError(rsp='ok')
self.conf.rpc.unlock_configuration = MagicMock(side_effect=ex)
self.assertRaises(UnlockError, self.conf.unlock)
@patch('jnpr.junos.utils.config.JXML.remove_namespaces')
def test_config_unlock_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.unlock_configuration = MagicMock(side_effect=MyException)
self.assertRaises(UnlockError, self.conf.unlock)
def test_config_rollback(self):
self.conf.rpc.load_configuration = MagicMock()
self.assertTrue(self.conf.rollback())
def test_config_rollback_exception(self):
self.conf.rpc.load_configuration = MagicMock()
self.assertRaises(ValueError, self.conf.rollback, 51)
self.assertRaises(ValueError, self.conf.rollback, -1)
示例9: apply_template
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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
示例10: NetconfJuniperSess
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [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()
#.........这里部分代码省略.........
示例11: TestConfig
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [as 别名]
#.........这里部分代码省略.........
</load-configuration-results>""")))
self.conf.rpc.load_config = MagicMock(side_effect=ex)
self.assertRaises(ConfigLoadError, self.conf.load, path='config.conf')
@patch('__builtin__.open')
def test_config_try_load_exception(self, mock_open):
class OtherException(Exception):
pass
self.conf.rpc.load_config = MagicMock(side_effect=OtherException())
self.assertRaises(OtherException, self.conf.load, path='config.conf')
@patch('jnpr.junos.utils.config.etree.XML')
def test_config_load_template_path(self, mock_etree):
self.conf.rpc.load_config = MagicMock()
self.conf.dev.Template = MagicMock()
self.conf.load(template_path='test.xml')
self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'],
'xml')
def test_config_load_template(self):
class Temp:
filename = 'abc.xml'
render = MagicMock(return_value='<test/>')
self.conf.rpc.load_config = MagicMock()
self.conf.load(template=Temp)
self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'],
'xml')
def test_config_diff_exception(self):
self.conf.rpc.get_configuration = MagicMock()
self.assertRaises(ValueError, self.conf.diff, 51)
self.assertRaises(ValueError, self.conf.diff, -1)
def test_config_lock(self):
self.conf.rpc.lock_configuration = MagicMock()
self.assertTrue(self.conf.lock())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_config_lock_LockError(self, mock_jxml):
ex = RpcError(rsp='ok')
self.conf.rpc.lock_configuration = MagicMock(side_effect=ex)
self.assertRaises(LockError, self.conf.lock)
@patch('jnpr.junos.utils.config.JXML.remove_namespaces')
def test_config_lock_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.lock_configuration = MagicMock(side_effect=MyException)
self.assertRaises(LockError, self.conf.lock)
def test_config_unlock(self):
self.conf.rpc.unlock_configuration = MagicMock()
self.assertTrue(self.conf.unlock())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_config_unlock_LockError(self, mock_jxml):
ex = RpcError(rsp='ok')
self.conf.rpc.unlock_configuration = MagicMock(side_effect=ex)
self.assertRaises(UnlockError, self.conf.unlock)
@patch('jnpr.junos.utils.config.JXML.remove_namespaces')
def test_config_unlock_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.unlock_configuration = MagicMock(side_effect=MyException)
self.assertRaises(UnlockError, self.conf.unlock)
示例12: TestConfig
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [as 别名]
#.........这里部分代码省略.........
ex = RpcTimeoutError(self.dev, None, 10)
self.conf.rpc.load_config = MagicMock(side_effect=ex)
self.assertRaises(RpcTimeoutError, self.conf.load, path='config.conf')
@patch(builtin_string + '.open')
def test_config_try_load_exception(self, mock_open):
class OtherException(Exception):
pass
self.conf.rpc.load_config = MagicMock(side_effect=OtherException())
self.assertRaises(OtherException, self.conf.load, path='config.conf')
@patch('jnpr.junos.utils.config.etree.XML')
def test_config_load_template_path(self, mock_etree):
self.conf.rpc.load_config = MagicMock()
self.conf.dev.Template = MagicMock()
self.conf.load(template_path='test.xml')
self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'],
'xml')
def test_config_load_template(self):
class Temp:
filename = 'abc.xml'
render = MagicMock(return_value='<test/>')
self.conf.rpc.load_config = MagicMock()
self.conf.load(template=Temp)
self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'],
'xml')
def test_config_diff_exception(self):
self.conf.rpc.get_configuration = MagicMock()
self.assertRaises(ValueError, self.conf.diff, 51)
self.assertRaises(ValueError, self.conf.diff, -1)
def test_config_lock(self):
self.conf.rpc.lock_configuration = MagicMock()
self.assertTrue(self.conf.lock())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_config_lock_LockError(self, mock_jxml):
ex = RpcError(rsp='ok')
self.conf.rpc.lock_configuration = MagicMock(side_effect=ex)
self.assertRaises(LockError, self.conf.lock)
@patch('jnpr.junos.utils.config.JXML.remove_namespaces')
def test_config_lock_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.lock_configuration = MagicMock(side_effect=MyException)
self.assertRaises(LockError, self.conf.lock)
def test_config_unlock(self):
self.conf.rpc.unlock_configuration = MagicMock()
self.assertTrue(self.conf.unlock())
@patch('jnpr.junos.utils.config.JXML.rpc_error')
def test_config_unlock_LockError(self, mock_jxml):
ex = RpcError(rsp='ok')
self.conf.rpc.unlock_configuration = MagicMock(side_effect=ex)
self.assertRaises(UnlockError, self.conf.unlock)
@patch('jnpr.junos.utils.config.JXML.remove_namespaces')
def test_config_unlock_exception(self, mock_jxml):
class MyException(Exception):
xml = 'test'
self.conf.rpc.unlock_configuration = MagicMock(side_effect=MyException)
self.assertRaises(UnlockError, self.conf.unlock)
示例13: provision_services
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [as 别名]
def provision_services():
name = request.form.get('name')
ip_address = request.form.get('ip_address')
campus_user = request.form.get('campus_user')
service2 = request.form.get('service2')
service3 = request.form.get('service3')
service4 = request.form.get('service4')
service5 = request.form.get('service5')
campus = request.form.get('campus')
internet_user = request.form.get('internet_user')
legacy = request.form.get('legacy')
provisioned_services = ''
provisioned_services += Markup('''\
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body><center>
Provisioned - <br>''')
if campus_user:
dev = Device(host='172.25.45.68', user='lab', passwd='jnpr123')
cu = Config(dev)
print name, ip_address
try:
dev.open()
dev.timeout = 300
cu.lock()
jinja_input = {'Address': ip_address, 'var1': name}
jinja_data = open("jinjafile.conf", "wb")
jinja_data.write(JinjaTemplate_Campus.render(**jinja_input))
jinja_data.close()
rsp = cu.load( template_path="jinjafile.conf", merge=True )
cu.commit()
cu.unlock()
except RpcError:
msg = "{0} was Skipped due to RPC Error. Device is not a Juniper SRX Series"
print msg
dev.close()
except Exception as err:
msg = "{0} was skipped due to unhandled exception.\n{1}"
print msg
traceback.print_exc(file=sys.stdout)
dev.close()
provisioned_services += Markup('''Campus User: '''+name+''' with IP Address:'''+ip_address+'''<br>''')
if internet_user:
dev = Device(host='172.25.45.68', user='lab', passwd='jnpr123')
cu = Config(dev)
print name, ip_address
try:
dev.open()
dev.timeout = 300
cu.lock()
jinja_input = {'Address': ip_address, 'var1': name}
jinja_data = open("jinjafile.conf", "wb")
jinja_data.write(JinjaTemplate_Internet.render(**jinja_input))
jinja_data.close()
rsp = cu.load( template_path="jinjafile.conf", merge=True )
cu.commit()
cu.unlock()
except RpcError:
msg = "{0} was Skipped due to RPC Error. Device is not a Juniper SRX Series"
print msg
dev.close()
except Exception as err:
msg = "{0} was skipped due to unhandled exception.\n{1}"
print msg
traceback.print_exc(file=sys.stdout)
dev.close()
provisioned_services += Markup('''Internet User'''+name+''' with IP Address: '''+ip_address+'''<br>''')
if legacy:
provisioned_services += Markup('''Legacy<br>''')
if service2:
provisioned_services += Markup('''Service 2<br>''')
if service3:
provisioned_services += Markup('''Service 3<br>''')
if service4:
provisioned_services += Markup('''Service 4<br>''')
if service5:
provisioned_services += Markup('''Service 5<br>''')
if campus:
provisioned_services += Markup('''Campus<br>''')
provisioned_services += Markup('''<button type="button" name="button" class="btn btn-primary btn-lg" onClick="location.href='../'" enabled><strong>Return to Main Page</strong></button><br>''')
provisioned_services += Markup('''</body></html>''')
#.........这里部分代码省略.........
示例14: get_user_info
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [as 别名]
password = get_user_info()
# Create object with ip_address, user and password
lines = open(filename).readlines()
for line in lines:
hostname = line.strip()
log("Juniper Device name:%s,configuration file:%s" %(hostname,args.commands))
ip = resolve_host(hostname)
if ip:
juniper_device = Device(host=ip,user=os.getenv("USER"),password=password,port='22')
# open the device defined instance
juniper_device.open()
# open configuration method
config = Config(juniper_device)
# open configuration lock method allowing only one configuration
try:
config.lock()
except LockError:
print "Error: Unable to lock configuration"
juniper_device.close()
sys.exit(0)
# rollback any configuration that might be in candidate configuration
config.rollback(0)
try:
config.load(path=args.commands, format=args.configuration_choice,
merge="True")
# Merge = "False" would implies a replace action. A
# replace action, however, requires that the configuration file have a
# 'replace:' statement in it print configuration diff from devices
# perspective. To load a jinja template:
# cu.load(template_path=conf_file, template_vars=config, merge=True)
except ValueError as err:
示例15: provision
# 需要导入模块: from jnpr.junos.utils.config import Config [as 别名]
# 或者: from jnpr.junos.utils.config.Config import lock [as 别名]
def provision(host, **kwargs):
# host = kwargs['host']
username = kwargs["username"]
password = kwargs["password"]
port = kwargs["port"]
compareconfig = kwargs["compareconfig"]
configuration = kwargs["configuration"]
waitconfirm = kwargs[b"waitconfirm"]
print colored("-------------------------------------------------------------------------------\n", "yellow")
print colored("Start committing configuration to: ", "cyan") + colored("%s" % host["address"], "yellow")
logging.info("Start committing configuration to %s" % host["address"])
dev = Device(
host=host["address"],
username=username,
password=password,
port=port,
timeout=5,
device_params={"name": "junos"},
hostkey_verify=False,
)
try:
logging.info("Connecting to %s" % host)
# logging.debug("Connecting to %s" % host)
dev.open()
except jnpr.junos.exception.ConnectAuthError as err:
logging.info("Wrong username or password while connecting to %s." % host["address"])
print colored("Wrong username or password while connecting to %s.", "red") % host["address"]
host["status"] = CONNECTION_FAILED
return
except jnpr.junos.exception.ConnectUnknownHostError as err:
logging.info("Wrong hostname: %s." % host["address"])
print "Host: " + colored("%s" % host["address"], "red") + " not found. Wrong FQDN?"
host["status"] = CONNECTION_FAILED
return
except jnpr.junos.exception.ConnectRefusedError as err:
logging.info("NETCONF session to %s failed." % host["address"])
print "Host: " + colored("NETCONF session to %s failed", "red") % host["address"]
host["status"] = CONNECTION_FAILED
return
except jnpr.junos.exception.ConnectTimeoutError as err:
logging.info("Time-out error. Could not open socket to: %s." % host["address"])
print "Time-out error. Could not open socket to : " + colored("%s" % host["address"], "red")
host["status"] = CONNECTION_FAILED
return
# Create an instance of Config
cu = Config(dev)
logging.debug("Acquiring lock to %s." % host)
# lock the device
try:
cu.lock()
except jnpr.junos.exception.LockError as err:
logging.info("Error: unable to lock configuration in %s." % host["address"])
print colored("Error: unable to lock configuration in %s", "red") % host["address"]
host["status"] = UNABLE_TO_LOCK
dev.close()
return
# parse configuration file and load commands. Handle exceptions accordingly
for line in configuration:
if line[0] != "#":
logging.debug("Loading command: %s in %s " % (line.rstrip("\n"), host["address"]))
try:
cu.load(line, format="set", merge=False)
except jnpr.junos.exception.ConfigLoadError as err:
logging.info(
"Failed loading command '%s' with severity %s in %s."
% (line.rstrip("\n"), err.errs["severity"], host["address"])
)
print colored("Loading command failed with severity: %s", "red") % err.errs["severity"]
host["status"] = COMMIT_FAILED_WARNING
if err.errs["severity"] == "error":
cu.rollback()
logging.info("Commit failed. Rolling back in %s and exiting the script" % host["address"])
logging.debug("Commit failed with %s rolling back in %s" % (err, host["address"]))
print colored("Exiting, configuration rolled-back", "red")
host["status"] = COMMIT_FAILED_ERROR
cu.unlock()
dev.close()
sys.exit(1)
# print "show|compare" results to stdout if requested
if compareconfig != "true":
print colored("\n'show | compare' output:", "blue")
print cu.diff()
if waitconfirm == b"true":
if kwargs["first_host"] == b"true":
ack = raw_input("Proceed with commiting? [y/n]: ")
else:
ack = "yes"
else:
ack = "yes"
if ack == "y" or ack == "yes":
try:
#.........这里部分代码省略.........