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
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"
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.") 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, "dsconnecting 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
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
def set_port_default(dev): vlan_numbers_list = [] vlan_id_dict = get_vlan_dict(dev) for k, v in vlan_id_dict.items(): if v[2][1] == 'l2ng-l2rtb-vlan-member-interface': continue else: if isinstance(v[2][1], list): for i in v[2][1]: if i.rstrip('*').find(parser.parse_args().port[0]): vlan_numbers_list.append(k) config_vars = { 'interface': parser.parse_args().port[0], 'units': set(vlan_numbers_list) } config_file = "templates/junos-config-port-default.conf" cu = Config(dev, mode='private') cu.load(template_path=config_file, template_vars=config_vars, replace=True, format='set', ignore_warning=True) cu.pdiff() apply_config(dev, cu)
class Jconfig: def __init__(self, host, user='******', password='******', 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
def provision(conn, junosConfig, config_format): log.debug("entered provision") log.debug("config mode set to %s", config_format) loadResult = None if (conn == None): log.error("the NETCONF session to the router is not open") return False if (junosConfig == None): log.error("no configuration found") return False log.debug("instantiating config object ...") co = Config(conn) try: if (config_format == "xml"): loadResult = co.load(junosConfig, "xml") elif (config_format == "text"): loadResult = co.load(junosConfig, "text") elif (config_format == "set"): loadResult = co.load(junosConfig, "set") if (loadResult): if (co.commit_check()): print("the configuration has been validated") print("") print("presenting the diff:") print("") co.pdiff() print("") print("committing the configuration ...") print("") co.commit() return True else: return False except Exception as e: log.error("could not provision the router") log.error(e.message) log.error("rolling back the configuration ...") co.rollback() return False
def main(): try: enable_password = get_password() config_file_data = read_config_file(args.config) if args.routers != None: multiple_routers_to_apply_config = read_file_multiple_routers( args.routers) print multiple_routers_to_apply_config for i in multiple_routers_to_apply_config: connect_to_devices = connect_to_router(i, args.username, enable_password) cu = Config(connect_to_devices) cu.load(config_file_data, format='text') print 'pushing config to {}'.format(i) cu.pdiff() connect_to_devices.open() commit_check_config = cu.commit_check() commitconfig(commit_check_config, i, args.username, enable_password) else: connect_to_devices = connect_to_router(args.device, args.username, enable_password) cu = Config(connect_to_devices) cu.load(config_file_data, format='text') cu.pdiff() connect_to_devices.open() commit_check_config = cu.commit_check() commitconfig(commit_check_config, args.device, args.username, enable_password) except ConnectAuthError as e: print e except ConnectRefusedError as e: print e except ConnectTimeoutError as e: print e except ConnectError as e: print e except LockError as e: print e except PermissionError as e: print e except UnlockError as e: print e except CommitError as e: print e except ConfigLoadError as e: print e
def main(): try: with Device(user=UNAME, passwd=PW, mode='serial', port="/dev/ttyUSB0", gather_facts=False, timeout=10) as EXdev: print( "...Checking connection ...\n...............................\n...Connection established: {checkit}" .format(checkit=EXdev.connected)) print(EXdev.cli("show version", format='text', warning=False)) cfg = Config(EXdev) start_time = time.time() cfg.lock() #cfg.load('delete', format='set') #cfg.load('set system host-name TEMP', format='set') #cfg.load('set system root-authentication encrypted-password "$1$MuK2KPdi$YZbi17SXuxiN7D3gCzkPq/"', format='set') #cfg.load('set system services netconf traceoptions file xyz', format='set') #cfg.commit(comment="****** Errazing the factory config done******", timeout=10) #cfg.pdiff() #cfg.lock() cfg.load(path=CONFIG_FILE, merge=True) cfg.pdiff() cfg.commit_check() print("Pushing the commit command...") cfg.commit(timeout=15) cfg.unlock() print("Commit completed...") #print(EXdev.cli("show configuration | no-more", format='text', warning=False)) print( "Closing connection to device ...\nThe loading has been completed in {sec} seconds" .format(sec=time.time() - start_time)) #dev.close() except ConnectError as err: print("{t} Cannot connect to device: {e}".format(t=time.asctime(), e=err)) sys.exit(1) except ConfigLoadError as err: print("{t} Unable to load the configuration due to: {e}".format( t=time.asctime(), e=err)) sys.exit(1) except Exception as err: print("{t} --+== {e} ==+--".format(t=time.asctime(), e=err)) sys.exit(1)
def loadVRFConfig(VRF_number): if 1 < int(VRF_number) < 255: dev = Device(host="172.2.3.5", user="******", ssh_private_key_file="/root/.ssh/VRF") dev.open() conf = Config(dev) variables = {} variables["VRF_instance"] = VRF_number conf.load(template_path="templateVRF_set.conf", template_vars=variables, format="set", merge=True) conf.pdiff() if conf.commit_check(): print "This config would commit succesfully" else: print "Config puck`d up" dev.close() else: print "The VRF number must be between 2 and 254"
def main(): vmx7 = { 'host': '54.69.184.104', 'user': '******', 'password': '******', } parser = argparse.ArgumentParser() #parser.add_argument("--config", help="Configuration file") parser.add_argument("--json", help="JSON file") args = parser.parse_args() config = json_to_junos(args.json) dev = Device(**vmx7) dev.open() cfg = Config(dev) cfg.load(config, format="text", merge=True) cfg.pdiff()
def interface_deactivate(iface, **kwargs): r = requests.get('http://config-server:9000/api/v2/config/device/%s/' % kwargs['device_id'], verify=False) device_info = r.json() hostname = device_info['host'] userid = device_info['authentication']['password']['username'] password = device_info['authentication']['password']['password'] with Device(host=hostname, user=userid, passwd=password) as dev: conf = """ interfaces { /* Disabled automatically by Healthbot server after aggressive flap */ %s { disable; } } """ % iface cu = Config(dev) cu.load(conf) cu.pdiff() cu.commit()
def create_irb_and_policer(dev): import netaddr from lxml import etree policer_present = 0 policer_config = dev.rpc.get_config(filter_xml=etree.XML( '<configuration><firewall><policer></policer></firewall></configuration>' ), options={'source': 'running'}, normalize=True) for node in policer_config.xpath(".//name"): if node.text == 'car-' + parser.parse_args().policer[0]: policer_present = 1 ip = netaddr.IPNetwork(parser.parse_args().address[0]) config_vars = { 'vlan_id': parser.parse_args().vlan[0], 'ip_address': '{}/{}'.format( ip.ip.__str__() if ip.ip.__str__() != ip.network.__str__() else ip[1].__str__(), ip.prefixlen.__str__()), 'policer_precence': policer_present, 'policer_name': parser.parse_args().policer[0], 'description': parser.parse_args().descr[0] } config_file = "templates/junos-config-irb.conf" cu = Config(dev, mode='private') cu.load(template_path=config_file, template_vars=config_vars, replace=True, format='set', ignore_warning=True) cu.pdiff() apply_config(dev, cu)
def del_vlan(dev): vlan_port_list = [] vlan_id_dict = get_vlan_dict(dev, strict=1) for k, v in vlan_id_dict.items(): if v[2][1] == 'l2ng-l2rtb-vlan-member-interface': continue else: vlan_port_list.append(v[2][1].rstrip('*')) config_vars = { 'interfaces': vlan_port_list, 'vlan': parser.parse_args().vlan[0] } config_file = "templates/junos-config-delete-vlans.conf" cu = Config(dev, mode='private') cu.load(template_path=config_file, template_vars=config_vars, replace=True, format='set', ignore_warning=True) cu.pdiff() apply_config(dev, cu)
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": "******", "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
def JunosConn(configs): mxs = { # Declaring Juniper device details 'host': '192.168.10.1', 'user': '******', 'password': '******', } dev = Device(**mxs) dev.open() print() print( yaml.dump(dev.facts) ) # Printing device facts such as model, serial number, version etc... print("Facts in json format:") print(json.dumps(dev.facts)) cfg = Config(dev) cfg.load(configs, format="text", merge=True) # Pushing configurations over the device cfg.pdiff() cfg.commit()
def add_vlan_and_port(dev): from jnpr.junos.op.ethport import EthPortTable ports_dict = {} eths = EthPortTable(dev).get() for port in eths: ports_dict[port.name] = port.description uplinks = [ k for k, v in ports_dict.items() if v != None and v.startswith('TRUNK') ] config_vars = { 'uplinks': uplinks, 'client_port': [parser.parse_args().port[0]], 'interfaces': uplinks + [parser.parse_args().port[0]], 'vlan': parser.parse_args().vlan[0], 'trunk_bool': parser.parse_args().tag } config_file = "templates/junos-config-add-vlans.conf" cu = Config(dev, mode='private') cu.load(template_path=config_file, template_vars=config_vars, replace=True) cu.pdiff() apply_config(dev, cu)
def Main(input, dev): cu = Config(dev) logging.info(json.dumps(input)) filter = '<configuration><interfaces/></configuration>' data = dev.rpc.get_config(filter_xml=filter, options={ 'format': 'json' }) ##get the running interface config from the device with json format config_list = [] disabled_interfaces = [] ## put the ae interface with "disable" but without "unit" into a list, create config with the ae interface name for i in data['configuration']['interfaces']['interface']: if ("ae" in i['name']) and ("disable" in i.keys()) and ("unit" not in i.keys()): disabled_interfaces.append(i['name']) config_list.append("delete interfaces {0} disable".format( i['name'])) config_str = "\n".join(config_list) if len(config_str): cross_check = True print("checking admin status of the interfaces:") ## get the interface admin status to cross check, if the status is not "down", break and return False for i in disabled_interfaces: int_status = dev.rpc.get_interface_information( {'format': 'json'}, interface_name=i, terse=True)['interface-information'][0]['physical-interface'][ 0]['admin-status'][0]['data'] print(i + " : " + int_status) if int_status != "down": cross_check = False print( "there is some discrepancy between interfaces config of {0} and interfaces status" .format(i)) break ##if cross check succeded , push the config to the device if cross_check: config_load = cu.load(config_str, format='set') print( etree.tostring(config_load, encoding='unicode', pretty_print=True)) print("Config diff:") print(cu.pdiff()) commit_result = cu.commit(timeout=30) print("Commit Succeeded: " + str(commit_result)) return commit_result else: return False else: print("there is no empty disabled ae interface on this device") return True
def main(): pwd = getpass() a_device = Device(host='184.105.247.76', user='******', password=pwd) a_device.open() print "\n***** Device Facts *****\n" pprint(a_device.facts) print "\n***** Config Change...****\n" cfg = Config(a_device) cfg.lock() print "Config is locked..." cfg.load(path='srx_hostname.conf', format='text', merge=True) print "Config change is uploaded.." cfg.pdiff() answer = raw_input("Do you want to rollback(y/n): ") if answer in ['y', 'Y', 'yes', 'YES']: print "Rollback is in progress..." cfg.rollback(0) cfg.commit() cfg.pdiff() else: pass cfg.unlock()
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): 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)
list = read_data.split() set_cmd = """ """ for x in range (0, len(list)): set_cmd += ("set policy-options prefix-list PXL-CUSTOMERS " + list[x] + "\n") U="netconfuser" P="netconf123" ROUTERS = ["192.0.2.1", "192.0.2.2", "192.0.2.3"] for device in ROUTERS: dev = Device(device, port=830, user=U, password=P) dev.open() conf = Config(dev) conf.lock() conf.load(set_cmd, format='set') print('Updating ACME-' + dev.facts['hostname'] + ' | ' + device) conf.pdiff() if conf.commit_check(): conf.commit() else: conf.rollback() conf.unlock() dev.close()
#! /usr/bin/env python from jnpr.junos.device import Device from jnpr.junos.utils.config import Config dev = Device(host='20.0.2.31',user='******',password='******') dev.open() cu = Config(dev) print cu.load(path="/home/hans/git/juniper/juniper/manual_file.set", format='set') print cu.pdiff() dev.close()
def push_conf_func(config): """ This code will first access the remote router via SSH and then use Juniper Pyez to push config """ # print("Trying to access router now......") try: a_device = Device(host="66.129.235.11", user="******", password="******", port="39000") a_device.open() cfg = Config(a_device) print("SSH access to Remote Router successful..") except Exception as e: print(e) print("Error while attempting ssh connection to server") quit() # sys.exit('Error while attempting ssh connection to server') #check router diff before pushing new config if cfg.diff() is None: print("Locking remote router now...") cfg.lock() else: print( "There are some pending diffs to be pushed on remote router. Please review and push. See Below----" ) print(cfg.pdiff()) print("Bye. See you again!!") a_device.close() sys.exit() f1 = open('conf-to-push.conf', 'w') f1.write(config) f1.close() print("\n") print("Below config is now being loaded to remote router") print('~' * 60) print(config) print('~' * 60) print("\n") try: cfg.load(path='conf-to-push.conf', format='set', merge=True) except ConfigLoadError as e: print(e) a_device.close() sys.exit("Error while loading config") print("Please review the diffs carefully") print('~' * 60) pprint(cfg.pdiff()) print('~' * 60) try: diff_push_input = input( "Are these diffs good to be pushed to running config? - Say 'yes or 'no': " ).strip().lower() if (diff_push_input == 'yes'): try: if cfg.commit_check() is True: cfg.commit() print("\nYour config is committed now.\n") else: print(cfg.commit_check()) except Exception as e: print(e) print("Exception while doing commit check") else: print( "\nAlright.. Config is being rolled back now to last pushed config\n" ) cfg.rollback(0) a_device.close() exit(1) except Exception as e: print(e) print("Error in processing commit code") print("Unlocking Remote router now....BYE!!\n") cfg.unlock() a_device.close() exit(1)
#----------------------------------------------------------------------------------------------------------------------- # DESCRIPTION: # Use PyEZ to enable LLDP on a subset of interfaces for a specific device. # # CONTACT: [email protected]; [email protected]; [email protected]; [email protected]; [email protected] # # CREATED: 2015-11-11 # # VERSION: 1 # # USAGE: enable_lldp.py # ----------------------------------------------------------------------------------------------------------------------- from jnpr.junos import Device # import the class Device from jnpr.junos.utils.config import Config # import the class Config import yaml s=open('configuration_management/interfaces.yml').read() #s is a string my_variables=yaml.load(s) # my_variables is a dictionary a_device=Device (host="172.30.179.113", user="******", password="******") a_device.open() cfg=Config(a_device) # cfg is the candidate configuration cfg.rollback() cfg.load(template_path='configuration_management/template_lldp.j2', template_vars=my_variables, format='set') cfg.pdiff() cfg.commit()
#pprint( device.facts ) device.bind(cfg=Config) try: device.rpc.open_configuration(private=True) except jnpr.junos.exception.RpcError as e: if 'severity: warning' in str(e): print str(e) pass else: raise for line in open("fila"): elhay = Config(device) set_cmd = line elhay.load(set_cmd, format='set') elhay.pdiff() elhay.commit() #for line in open("fila"): # print device.cli(line) #device.cfg.load(template_path=template, template_vars=customer) #device.bind(cu=Config) #device.rpc.open_configuration(private=True,normalize=True) #device.cu.load("set system host-name r0") #device.cu.commit() #device.rpc.close_configuration()
print("#"*10) print("设备:{}, ip地址:{}".format(name,ip)) print("#"*10) vSRX=Device(host=ip,user="******",passwd="juniper123").open() vSRX_config=Config(vSRX,mode="exclusive") print("#"*10) print("以下配置将被导入进设备{}:".format(name)) print("#"*10) for each in final_config[name]: print(each) vSRX_config.load(each,format="set") if vSRX_config.diff() == None: print("无新增配置,连接关闭!") vSRX.close() else: print("{} show | compare输出内容如下,请确认:".format(name)) vSRX_config.pdiff() yes_no=input("请输入yes 或者 no 来确定是否提交上述配置:") while not(yes_no=="yes" or yes_no=="no") print("输入错误,请重新输入yes或者no!") yes_no=input("请输入yes 或者 no 来确定是否提交上述配置:") if yes_no=="yes": vSRX_config.commit(comment="add ospf adn security config bu PyEZ",timeout=60) vSRX.close() else: print("连接关闭,谢谢!") vSRX.close()
class TestConfig(unittest.TestCase): @patch("ncclient.manager.connect") def setUp(self, mock_connect): mock_connect.side_effect = self._mock_manager self.dev = Device(host="1.1.1.1", user="******", password="******", gather_facts=False) self.dev.open() self.conf = Config(self.dev) @patch("ncclient.operations.session.CloseSession.request") def tearDown(self, mock_session): self.dev.close() def test_config_constructor(self): self.assertTrue(isinstance(self.conf._dev, Device)) def test_config_confirm_true(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(confirm=True) self.conf.rpc.commit_configuration.assert_called_with(confirmed=True) def test_config_commit_confirm(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") def test_config_commit_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(sync=True) self.conf.rpc.commit_configuration.assert_called_with(synchronize=True) def test_config_commit_force_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(force_sync=True) self.conf.rpc.commit_configuration.assert_called_with( **{ "synchronize": True, "force-synchronize": True }) def test_config_commit_timeout(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(timeout=60) self.conf.rpc.commit_configuration.assert_called_with(dev_timeout=60) def test_config_commit_full(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(full=True) self.conf.rpc.commit_configuration.assert_called_with(full=True) def test_config_commit_detail(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = "<mockdetail/>" self.assertEqual("<mockdetail/>", self.conf.commit(detail=True)) self.conf.rpc.commit_configuration.assert_called_with( {"detail": "detail"}) def test_config_commit_combination(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = "<moredetail/>" self.assertEqual( "<moredetail/>", self.conf.commit(detail=True, force_sync=True, full=True)) self.conf.rpc.commit_configuration.assert_called_with( {"detail": "detail"}, **{ "synchronize": True, "full": True, "force-synchronize": True }) @patch("jnpr.junos.utils.config.JXML.remove_namespaces") def test_config_commit_xml_exception(self, mock_jxml): class MyException(Exception): xml = etree.fromstring("<test/>") self.conf.rpc.commit_configuration = MagicMock(side_effect=MyException) self.assertRaises(CommitError, self.conf.commit) def test_config_commit_exception(self): class MyException(Exception): pass self.conf.rpc.commit_configuration = MagicMock(side_effect=MyException) self.assertRaises(MyException, 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): class MyException(Exception): xml = etree.fromstring(""" <rpc-reply> <rpc-error> <error-type>protocol</error-type> <error-tag>operation-failed</error-tag> <error-severity>error</error-severity> <error-message>permission denied</error-message> <error-info> <bad-element>system</bad-element> </error-info> </rpc-error> </rpc-reply> """) self.conf.rpc.commit_configuration = MagicMock(side_effect=MyException) # with self.assertRaises(AttributeError): self.assertDictEqual( self.conf.commit_check(), { "source": None, "message": "permission denied", "bad_element": "system", "severity": "error", "edit_path": None, }, ) 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" }, ignore_warning=False, ) 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) def test_config_diff_rpc_timeout(self): ex = RpcTimeoutError(self.dev, None, 10) self.conf.rpc.get_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.diff) 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") def test_config_load_len_with_format_text(self): self.conf.rpc.load_config = MagicMock(return_value="rpc_contents") textdata = """policy-options { prefix-list TEST1-NETS { 100.0.0.0/24; } policy-statement TEST1-NETS { term TEST1 { from { prefix-list TEST1-NETS; } then accept; } term REJECT { then reject; } } }""" self.assertEqual(self.conf.load(textdata), "rpc_contents") def test_config_load_with_format_json(self): self.conf.rpc.load_config = MagicMock( return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load("test.json", format="json") self.assertEqual(op.tag, "load-configuration-results") self.assertEqual(self.conf.rpc.load_config.call_args[1]["format"], "json") @patch(builtin_string + ".open") def test_config_load_with_format_json_from_file_ext(self, mock_open): self.conf.rpc.load_config = MagicMock( return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load(path="test.json") self.assertEqual(op.tag, "load-configuration-results") self.assertEqual(self.conf.rpc.load_config.call_args[1]["format"], "json") @patch(builtin_string + ".open") def test_config_load_update(self, mock_open): self.conf.rpc.load_config = MagicMock( return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load(path="test.conf", update=True) self.assertEqual(op.tag, "load-configuration-results") self.assertEqual(self.conf.rpc.load_config.call_args[1]["format"], "text") def test_config_load_update_merge_overwrite(self): self.assertRaises( ValueError, self.conf.load, path="test.jnpr", update=True, merge=True, overwrite=True, ) @patch(builtin_string + ".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_string + ".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_string + ".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_string + ".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") @patch(builtin_string + ".open") def test_config_load_try_load_rpcerror(self, mock_open): ex = ConfigLoadError( rsp=etree.fromstring(("""<load-configuration-results> <rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error> </load-configuration-results>"""))) self.conf.rpc.load_config = MagicMock(side_effect=ex) self.assertRaises(ConfigLoadError, self.conf.load, path="config.conf") @patch(builtin_string + ".open") def test_config_load_try_load_rpctimeouterror(self, mock_open): 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.rpc_error") def test_config_lock_ConnectClosedError(self, mock_jxml): ex = ConnectClosedError(dev=self) self.conf.rpc.lock_configuration = MagicMock(side_effect=ex) self.assertRaises(ConnectClosedError, 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.rpc_error") def test_config_unlock_ConnectClosedError(self, mock_jxml): ex = ConnectClosedError(dev=self) self.conf.rpc.unlock_configuration = MagicMock(side_effect=ex) self.assertRaises(ConnectClosedError, 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) @patch("jnpr.junos.Device.execute") def test_rescue_action_save(self, mock_exec): self.dev.request_save_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue("save")) @patch("jnpr.junos.Device.execute") def test_rescue_action_get_exception(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock(side_effect=Exception) self.assertTrue(self.conf.rescue("get") is None) @patch("jnpr.junos.Device.execute") def test_rescue_action_get(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock() self.dev.rpc.get_rescue_information.return_value = 1 self.assertEqual(self.conf.rescue("get", format="xml"), 1) @patch("jnpr.junos.Device.execute") def test_rescue_action_delete(self, mock_exec): self.dev.rpc.request_delete_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue("delete")) @patch("jnpr.junos.Device.execute") def test_rescue_action_reload(self, mock_exec): self.dev.rpc.load_configuration = MagicMock() self.dev.rpc.load_configuration.return_value = True self.assertTrue(self.conf.rescue("reload")) @patch("jnpr.junos.Device.execute") def test_rescue_action_reload_exception(self, mock_exec): self.dev.rpc.load_configuration = MagicMock(side_effect=Exception) self.assertFalse(self.conf.rescue("reload")) @patch("jnpr.junos.Device.execute") def test_rescue_action_unsupported_action(self, mock_exec): self.assertRaises(ValueError, self.conf.rescue, "abc") def test_config_load_lset_from_rexp_xml(self): self.conf.rpc.load_config = MagicMock() conf = """<snmp><name>iBGP</name></snmp>""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["format"], "xml") def test_config_load_lset_from_rexp_json(self): self.conf.rpc.load_config = MagicMock() conf = """{ "configuration" : { "system" : { "services" : { "telnet" : [null] } } } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["format"], "json") def test_config_load_lset_from_rexp_set(self): self.conf.rpc.load_config = MagicMock() conf = """set system domain-name englab.nitin.net""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_delete(self): self.conf.rpc.load_config = MagicMock() conf = """delete snmp""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_rename(self): self.conf.rpc.load_config = MagicMock() conf = """rename firewall family inet filter f1 to filter f2""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_insert(self): self.conf.rpc.load_config = MagicMock() conf = """insert policy-options policy-statement hop term 10 after 9""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_activate(self): self.conf.rpc.load_config = MagicMock() conf = """activate system services ftp""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_deactivate(self): self.conf.rpc.load_config = MagicMock() conf = """deactivate system services ftp""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_annotate(self): self.conf.rpc.load_config = MagicMock() conf = """annotate system \"Annotation test\"""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_copy(self): self.conf.rpc.load_config = MagicMock() conf = """copy firewall family inet filter f1 to filter f2""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_protect(self): self.conf.rpc.load_config = MagicMock() conf = """protect system services""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_set_unprotect(self): self.conf.rpc.load_config = MagicMock() conf = """unprotect system services""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "set") def test_config_load_lset_from_rexp_conf(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["format"], "text") def test_config_load_lset_from_rexp_conf_replace_tag(self): self.conf.rpc.load_config = MagicMock() conf = """replace: snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]["format"], "text") self.assertEqual(self.conf.rpc.load_config.call_args[1]["action"], "replace") def test_config_load_lset_from_rexp_error(self): self.conf.rpc.load_config = MagicMock() conf = """test>""" self.assertRaises(RuntimeError, self.conf.load, conf) def test_load_merge_true(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf, merge=True) self.assertFalse("action" in self.conf.rpc.load_config.call_args[1]) def test_commit_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit) def test_commit_check_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit_check) def test_commit_configuration_multi_rpc_error(self): self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager) try: self.dev.rpc.commit_configuration() except Exception as ex: self.assertTrue(isinstance(ex, RpcError)) self.assertEqual( ex.message, "error: interface-range 'axp' is not defined\n" "error: interface-ranges expansion failed", ) self.assertEqual( ex.errs, [ { "source": None, "message": "interface-range 'axp' is not defined", "bad_element": None, "severity": "error", "edit_path": None, }, { "source": None, "message": "interface-ranges expansion failed", "bad_element": None, "severity": "error", "edit_path": None, }, ], ) @patch("jnpr.junos.utils.config.Config.lock") @patch("jnpr.junos.utils.config.Config.unlock") def test_config_mode_exclusive(self, mock_unlock, mock_lock): with Config(self.dev, mode="exclusive") as conf: conf.rpc.load_config = MagicMock() conf.load("conf", format="set") self.assertTrue(mock_lock.called and mock_unlock.called) @patch("jnpr.junos.Device.execute") def test_config_mode_batch(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode="batch") as conf: conf.load("conf", format="set") self.dev.rpc.open_configuration.assert_called_with(batch=True) @patch("jnpr.junos.Device.execute") def test_config_mode_private(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode="private") as conf: conf.load("conf", format="set") self.dev.rpc.open_configuration.assert_called_with(private=True) @patch("jnpr.junos.Device.execute") def test_config_mode_dynamic(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode="dynamic") as conf: conf.load("conf", format="set") self.dev.rpc.open_configuration.assert_called_with(dynamic=True) @patch("jnpr.junos.Device.execute") def test_config_mode_ephemeral_default(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode="ephemeral") as conf: conf.load("conf", format="set") self.dev.rpc.open_configuration.assert_called_with(ephemeral=True) @patch("jnpr.junos.Device.execute") def test_config_mode_ephemeral_instance(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode="ephemeral", ephemeral_instance="xyz") as conf: conf.load("conf", format="set") self.dev.rpc.open_configuration.assert_called_with( ephemeral_instance="xyz") def test_config_unsupported_kwargs(self): self.dev.rpc.open_configuration = MagicMock() try: with Config(self.dev, mode="ephemeral", xyz="xyz") as conf: conf.load("conf", format="set") except Exception as ex: self.assertEqual(str(ex), "Unsupported argument provided to Config class") @patch("jnpr.junos.Device.execute") def test_config_mode_close_configuration_ex(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() ex = RpcError(rsp="ok") ex.message = "Configuration database is not open" self.dev.rpc.close_configuration = MagicMock(side_effect=ex) try: with Config(self.dev, mode="batch") as conf: conf.load("conf", format="set") except Exception as ex: self.assertTrue(isinstance(ex, RpcError)) self.assertTrue(self.dev.rpc.close_configuration.called) def test_config_mode_undefined(self): try: with Config(self.dev, mode="unknown") as conf: conf.load("conf", format="set") except Exception as ex: self.assertTrue(isinstance(ex, ValueError)) @patch("jnpr.junos.Device.execute") @patch("jnpr.junos.utils.config.warnings") def test_config_mode_batch_open_configuration_ex(self, mock_warnings, mock_exec): rpc_xml = """ <rpc-error> <error-severity>warning</error-severity> <error-info><bad-element>bgp</bad-element></error-info> <error-message>syntax error</error-message> </rpc-error> """ rsp = etree.XML(rpc_xml) obj = RpcError(rsp=rsp) self.dev.rpc.open_configuration = MagicMock(side_effect=obj) with Config(self.dev, mode="batch") as conf: conf.load("conf", format="set") self.dev.rpc.open_configuration.assert_called_with(batch=True) @patch("jnpr.junos.Device.execute") @patch("jnpr.junos.utils.config.warnings") def test_config_mode_private_open_configuration_ex(self, mock_warnings, mock_exec): rpc_xml = """ <rpc-error> <error-severity>warning</error-severity> <error-info><bad-element>bgp</bad-element></error-info> <error-message>syntax error</error-message> </rpc-error> """ rsp = etree.XML(rpc_xml) obj = RpcError(rsp=rsp) self.dev.rpc.open_configuration = MagicMock(side_effect=obj) with Config(self.dev, mode="private") as conf: conf.load("conf", format="set") self.dev.rpc.open_configuration.assert_called_with(private=True) def test__enter__private_exception_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.conf.rpc.open_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, Config.__enter__, Config(self.dev, mode="private")) def test__enter__private_exception_RpcError(self): rpc_xml = """<rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error>""" rsp = etree.XML(rpc_xml) self.conf.rpc.open_configuration = MagicMock(side_effect=RpcError( rsp=rsp)) self.assertRaises(RpcError, Config.__enter__, Config(self.dev, mode="private")) def test__enter__dyanamic_exception_RpcError(self): rpc_xml = """<rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error>""" rsp = etree.XML(rpc_xml) self.conf.rpc.open_configuration = MagicMock(side_effect=RpcError( rsp=rsp)) self.assertRaises(RpcError, Config.__enter__, Config(self.dev, mode="dynamic")) def test__enter__batch_exception_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.conf.rpc.open_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, Config.__enter__, Config(self.dev, mode="batch")) def test__enter__batch_exception_RpcError(self): rpc_xml = """<rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error>""" rsp = etree.XML(rpc_xml) self.conf.rpc.open_configuration = MagicMock(side_effect=RpcError( rsp=rsp)) self.assertRaises(RpcError, Config.__enter__, Config(self.dev, mode="batch")) def test_config_load_url(self): self.conf.rpc.load_config = MagicMock() self.conf.load(url="/var/home/user/golden.conf") self.assertEqual(self.conf.rpc.load_config.call_args[1]["url"], "/var/home/user/golden.conf") @patch("jnpr.junos.Device.execute") def test_load_config_patch(self, mock_exec): conf = """[edit system] - host-name pakzds904; + host-name pakzds904_set; """ self.conf.load(conf, format="text", patch=True) self.assertEqual(mock_exec.call_args[0][0].tag, "load-configuration") self.assertEqual(mock_exec.call_args[0][0].attrib, { "format": "text", "action": "patch" }) @patch("jnpr.junos.Device.execute") def test_load_config_text(self, mock_exec): textdata = """policy-options { prefix-list TEST1-NETS { 100.0.0.0/24; } policy-statement TEST1-NETS { term TEST1 { from { prefix-list TEST1-NETS; } then accept; } term REJECT { then reject; } } }""" self.conf.load(textdata, overwrite=True) self.assertEqual(mock_exec.call_args[0][0].tag, "load-configuration") self.assertEqual(mock_exec.call_args[0][0].getchildren()[0].tag, "configuration-text") self.assertEqual(mock_exec.call_args[0][0].attrib, { "format": "text", "action": "override" }) def _read_file(self, fname): fpath = os.path.join(os.path.dirname(__file__), "rpc-reply", fname) foo = open(fpath).read() # specific to multi rpc error if fname == "commit-configuration.xml": raw = etree.XML(foo) obj = RPCReply(raw) obj.parse() raise RPCError(etree.XML(foo), errs=obj._errors) def _mock_manager(self, *args, **kwargs): if kwargs: device_params = kwargs["device_params"] device_handler = make_device_handler(device_params) session = SSHSession(device_handler) return Manager(session, device_handler) elif args: return self._read_file(args[0].tag + ".xml")
print(log) current = candidate if voip_source < 10: candidate = data[0] elif voip_source < 120: candidate = data[1] else: candidate = data[2] if current != candidate: conf1.lock() #блокировка конфигурации conf1.load( #загрузка новой конфигурации format='text', template_path=candidate, template_vars={'vlan': 14}, ignore_warning='statement not found') conf1.pdiff() #вывод изменений conf1.commit() #фиксация изменений conf1.unlock() #разблокировка конфигурации seconds += 1 except Exception as ex: print(f'{ex}\nExit') finally: dev1.close() dev2.close() log_file.close()
After each load(), display the differences between the running config and the candidate config. Additionally, perform at least one commit and one rollback(0) in this program. The committed hostname at the end of the program should be: pynet-jnpr-srx1 ''' from jnpr.junos import Device from jnpr.junos.utils.config import Config a_device = Device(host='184.105.247.76', user='******', password='******') a_device.open() cfg = Config(a_device) cfg.load("set system host-name foo", format="set", merge=True) print "Hostname Change using 'set' format:" print cfg.pdiff() print "*" * 80 print "Rollback candidate config" cfg.rollback(0) print cfg.pdiff() print "*" * 80 cfg.load(path="exercise4.conf", format="text", merge=True) print "Hostname Change using 'text' format:" print cfg.pdiff() print "*" * 80 print "Committing hostname change." cfg.commit(comment="Changing hostname to bar") cfg.load(path="exercise4.xml", format="xml", merge=True) print "Hostname Change using 'xml' format:"
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_true(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(confirm=True) self.conf.rpc.commit_configuration\ .assert_called_with(confirmed=True) def test_config_commit_confirm(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') def test_config_commit_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(synchronize=True) def test_config_commit_force_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(force_sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(**{'synchronize': True, 'force-synchronize': True}) def test_config_commit_timeout(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(timeout=60) self.conf.rpc.commit_configuration\ .assert_called_with(dev_timeout=60) def test_config_commit_full(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(full=True) self.conf.rpc.commit_configuration\ .assert_called_with(full=True) def test_config_commit_detail(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<mockdetail/>' self.assertEqual('<mockdetail/>', self.conf.commit(detail=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}) def test_config_commit_combination(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<moredetail/>' self.assertEqual('<moredetail/>', self.conf.commit(detail=True, force_sync=True, full=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}, **{'synchronize': True, 'full': True, 'force-synchronize': True}) @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() 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') 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') @patch('__builtin__.open') def test_config_load_try_load_rpcerror(self, mock_open): ex = ConfigLoadError( rsp=etree.fromstring(( """<load-configuration-results> <rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error> </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) 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) @patch('jnpr.junos.Device.execute') def test_rescue_action_save(self, mock_exec): self.dev.request_save_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('save')) @patch('jnpr.junos.Device.execute') def test_rescue_action_get_exception(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock(side_effect=Exception) self.assertTrue(self.conf.rescue('get') is None) @patch('jnpr.junos.Device.execute') def test_rescue_action_get(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock() self.dev.rpc.get_rescue_information.return_value = 1 self.assertEqual(self.conf.rescue('get', format='xml'), 1) @patch('jnpr.junos.Device.execute') def test_rescue_action_delete(self, mock_exec): self.dev.rpc.request_delete_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('delete')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload(self, mock_exec): self.dev.rpc.load_configuration = MagicMock() self.dev.rpc.load_configuration.return_value = True self.assertTrue(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload_exception(self, mock_exec): self.dev.rpc.load_configuration = MagicMock(side_effect=Exception) self.assertFalse(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_unsupported_action(self, mock_exec): self.assertRaises(ValueError, self.conf.rescue, 'abc') def test_config_load_lset_from_rexp_xml(self): self.conf.rpc.load_config = MagicMock() conf = """<snmp><name>iBGP</name></snmp>""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'xml') def test_config_load_lset_from_rexp_set(self): self.conf.rpc.load_config = MagicMock() conf = """set system domain-name englab.nitin.net""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_set_delete(self): self.conf.rpc.load_config = MagicMock() conf = """delete snmp""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_conf(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') def test_config_load_lset_from_rexp_conf_replace_tag(self): self.conf.rpc.load_config = MagicMock() conf = """replace: snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'replace') def test_config_load_lset_from_rexp_error(self): self.conf.rpc.load_config = MagicMock() conf = """nitin>""" self.assertRaises(RuntimeError, self.conf.load, conf) def test_load_merge_true(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf, merge=True) self.assertFalse('action' in self.conf.rpc.load_config.call_args[1]) def test_commit_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit)
def update_process(type,host,package,threadIns): # verify package exists if type=='OS' or type=='Firmware': if not (os.path.isfile(package)): msg = 'Software package does not exist: {0}. '.format(package) logging.error(msg) print msg sys.exit() time.sleep(20) dev=None dev = Device(host=host,user=junos_username, passwd=junos_password) rebootTime=10 rebootOK=False while not rebootOK: try: time.sleep(10) rebootOK=True dev.open() except Exception as err: print threadIns.hostIP+threadIns.serialNumber+':wait device time='+str(rebootTime)+"Sec "+str(err) logging.info(threadIns.hostIP+threadIns.serialNumber+':wait device time='+str(rebootTime)+"Sec "+str(err)) rebootTime+=10 rebootOK=False if rebootTime>=rebootTimeout: logging.error('Cannot connect to device\n') print 'Cannot connect to device\n' return if type=='createLogFile': threadIns.status="createLog" dev.timeout = 100 create_log(dev) dev.close() return if type=='checkSerialNumber': threadIns.status="checkSN" threadIns.serialNumber=dev.facts['serialnumber'] dev.close() return if type=='Snapshot': threadIns.status="Snapshot" dev.timeout = 600 dev.rpc.request_snapshot(slice='alternate') dev.close() return if type=='setFixIP': threadIns.status="setFixIP" cu = Config(dev) cu.load('delete interfaces ge-0/0/0', format='set') cu.load('set interfaces ge-0/0/0 unit 0 family inet address '+threadIns.hostIP+'/'+str(dhcpNetmask), format='set') cu.pdiff() cu.commit() return # Create an instance of SW sw = SW(dev) threadIns.status="install"+type try: logging.info('Starting the software upgrade process: {0}'.format(package)) okOS = sw.install(package=package, remote_path=remote_path,progress=update_progress, validate=validate) #okOS=True except Exception as err: msg = 'Unable to install software, {0}'.format(err) logging.error(msg) okOS = False if type=="Firmware": #UPGRADED SUCCESSFULLY logging.info("!!!!!!!!!!!!!") logging.info(dev.cli("request system firmware upgrade pic pic-slot 0 fpc-slot 1")) threadIns.status="checkFirmware" okFirmware=False #okFirmware=True firmwareTime=0 while not okFirmware and okOS: xmlStr=etree.tostring(dev.rpc.get_system_firmware_information(), encoding='unicode') xmlRoot = ET.fromstring(xmlStr) for firmware_status in xmlRoot.iter('firmware-status'): #UPGRADED SUCCESSFULLY if firmware_status.text=='UPGRADED SUCCESSFULLY':okFirmware=True if firmware_status.text!='OK':print firmware_status.text print threadIns.hostIP+threadIns.serialNumber+":wate firmware upgrade "+str(firmwareTime)+" Sec" time.sleep(1) firmwareTime=firmwareTime+1 #print okFirmware elif type=="OS":okFirmware=True threadIns.status="reboot after install"+type if okOS is True and okFirmware is True: logging.info('Software installation complete. Rebooting') rsp = sw.reboot() logging.info('Upgrade pending reboot cycle, please be patient.') logging.info(rsp) else: msg = 'Unable to install software, {0}'.format(okOS) logging.error(msg) # End the NETCONF session and close the connection dev.close()
class TestConfig(unittest.TestCase): @patch('ncclient.manager.connect') def setUp(self, mock_connect): mock_connect.side_effect = self._mock_manager self.dev = Device(host='1.1.1.1', user='******', password='******', gather_facts=False) self.dev.open() self.conf = Config(self.dev) @patch('ncclient.operations.session.CloseSession.request') def tearDown(self, mock_session): self.dev.close() def test_config_constructor(self): self.assertTrue(isinstance(self.conf._dev, Device)) def test_config_confirm_true(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(confirm=True) self.conf.rpc.commit_configuration\ .assert_called_with(confirmed=True) def test_config_commit_confirm(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') def test_config_commit_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(synchronize=True) def test_config_commit_force_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(force_sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(**{'synchronize': True, 'force-synchronize': True}) def test_config_commit_timeout(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(timeout=60) self.conf.rpc.commit_configuration\ .assert_called_with(dev_timeout=60) def test_config_commit_full(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(full=True) self.conf.rpc.commit_configuration\ .assert_called_with(full=True) def test_config_commit_detail(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<mockdetail/>' self.assertEqual('<mockdetail/>', self.conf.commit(detail=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}) def test_config_commit_combination(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<moredetail/>' self.assertEqual( '<moredetail/>', self.conf.commit( detail=True, force_sync=True, full=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}, **{'synchronize': True, 'full': True, 'force-synchronize': True}) @patch('jnpr.junos.utils.config.JXML.remove_namespaces') def test_config_commit_xml_exception(self, mock_jxml): class MyException(Exception): xml = etree.fromstring('<test/>') self.conf.rpc.commit_configuration = \ MagicMock(side_effect=MyException) self.assertRaises(CommitError, self.conf.commit) def test_config_commit_exception(self): class MyException(Exception): pass self.conf.rpc.commit_configuration = \ MagicMock(side_effect=MyException) self.assertRaises(MyException, 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() 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') def test_config_load_len_with_format_text(self): self.conf.rpc.load_config = \ MagicMock(return_value='rpc_contents') textdata = """policy-options { prefix-list TEST1-NETS { 100.0.0.0/24; } policy-statement TEST1-NETS { term TEST1 { from { prefix-list TEST1-NETS; } then accept; } term REJECT { then reject; } } }""" self.assertEqual(self.conf.load(textdata), 'rpc_contents') def test_config_load_with_format_json(self): self.conf.rpc.load_config = \ MagicMock(return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load('test.json', format='json') self.assertEqual(op.tag, 'load-configuration-results') self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'json') @patch(builtin_string + '.open') def test_config_load_with_format_json_from_file_ext(self, mock_open): self.conf.rpc.load_config = \ MagicMock(return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load(path='test.json') self.assertEqual(op.tag, 'load-configuration-results') self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'json') @patch(builtin_string + '.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_string + '.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_string + '.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_string + '.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') @patch(builtin_string + '.open') def test_config_load_try_load_rpcerror(self, mock_open): ex = ConfigLoadError( rsp=etree.fromstring(( """<load-configuration-results> <rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error> </load-configuration-results>"""))) self.conf.rpc.load_config = MagicMock(side_effect=ex) self.assertRaises(ConfigLoadError, self.conf.load, path='config.conf') @patch(builtin_string + '.open') def test_config_load_try_load_rpctimeouterror(self, mock_open): 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) 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) @patch('jnpr.junos.Device.execute') def test_rescue_action_save(self, mock_exec): self.dev.request_save_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('save')) @patch('jnpr.junos.Device.execute') def test_rescue_action_get_exception(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock(side_effect=Exception) self.assertTrue(self.conf.rescue('get') is None) @patch('jnpr.junos.Device.execute') def test_rescue_action_get(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock() self.dev.rpc.get_rescue_information.return_value = 1 self.assertEqual(self.conf.rescue('get', format='xml'), 1) @patch('jnpr.junos.Device.execute') def test_rescue_action_delete(self, mock_exec): self.dev.rpc.request_delete_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('delete')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload(self, mock_exec): self.dev.rpc.load_configuration = MagicMock() self.dev.rpc.load_configuration.return_value = True self.assertTrue(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload_exception(self, mock_exec): self.dev.rpc.load_configuration = MagicMock(side_effect=Exception) self.assertFalse(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_unsupported_action(self, mock_exec): self.assertRaises(ValueError, self.conf.rescue, 'abc') def test_config_load_lset_from_rexp_xml(self): self.conf.rpc.load_config = MagicMock() conf = """<snmp><name>iBGP</name></snmp>""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'xml') def test_config_load_lset_from_rexp_set(self): self.conf.rpc.load_config = MagicMock() conf = """set system domain-name englab.nitin.net""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_set_delete(self): self.conf.rpc.load_config = MagicMock() conf = """delete snmp""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_conf(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') def test_config_load_lset_from_rexp_conf_replace_tag(self): self.conf.rpc.load_config = MagicMock() conf = """replace: snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'replace') def test_config_load_lset_from_rexp_error(self): self.conf.rpc.load_config = MagicMock() conf = """test>""" self.assertRaises(RuntimeError, self.conf.load, conf) def test_load_merge_true(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf, merge=True) self.assertFalse('action' in self.conf.rpc.load_config.call_args[1]) def test_commit_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit) def test_commit_check_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit_check) def test_commit_configuration_multi_rpc_error(self): self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager) try: self.dev.rpc.commit_configuration() except Exception as ex: self.assertTrue(isinstance(ex, RpcError)) if ncclient.__version__ > (0, 4, 5): self.assertEqual(ex.message, "error: interface-range 'axp' is not defined\n" "error: interface-ranges expansion failed") self.assertEqual(ex.errs, [{'source': None, 'message': "interface-range 'axp' is not defined", 'bad_element': None, 'severity': 'error', 'edit_path': None}, {'source': None, 'message': 'interface-ranges expansion failed', 'bad_element': None, 'severity': 'error', 'edit_path': None}]) else: self.assertEqual(ex.message, "interface-range 'axp' is not defined") @patch('jnpr.junos.utils.config.Config.lock') @patch('jnpr.junos.utils.config.Config.unlock') def test_config_mode_exclusive(self, mock_unlock, mock_lock): with Config(self.dev, mode='exclusive') as conf: conf.rpc.load_config = MagicMock() conf.load('conf', format='set') self.assertTrue(mock_lock.called and mock_unlock.called) @patch('jnpr.junos.Device.execute') def test_config_mode_batch(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode='batch') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(batch=True) @patch('jnpr.junos.Device.execute') def test_config_mode_private(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode='private') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(private=True) @patch('jnpr.junos.Device.execute') def test_config_mode_dynamic(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode='dynamic') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(dynamic=True) @patch('jnpr.junos.Device.execute') def test_config_mode_close_configuration_ex(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() ex = RpcError(rsp='ok') ex.message = 'Configuration database is not open' self.dev.rpc.close_configuration = MagicMock(side_effect=ex) try: with Config(self.dev, mode='batch') as conf: conf.load('conf', format='set') except Exception as ex: self.assertTrue(isinstance(ex, RpcError)) self.assertTrue(self.dev.rpc.close_configuration.called) @patch('jnpr.junos.Device.execute') def test_config_mode_undefined(self, mock_exec): try: with Config(self.dev, mode='unknown') as conf: conf.load('conf', format='set') except Exception as ex: self.assertTrue(isinstance(ex, ValueError)) @patch('jnpr.junos.Device.execute') def test_config_mode_batch_open_configuration_ex(self, mock_exec): rpc_xml = ''' <rpc-error> <error-severity>warning</error-severity> <error-info><bad-element>bgp</bad-element></error-info> <error-message>syntax error</error-message> </rpc-error> ''' rsp = etree.XML(rpc_xml) obj = RpcError(rsp=rsp) self.dev.rpc.open_configuration = MagicMock(side_effect=obj) with Config(self.dev, mode='batch') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(batch=True) @patch('jnpr.junos.Device.execute') def test_config_mode_private_open_configuration_ex(self, mock_exec): rpc_xml = ''' <rpc-error> <error-severity>warning</error-severity> <error-info><bad-element>bgp</bad-element></error-info> <error-message>syntax error</error-message> </rpc-error> ''' rsp = etree.XML(rpc_xml) obj = RpcError(rsp=rsp) self.dev.rpc.open_configuration = MagicMock(side_effect=obj) with Config(self.dev, mode='private') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(private=True) def _read_file(self, fname): from ncclient.xml_ import NCElement fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname) foo = open(fpath).read() # specific to multi rpc error if fname == 'commit-configuration.xml': raw = etree.XML(foo) obj = RPCReply(raw) obj.parse() if ncclient.__version__ > (0, 4, 5): raise RPCError(etree.XML(foo), errs=obj._errors) else: raise RPCError(etree.XML(foo)) def _mock_manager(self, *args, **kwargs): if kwargs: device_params = kwargs['device_params'] device_handler = make_device_handler(device_params) session = SSHSession(device_handler) return Manager(session, device_handler) elif args: return self._read_file(args[0].tag + '.xml')
#pprint( device.facts ) device.bind(cfg=Config) try: device.rpc.open_configuration(private=True) except jnpr.junos.exception.RpcError as e: if 'severity: warning' in str(e): print str(e) pass else: raise for line in open("fila"): elhay = Config(device) set_cmd = line elhay.load(set_cmd, format='set') elhay.pdiff() elhay.commit() #for line in open("fila"): # print device.cli(line) #device.cfg.load(template_path=template, template_vars=customer) #device.bind(cu=Config) #device.rpc.open_configuration(private=True,normalize=True) #device.cu.load("set system host-name r0") #device.cu.commit() #device.rpc.close_configuration() device.close()
class TestConfig(unittest.TestCase): @patch('ncclient.manager.connect') def setUp(self, mock_connect): mock_connect.side_effect = self._mock_manager self.dev = Device(host='1.1.1.1', user='******', password='******', gather_facts=False) self.dev.open() self.conf = Config(self.dev) @patch('ncclient.operations.session.CloseSession.request') def tearDown(self, mock_session): self.dev.close() def test_config_constructor(self): self.assertTrue(isinstance(self.conf._dev, Device)) def test_config_confirm_true(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(confirm=True) self.conf.rpc.commit_configuration\ .assert_called_with(confirmed=True) def test_config_commit_confirm(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') def test_config_commit_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(synchronize=True) def test_config_commit_force_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(force_sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(**{'synchronize': True, 'force-synchronize': True}) def test_config_commit_timeout(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(timeout=60) self.conf.rpc.commit_configuration\ .assert_called_with(dev_timeout=60) def test_config_commit_full(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(full=True) self.conf.rpc.commit_configuration\ .assert_called_with(full=True) def test_config_commit_detail(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<mockdetail/>' self.assertEqual('<mockdetail/>', self.conf.commit(detail=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}) def test_config_commit_combination(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<moredetail/>' self.assertEqual( '<moredetail/>', self.conf.commit( detail=True, force_sync=True, full=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}, **{'synchronize': True, 'full': True, 'force-synchronize': True}) @patch('jnpr.junos.utils.config.JXML.remove_namespaces') def test_config_commit_xml_exception(self, mock_jxml): class MyException(Exception): xml = etree.fromstring('<test/>') self.conf.rpc.commit_configuration = \ MagicMock(side_effect=MyException) self.assertRaises(CommitError, self.conf.commit) def test_config_commit_exception(self): class MyException(Exception): pass self.conf.rpc.commit_configuration = \ MagicMock(side_effect=MyException) self.assertRaises(MyException, 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_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) 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') def test_config_load_len_with_format_text(self): self.conf.rpc.load_config = \ MagicMock(return_value='rpc_contents') textdata = """policy-options { prefix-list TEST1-NETS { 100.0.0.0/24; } policy-statement TEST1-NETS { term TEST1 { from { prefix-list TEST1-NETS; } then accept; } term REJECT { then reject; } } }""" self.assertEqual(self.conf.load(textdata), 'rpc_contents') def test_config_load_with_format_json(self): self.conf.rpc.load_config = \ MagicMock(return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load('test.json', format='json') self.assertEqual(op.tag, 'load-configuration-results') self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'json') @patch(builtin_string + '.open') def test_config_load_with_format_json_from_file_ext(self, mock_open): self.conf.rpc.load_config = \ MagicMock(return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load(path='test.json') self.assertEqual(op.tag, 'load-configuration-results') self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'json') @patch(builtin_string + '.open') def test_config_load_update(self, mock_open): self.conf.rpc.load_config = \ MagicMock(return_value=etree.fromstring("""<load-configuration-results> <ok/> </load-configuration-results>""")) op = self.conf.load(path='test.conf', update=True) self.assertEqual(op.tag, 'load-configuration-results') self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') def test_config_load_update_merge_overwrite(self): self.assertRaises(ValueError, self.conf.load, path='test.jnpr', update=True, merge=True, overwrite=True) @patch(builtin_string + '.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_string + '.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_string + '.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_string + '.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') @patch(builtin_string + '.open') def test_config_load_try_load_rpcerror(self, mock_open): ex = ConfigLoadError( rsp=etree.fromstring(( """<load-configuration-results> <rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error> </load-configuration-results>"""))) self.conf.rpc.load_config = MagicMock(side_effect=ex) self.assertRaises(ConfigLoadError, self.conf.load, path='config.conf') @patch(builtin_string + '.open') def test_config_load_try_load_rpctimeouterror(self, mock_open): 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) 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) @patch('jnpr.junos.Device.execute') def test_rescue_action_save(self, mock_exec): self.dev.request_save_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('save')) @patch('jnpr.junos.Device.execute') def test_rescue_action_get_exception(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock(side_effect=Exception) self.assertTrue(self.conf.rescue('get') is None) @patch('jnpr.junos.Device.execute') def test_rescue_action_get(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock() self.dev.rpc.get_rescue_information.return_value = 1 self.assertEqual(self.conf.rescue('get', format='xml'), 1) @patch('jnpr.junos.Device.execute') def test_rescue_action_delete(self, mock_exec): self.dev.rpc.request_delete_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('delete')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload(self, mock_exec): self.dev.rpc.load_configuration = MagicMock() self.dev.rpc.load_configuration.return_value = True self.assertTrue(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload_exception(self, mock_exec): self.dev.rpc.load_configuration = MagicMock(side_effect=Exception) self.assertFalse(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_unsupported_action(self, mock_exec): self.assertRaises(ValueError, self.conf.rescue, 'abc') def test_config_load_lset_from_rexp_xml(self): self.conf.rpc.load_config = MagicMock() conf = """<snmp><name>iBGP</name></snmp>""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'xml') def test_config_load_lset_from_rexp_json(self): self.conf.rpc.load_config = MagicMock() conf = """{ "configuration" : { "system" : { "services" : { "telnet" : [null] } } } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'json') def test_config_load_lset_from_rexp_set(self): self.conf.rpc.load_config = MagicMock() conf = """set system domain-name englab.nitin.net""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_set_delete(self): self.conf.rpc.load_config = MagicMock() conf = """delete snmp""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_conf(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') def test_config_load_lset_from_rexp_conf_replace_tag(self): self.conf.rpc.load_config = MagicMock() conf = """replace: snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'replace') def test_config_load_lset_from_rexp_error(self): self.conf.rpc.load_config = MagicMock() conf = """test>""" self.assertRaises(RuntimeError, self.conf.load, conf) def test_load_merge_true(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf, merge=True) self.assertFalse('action' in self.conf.rpc.load_config.call_args[1]) def test_commit_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit) def test_commit_check_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit_check) def test_commit_configuration_multi_rpc_error(self): self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager) try: self.dev.rpc.commit_configuration() except Exception as ex: self.assertTrue(isinstance(ex, RpcError)) if ncclient.__version__ > (0, 4, 5): self.assertEqual(ex.message, "error: interface-range 'axp' is not defined\n" "error: interface-ranges expansion failed") self.assertEqual(ex.errs, [{'source': None, 'message': "interface-range 'axp' is not defined", 'bad_element': None, 'severity': 'error', 'edit_path': None}, {'source': None, 'message': 'interface-ranges expansion failed', 'bad_element': None, 'severity': 'error', 'edit_path': None}]) else: self.assertEqual(ex.message, "interface-range 'axp' is not defined") @patch('jnpr.junos.utils.config.Config.lock') @patch('jnpr.junos.utils.config.Config.unlock') def test_config_mode_exclusive(self, mock_unlock, mock_lock): with Config(self.dev, mode='exclusive') as conf: conf.rpc.load_config = MagicMock() conf.load('conf', format='set') self.assertTrue(mock_lock.called and mock_unlock.called) @patch('jnpr.junos.Device.execute') def test_config_mode_batch(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode='batch') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(batch=True) @patch('jnpr.junos.Device.execute') def test_config_mode_private(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode='private') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(private=True) @patch('jnpr.junos.Device.execute') def test_config_mode_dynamic(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() with Config(self.dev, mode='dynamic') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(dynamic=True) @patch('jnpr.junos.Device.execute') def test_config_mode_close_configuration_ex(self, mock_exec): self.dev.rpc.open_configuration = MagicMock() ex = RpcError(rsp='ok') ex.message = 'Configuration database is not open' self.dev.rpc.close_configuration = MagicMock(side_effect=ex) try: with Config(self.dev, mode='batch') as conf: conf.load('conf', format='set') except Exception as ex: self.assertTrue(isinstance(ex, RpcError)) self.assertTrue(self.dev.rpc.close_configuration.called) @patch('jnpr.junos.Device.execute') def test_config_mode_undefined(self, mock_exec): try: with Config(self.dev, mode='unknown') as conf: conf.load('conf', format='set') except Exception as ex: self.assertTrue(isinstance(ex, ValueError)) @patch('jnpr.junos.Device.execute') @patch('jnpr.junos.utils.config.warnings') def test_config_mode_batch_open_configuration_ex(self, mock_warnings, mock_exec): rpc_xml = ''' <rpc-error> <error-severity>warning</error-severity> <error-info><bad-element>bgp</bad-element></error-info> <error-message>syntax error</error-message> </rpc-error> ''' rsp = etree.XML(rpc_xml) obj = RpcError(rsp=rsp) self.dev.rpc.open_configuration = MagicMock(side_effect=obj) with Config(self.dev, mode='batch') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(batch=True) @patch('jnpr.junos.Device.execute') @patch('jnpr.junos.utils.config.warnings') def test_config_mode_private_open_configuration_ex(self, mock_warnings, mock_exec): rpc_xml = ''' <rpc-error> <error-severity>warning</error-severity> <error-info><bad-element>bgp</bad-element></error-info> <error-message>syntax error</error-message> </rpc-error> ''' rsp = etree.XML(rpc_xml) obj = RpcError(rsp=rsp) self.dev.rpc.open_configuration = MagicMock(side_effect=obj) with Config(self.dev, mode='private') as conf: conf.load('conf', format='set') self.dev.rpc.open_configuration.assert_called_with(private=True) def test__enter__private_exception_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.conf.rpc.open_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, Config.__enter__, Config(self.dev, mode='private')) def test__enter__private_exception_RpcError(self): rpc_xml = """<rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error>""" rsp = etree.XML(rpc_xml) self.conf.rpc.open_configuration = \ MagicMock(side_effect=RpcError(rsp=rsp)) self.assertRaises(RpcError, Config.__enter__, Config(self.dev, mode='private')) def test__enter__dyanamic_exception_RpcError(self): rpc_xml = """<rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error>""" rsp = etree.XML(rpc_xml) self.conf.rpc.open_configuration = \ MagicMock(side_effect=RpcError(rsp=rsp)) self.assertRaises(RpcError, Config.__enter__, Config(self.dev, mode='dynamic')) def test__enter__batch_exception_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.conf.rpc.open_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, Config.__enter__, Config(self.dev, mode='batch')) def test__enter__batch_exception_RpcError(self): rpc_xml = """<rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error>""" rsp = etree.XML(rpc_xml) self.conf.rpc.open_configuration = \ MagicMock(side_effect=RpcError(rsp=rsp)) self.assertRaises(RpcError, Config.__enter__, Config(self.dev, mode='batch')) def _read_file(self, fname): fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname) foo = open(fpath).read() # specific to multi rpc error if fname == 'commit-configuration.xml': raw = etree.XML(foo) obj = RPCReply(raw) obj.parse() if ncclient.__version__ > (0, 4, 5): raise RPCError(etree.XML(foo), errs=obj._errors) else: raise RPCError(etree.XML(foo)) def _mock_manager(self, *args, **kwargs): if kwargs: device_params = kwargs['device_params'] device_handler = make_device_handler(device_params) session = SSHSession(device_handler) return Manager(session, device_handler) elif args: return self._read_file(args[0].tag + '.xml')
for HOST in JUNOS_HOSTS: try: # Open and read the Jinja2 template file with open('Interface_Config.j2', 'r') as TEMPLATE_FH: TEMPLATE_FORMAT = TEMPLATE_FH.read() # Open and read the YAML file with open('Interface_Answ.yml', 'r') as ANSWER_FH: DATA = yaml.load(ANSWER_FH.read()) # Associate TEMPLATE_FORMAT file with Template TEMPLATE = Template(TEMPLATE_FORMAT) # Merge the data with the Template TEMP_CONFIG = TEMPLATE.render(DATA) print "\nResults for device " + HOST print "------------------------------" print TEMP_CONFIG DEVICE = Device(host=HOST, user='******', password='******').open() CONFIG = Config(DEVICE) CONFIG.lock() #CONFIG.load(TEMP_CONFIG, merge=True, format='text') #merge existing config with this config CONFIG.load(TEMP_CONFIG, override=True, format='text') # #CONFIG.load(TEMP_CONFIG, replace=True, format='text') # #CONFIG.load(TEMP_CONFIG, update=True, format='text') #replaces with this config CONFIG.pdiff() CONFIG.commit() CONFIG.unlock() DEVICE.close() except LockError as e: print "The config database was locked!" except ConnectTimeoutError as e: print "Connection time out!"
dev.open() cu = Config(dev) data = """interfaces { ge-1/0/1 { description "MPLS interface"; unit 0 { family mpls; } } ge-1/0/2 { description "MPLS interface"; unit 0 { family mpls; } } } protocols { mpls { interface ge-1/0/1; interface ge-1/0/2; } } """ cu.load(data, format='text') cu.pdiff() if cu.commit_check(): cu.commit() else: cu.rollback()
cfg = Config(dev) # Execute Rollback to prevent commit change from old config session # We prefer to raise a LockError is config is not clean #cfg.rollback() try: cfg.lock() #ask for configure exclusive except jnpr.junos.exception.LockError as error: print('\nCould not set configure exclusive lock :') print(error.message) exit() try: cfg.load(path="junos.conf", format='set') except jnpr.junos.exception.ConfigLoadError as error: print('\nthere were some errors/warnings while loading the config :') print(error.message) print(cfg.pdiff()) commit = raw_input("Commit? (y/N)") if commit in ["y", "Y", "Yes", "yes"]: try: cfg.commit(comment=comment) cfg.unlock() print('configuration commited on ' + dev.facts["hostname"]) except jnpr.junos.exception.CommitError as error: print('\ncommit failed on ' + dev.facts["hostname"]) print(' ' + error.errs[0]['edit_path']) print(' ' + error.errs[0]['bad_element']) print(error.message) make_rollback_and_quit(dev) else: make_rollback_and_quit(dev)
from jnpr.junos import Device from jnpr.junos.utils.config import Config switch = {'host': '10.10.10.150', 'user': '******', 'pw': ''} device = Device(host=switch['host'], user=switch['user'], password=switch['pw']) device.open() config = Config(device) payload = """vlans{ vlan101{ vlan-id 101; } } """ config.lock() config.load(payload, format='text') config.pdiff() if config.commit_check() == True: config.commit() else: config.rollback() config.unlock() device.close()
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_true(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(confirm=True) self.conf.rpc.commit_configuration\ .assert_called_with(confirmed=True) def test_config_commit_confirm(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') def test_config_commit_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(synchronize=True) def test_config_commit_force_sync(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(force_sync=True) self.conf.rpc.commit_configuration\ .assert_called_with(**{'synchronize': True, 'force-synchronize': True}) def test_config_commit_timeout(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(timeout=60) self.conf.rpc.commit_configuration\ .assert_called_with(dev_timeout=60) def test_config_commit_full(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.commit(full=True) self.conf.rpc.commit_configuration\ .assert_called_with(full=True) def test_config_commit_detail(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<mockdetail/>' self.assertEqual('<mockdetail/>', self.conf.commit(detail=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}) def test_config_commit_combination(self): self.conf.rpc.commit_configuration = MagicMock() self.conf.rpc.commit_configuration.return_value = '<moredetail/>' self.assertEqual( '<moredetail/>', self.conf.commit(detail=True, force_sync=True, full=True)) self.conf.rpc.commit_configuration\ .assert_called_with({'detail': 'detail'}, **{'synchronize': True, 'full': True, 'force-synchronize': True}) @patch('jnpr.junos.utils.config.JXML.remove_namespaces') def test_config_commit_xml_exception(self, mock_jxml): class MyException(Exception): xml = etree.fromstring('<test/>') self.conf.rpc.commit_configuration = \ MagicMock(side_effect=MyException) self.assertRaises(CommitError, self.conf.commit) def test_config_commit_exception(self): class MyException(Exception): pass self.conf.rpc.commit_configuration = \ MagicMock(side_effect=MyException) self.assertRaises(MyException, 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() 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') 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') @patch('__builtin__.open') def test_config_load_try_load_rpcerror(self, mock_open): ex = ConfigLoadError( rsp=etree.fromstring(("""<load-configuration-results> <rpc-error> <error-severity>error</error-severity> <error-message>syntax error</error-message> </rpc-error> </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) 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) @patch('jnpr.junos.Device.execute') def test_rescue_action_save(self, mock_exec): self.dev.request_save_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('save')) @patch('jnpr.junos.Device.execute') def test_rescue_action_get_exception(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock(side_effect=Exception) self.assertTrue(self.conf.rescue('get') is None) @patch('jnpr.junos.Device.execute') def test_rescue_action_get(self, mock_exec): self.dev.rpc.get_rescue_information = MagicMock() self.dev.rpc.get_rescue_information.return_value = 1 self.assertEqual(self.conf.rescue('get', format='xml'), 1) @patch('jnpr.junos.Device.execute') def test_rescue_action_delete(self, mock_exec): self.dev.rpc.request_delete_rescue_configuration = MagicMock() self.assertTrue(self.conf.rescue('delete')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload(self, mock_exec): self.dev.rpc.load_configuration = MagicMock() self.dev.rpc.load_configuration.return_value = True self.assertTrue(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_reload_exception(self, mock_exec): self.dev.rpc.load_configuration = MagicMock(side_effect=Exception) self.assertFalse(self.conf.rescue('reload')) @patch('jnpr.junos.Device.execute') def test_rescue_action_unsupported_action(self, mock_exec): self.assertRaises(ValueError, self.conf.rescue, 'abc') def test_config_load_lset_from_rexp_xml(self): self.conf.rpc.load_config = MagicMock() conf = """<snmp><name>iBGP</name></snmp>""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'xml') def test_config_load_lset_from_rexp_set(self): self.conf.rpc.load_config = MagicMock() conf = """set system domain-name englab.nitin.net""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_set_delete(self): self.conf.rpc.load_config = MagicMock() conf = """delete snmp""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'set') def test_config_load_lset_from_rexp_conf(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') def test_config_load_lset_from_rexp_conf_replace_tag(self): self.conf.rpc.load_config = MagicMock() conf = """replace: snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf) self.assertEqual(self.conf.rpc.load_config.call_args[1]['format'], 'text') self.assertEqual(self.conf.rpc.load_config.call_args[1]['action'], 'replace') def test_config_load_lset_from_rexp_error(self): self.conf.rpc.load_config = MagicMock() conf = """nitin>""" self.assertRaises(RuntimeError, self.conf.load, conf) def test_load_merge_true(self): self.conf.rpc.load_config = MagicMock() conf = """ snmp { location USA; community iBGP { authorization read-only; } }""" self.conf.load(conf, merge=True) self.assertFalse('action' in self.conf.rpc.load_config.call_args[1]) def test_commit_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit) def test_commit_check_RpcTimeoutError(self): ex = RpcTimeoutError(self.dev, None, 10) self.dev.rpc.commit_configuration = MagicMock(side_effect=ex) self.assertRaises(RpcTimeoutError, self.conf.commit_check)
cu = Config(dev) data = """interfaces { ge-1/0/1 { description "MPLS interface"; unit 0 { family mpls; } } ge-1/0/2 { description "MPLS interface"; unit 0 { family mpls; } } } protocols { mpls { interface ge-1/0/1; interface ge-1/0/2; } } """ cu.load(data, format='text') cu.pdiff() if cu.commit_check(): cu.commit() else: cu.rollback() dev.close()
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_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') 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') @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) 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)
#----------------------------------------------------------------------------------------------------------------------- # DESCRIPTION: # Use PyEZ to automatically merge a variables YML file and a Jinja2 template and update the candidate configuration on # a device. # # CONTACT: [email protected]; [email protected]; [email protected]; [email protected]; [email protected] # # CREATED: 2015-11-11 # # VERSION: 1 # # USAGE: conf_int_with_vlan.py # ----------------------------------------------------------------------------------------------------------------------- from jnpr.junos import Device from jnpr.junos.utils.config import Config import yaml ip = raw_input("ip address of the device:") a_device = Device(host=ip, user="******", password="******") a_device.open() cfg = Config(a_device) cfg.rollback() s = open('configuration_management/list_int_vlan.yml').read() myvars = yaml.load(s) cfg.load(template_path='configuration_management/template_int_vlan.j2', template_vars=myvars, format='set') cfg.pdiff() #cfg.commit() cfg.rollback()
def apply_conf(template, newconf, dev, state, hostname, printlock): """Function to configure Juniper devices using PyEZ.""" cu = Config(dev) def lockprint(message): """Print function with multiprocessing lock.""" with printlock: print message lockprint("Locking the configuration") try: cu.lock() except LockError as err: lockprint("ERROR: Unable to lock configuration: {}".format(err)) lockprint("Closing connection") dev.close() state[hostname] = 'No_lock' return lockprint("Loading the configuration") try: cu.load(template_path=template, template_vars=newconf, format='set') except ConfigLoadError as err: lockprint("ERROR: Unable to load configuration changes: {}".format(err)) lockprint("Unlocking the configuration") state[hostname] = 'No_load' try: cu.unlock() lockprint("Closing the connection") dev.close() return except UnlockError as err: lockprint("ERROR: Unable to unlock configuration: {}".format(err)) lockprint("Closing the connction") dev.close() return except ValueError as err: lockprint("ERROR: Unable to load configuration changes: {}".format(err)) lockprint("Unlocking the configuration") state[hostname] = 'No_load' try: cu.unlock() lockprint("Closing the connection") dev.close() return except UnlockError as err: lockprint("ERROR: Unable to unlock configuration: {}".format(err)) lockprint("Closing the connection") dev.close() return except Exception as err: lockprint("ERROR: Unable to load configuration changes: {}".format(err)) lockprint("Unlocking the configuration") state[hostname] = 'No_load' try: cu.unlock() lockprint("Closing the connection") dev.close() return except UnlockError as err: lockprint("ERROR: Unable to unlock configuration: {}".format(err)) lockprint("Closing the connection") dev.close() return cu.pdiff() lockprint("Committing the configuration") try: cu.commit() except CommitError as err: lockprint("ERROR: Unable to commit configuration: {}".format(err)) lockprint("Unlocking the configuration") state[hostname] = 'No_commit' try: cu.unlock() lockprint("Closing the connection") dev.close() return except UnlockError as err: lockprint("ERROR: Unable to unlock configuration: {}".format(err)) lockprint("Closing the connection") dev.close() return lockprint("Closing the connection") dev.close() state[hostname] = 'Complete' return