Exemple #1
0
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"
Exemple #2
0
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
Exemple #3
0
    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 test_load_console(self, mock_read_until, mock_select, mock_write):
        mock_select.return_value = ([self.dev._tty._rx], [], [])
        xml = """<policy-options>
                  <policy-statement>
                    <name>F5-in</name>
                    <term>
                        <name>testing</name>
                        <then>
                            <accept/>
                        </then>
                    </term>
                    <from>
                        <protocol>mpls</protocol>
                    </from>
                </policy-statement>
                </policy-options>"""

        mock_read_until.return_value = six.b("""
        <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/15.2I0/junos">
            <load-configuration-results>
            <ok/>
            </load-configuration-results>
            </rpc-reply>
            ]]>]]>""")
        cu = Config(self.dev)
        cu.load(xml, format='xml')
        cu.commit()
Exemple #5
0
 def create_port(self, port_name, port_description):
     """Configures port_name as an access port with port_description configured on IFD
     """
     port_vars={}
     port_vars['port_name'] = port_name
     port_vars['port_description'] = port_description
     cu = Config(self.connection)
     cu.load(template_path='service-templates/junos/ex/dot1ad-port.conf', template_vars=port_vars, merge=True)  
class JuniperObject(object):
    def __init__(self, jnp_dev):
        self.conn = jnp_dev
        self.config = None
        self.ports = {}
        self.routes = {}

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

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

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

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

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

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

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

    def show_all_routes(self):
        self.__get_routes()
        print "Juniper SRX Routing Table"
        for my_key in self.routes.keys():
            print "---------------------------------"
            print my_key + ":"
            print "  Next Hop: {}".format(self.routes[my_key]['nexthop'])
            print "  Age: {}".format(self.routes[my_key]['age'])
            print "  via: {}".format(self.routes[my_key]['via'])
            print "  Protocol: {}".format(self.routes[my_key]['protocol'])
Exemple #7
0
 def create_svlan(self, vlan_id, svlan_name, vlan_description):
     """Create Service VLAN on switch
     """
     svlan_vars={}
     svlan_vars['vlan_stag'] = vlan_id
     svlan_vars['svlan_name'] = svlan_name
     svlan_vars['vlan_description'] = vlan_description
     cu = Config(self.connection)
     cu.load(template_path='service-templates/junos/ex/dot1ad-vlan.conf', template_vars=svlan_vars, merge=True)  
    def run(self):
        self.logfile = open(os.getcwd() + '/' + 'linkfailure_log', 'a')
        while True:
            while self.failed() == False:
                time.sleep(1)
            # select a router
            r_number = random.randint(1,len(self.rtr)) - 1
            # select a random interface 
            i_number = random.randint(1, len(self.rtr[r_number]['interfaces'])) - 1

            #set interfaces ge-1/0/3 disable 

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

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

            cmd = 'delete interfaces ' + self.rtr[r_number]['interfaces'][i_number]['name'] + ' disable'
            dev = Device(host=self.rtr[r_number]['ip'], user='******', password='******')
            dev.open()
            dev.timeout = 60
            cu = Config(dev)
            cu.lock()
            cu.load(cmd, format='set', merge=True)
            cu.commit()
            cu.unlock()
            dev.close()
            link__data = { 'status': 'healed', 'timestamp': datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S'), 
                                'router_id': self.rtr[r_number]['router_id'], 'router_name': self.rtr[r_number]['name'],
                                'interface_address': self.rtr[r_number]['interfaces'][i_number]['address'],
                                'interface_name': self.rtr[r_number]['interfaces'][i_number]['name']
                         }
            jd = json.dumps(link__data)
            self.redis.publish('link_event', jd)
            self.logfile.write("Link healed: " + datetime.datetime.fromtimestamp(time.time()).strftime('%a:%H:%M:%S') + " " +
                               self.rtr[r_number]['name'] + " " +  self.rtr[r_number]['ip'] + " " + self.rtr[r_number]['interfaces'][i_number]['name'] + "\n")
            self.logfile.flush()
Exemple #9
0
 def bind_service(self, cvlan_id, svlan_name, port_name):
     """Binds cvlan_id from port_name to svlan_name (one-to-one bundling)
     """
     bind_service_vars={}
     bind_service_vars['cvlan_id'] = cvlan_id
     bind_service_vars['svlan_name'] = svlan_name
     bind_service_vars['port_name'] = port_name
     cu = Config(self.connection)
     cu.load(template_path='service-templates/junos/ex/dot1ad-service.conf', template_vars=bind_service_vars, merge=True)  
 def test_ignore_warning_string_1snf_warning_1err(self):
     self.dev._conn.rpc = MagicMock(side_effect=
                                    self._mock_manager_1snf_warning_1err)
     cu = Config(self.dev)
     config = """
         delete interfaces ge-0/0/0
         delete protcols ospf
         delete policy-options prefix-list foo
     """
     with self.assertRaises(ConfigLoadError):
         cu.load(config, ignore_warning='statement not found')
 def test_ignore_warning_list_3warn_no_match(self):
     self.dev._conn.rpc = MagicMock(side_effect=
                                    self._mock_manager_3foobar_warnings)
     cu = Config(self.dev)
     config = """
         delete interfaces ge-0/0/0
         delete protcols ospf
         delete policy-options prefix-list foo
     """
     with self.assertRaises(ConfigLoadError):
         cu.load(config, ignore_warning=['foo', 'foo bar'])
Exemple #12
0
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 test_load_config(self):
     from jnpr.junos.utils.config import Config
     cu = Config(self.dev)
     data = """interfaces {
        ge-1/0/0 {
           description "MPLS interface";
           unit 0 {
              family mpls;
           }
       }
     }
     """
     cu.load(data, format='text')
     self.assertTrue(cu.commit_check())
     if cu.commit_check():
         cu.rollback()
class NetconfConnection(AbstractConnection):
    ''' Netconf connection class
    '''
    def __init__(self, host, username='******', password='******',
        logger=None, **kwargs):
        self.host = host
        self.username = username
        self.password = password
        self.handle = None
        self.logger = kwargs.get('logger', contrail_logging.getLogger(__name__))
        self.config_handle = None

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

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

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

    def config(self, stmts=[], commit=True, ignore_errors=False, timeout = 30):
        for stmt in stmts:
            try:
                self.config_handle.load(stmt, format='set', merge=True)
            except ConfigLoadError,e:
                if ignore_errors:
                    self.logger.debug('Exception %s ignored' % (e))
                    self.logger.exception(e)
                else:
                    raise e
        if commit:
            try:
                self.config_handle.commit(timeout = timeout)
            except CommitError,e:
                self.logger.exception(e)
                return (False,e)
Exemple #15
0
    def updateDeviceConfiguration(self):
        '''
        Device Connection should be open by now, no need to connect again 
        '''
        logger.debug('updateDeviceConfiguration for %s' % (self.deviceLogStr))
        l3ClosMediation = L3ClosMediation(conf = self._conf)
        config = l3ClosMediation.createLeafConfigFor2Stage(self.device)
        # l3ClosMediation used seperate db sessions to create device config
        # expire device from current session for lazy load with committed data
        self._session.expire(self.device)
        
        configurationUnit = Config(self.deviceConnectionHandle)

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

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

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

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

        finally:
            configurationUnit.unlock()
            logger.debug('Unlock config for %s' % (self.deviceLogStr))
Exemple #16
0
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 test_ignore_warning_string_3snf_warnings(self):
     self.dev._conn.rpc = MagicMock(side_effect=
                                    self._mock_manager_3snf_warnings)
     cu = Config(self.dev)
     config = """
         delete interfaces ge-0/0/0
         delete protocols ospf
         delete policy-options prefix-list foo
     """
     self.assertTrue(cu.load(config, ignore_warning='statement not found'))
def load_config_cmd_on_devices(fname):
	#import pdb;pdb.set_trace()
	global handles 
	global hosts
	global dev
	print ("\n")
	i=0
	j=0
	#print ("to find")
	#print (handles)
	locallist = list(handles['resources'].keys())
	#router_index = 0
	for router in hosts:
		#import pdb; pdb.set_trace()
		#print ("find here")
		#dev[i].bind( cu=Config )
		print ("Loading configuration changes on Device", hosts[i])
		print ("\n")
		#import pdb;pdb.set_trace()
		try:
			#print ("run trough python")
			file_name = fname
			#print ("loading " + file_name + " configuration on DUT " + router)
			cfg = Config(dev[i])
			print ("Configuring Below command on ",hosts[i])
			#print (each_line.strip())
			cfg.load(path=file_name, format="set", merge=True)
			#dev[k].cfg.load(each_line.strip(), format='set')
			#k = k + 1
			#j = j + 1
		except ValueError as err:
			print (err.message)
		except Exception as err:
			if err.rsp.find('.//ok') is None:
				rpc_msg = err.rsp.findtext('.//error-message')
				print ("Unable to load configuration changes: ", rpc_msg)
				print ("Unlocking the configuration on Device", hosts[i])
				print ("\n")
				#dev[i].close()
			return
		print ("\n")
		i = i+1
Exemple #19
0
    def updateDeviceConfiguration(self):
        '''
        Device Connection should be open by now, no need to connect again 
        '''
        logger.debug('updateDeviceConfiguration for %s' % (self.deviceLogStr))
        config = self.getDeviceConfig()
        
        configurationUnit = Config(self.deviceConnectionHandle)

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

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

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

            #print configurationUnit.diff()
            #print configurationUnit.commit_check()
            configurationUnit.commit()
            logger.info('Committed twoStage config for %s' % (self.deviceLogStr))
        except CommitError as exc:
            #TODO: eznc Error handling is not giving helpful error message
            logger.error('updateDeviceConfiguration failed for %s, CommitError: %s, %s, %s' % (self.deviceLogStr, exc, exc.errs, exc.rpc_error))
            configurationUnit.rollback() 
            raise DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), exc)
        except Exception as exc:
            logger.error('updateDeviceConfiguration failed for %s, %s' % (self.deviceLogStr, exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            configurationUnit.rollback() 
            raise DeviceRpcFailed('updateDeviceConfiguration failed for %s' % (self.deviceLogStr), exc)
        finally:
            configurationUnit.unlock()
            logger.debug('Unlock config for %s' % (self.deviceLogStr))
Exemple #20
0
class VlanDeployer(threading.Thread):
	def __init__(self , host , vlans):
		self.cred = host
		self.vlans = vlans
		threading.Thread.__init__(self)
		self.dev1 = None
		self.cu=None
	
	def run(self):
		self.dev1 = Device(host=self.cred[0] , user=self.cred[1] , password=self.cred[2])
		self.dev1.open()
		self.cu = Config(self.dev1)
		print "CONNECTED TO "+self.cred[0]

		for term in self.vlans:
			config_text= 'vlans{ ' + term['Vlan-name'] + '{description "'  + term['Desc'] + '"; vlan-id ' + term["Vlan-id"]+ ';}}'
			self.cu.load(config_text , format="text" , merge=True)

		self.cu.commit()
		self.dev1.close()
		print "CONF PUSHED TO "+ self.cred[0]
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
Exemple #22
0
def main():

    pwd = getpass()

    juniper = {
        "host": "50.76.53.27",
        "user": "******",
        "password": pwd
    }

    a_device = Device(**juniper)
    a_device.open()

    cfg = Config(a_device)

    print "Changing hostname with set command"
    cfg_load = cfg.load("set system host-name batz-jnpr-srx1", format ="set", merge=True)
    print cfg.diff()
    print
    print "Doing rollback"
    cfg.rollback(0)


    print "Changing hostname with conf method "
    cfg_load_conf = cfg.load(path='hostname.conf', format='text', merge=True)
    print cfg.diff()
    print
    print "Doing rollback"
    cfg.rollback(0)


    print "Changing hostname with xml method"
    cfg_load_xml = cfg.load(path='hostname.xml', format='xml', merge=True)
    print cfg.diff()
    print

    print "Doing changes"
    cfg.commit()
    print
    def commitConfiguration(self):
        dev = Device(host=self.srxip, user=self.username, password=self.password)
        dev.open()
        cu = Config(dev)
        config = """ set routing-options static route %s/32 next-hop %s
set interfaces %s family inet
set security zones security-zone vpn interfaces %s
set security ike gateway gateway-%s ike-policy pol-basic
set security ike gateway gateway-%s address %s
set security ike gateway gateway-%s external-interface ge-0/0/0.0
set security ipsec vpn vpn-%s bind-interface %s
set security ipsec vpn vpn-%s ike gateway gateway-%s
set security ipsec vpn vpn-%s ike proxy-identity local 192.168.1.0/26
set security ipsec vpn vpn-%s ike proxy-identity remote %s/32
set security ipsec vpn vpn-%s ike ipsec-policy pol-basic
set security ipsec vpn vpn-%s establish-tunnels immediately
        """ % (self.remoteipprivate, self.tunnelint, self.tunnelint, self.tunnelint, self.hostname,
               self.hostname, self.remoteippublic, self.hostname, self.hostname, self.tunnelint, self.hostname,
               self.hostname, self.hostname, self.hostname, self.remoteipprivate, self.hostname, self.hostname)
        cu.load(config, format="set")
        cu.commit()
        dev.close()
        return "committed config: \n" + config
Exemple #24
0
def process_device(ip, **kwargs):
    dev = Device(host=ip, **kwargs)
    cu = Config(dev)
    print "Searching for active sessions on Device:", ip, "matching the following criteria" + '\n\n\t' + "Destination IP-Address:" + '\t' + destip + '\n\t' + "Destination-Port:" + '\t' +  dport + '\n\t' + "Application:" + '\t\t' +  application + '\n'

    try:

        dev.open()
        cluster_status = ClusterStatus(dev)
        cluster_status.get()
        session_table = SessionTable(dev)
        session_table.get()
        found = 'f'
        cluster = 'a'
        cu.lock()

        for c in cluster_status:
          if cluster_status.keys():
            print "SRX Cluster has redundancy-group", c.redundancy_group_id
          if not cluster_status.keys():
            print "Clustering is not Enabled"

        for s in session_table:
          if session_table.keys() and s.in_destination_address == destip and s.in_destination_port == dport and s.in_session_protocol == application:
            found = 't'
            print "Found Session on", ip, s.re_name  + '\n\n\t' + "Source-Address:" + '\t' + s.in_source_address +'\n\t' + "Session-Id:" + '\t' + s.session_identifier + '\n\n' + "Creating Address-entry on Device:", ip + '\n\n' + "Clearing active session" + '\n\t' + "Session-Id:" + '\t' + s.session_identifier + '\n\t' + "Cluster-Node:" + '\t' + s.re_name + '\n'
            block_src = {'Address': s.in_source_address}
            jinja_data = open("jinjafile.conf", "wb")
            jinja_data.write(JinjaTemplate.render(**block_src))
            jinja_data.close()
            rsp = cu.load( template_path="jinjafile.conf", merge=True )
            clearflow = dev.rpc.clear_flow_session(destination_prefix=s.in_destination_address, source_prefix=s.in_source_address, destination_port=s.in_destination_port, protocol=s.in_session_protocol)
        cu.commit()
        cu.unlock()

        if found == 'f':
            print "No Active Sessions were found with the following criteria:" + '\n\n\t' + "Destination IP-Address:" + '\t' + destip + '\n\t' + "Destination Port:" + '\t' + dport +'\n\t' + "Application:" + '\t\t' + application + '\n'

    except RpcError:
        msg = "{0} was Skipped due to RPC Error.  Device is not a Juniper SRX Series".format(ip.rstrip())
        print msg
        dev.close()

    except Exception as err:
        msg = "{0} was skipped due to unhandled exception.\n{1}".format(ip.rstrip(), err)
        print msg
        traceback.print_exc(file=sys.stdout)

    dev.close()
def main():
    '''
    Exercise using Juniper's PyEZ to make changes to device in various ways
    '''
    pwd = getpass()
    ip_addr = raw_input("Enter Juniper SRX IP: ")
    ip_addr = ip_addr.strip()

    juniper_srx = {
        "host": ip_addr,
        "user": "******",
        "password": pwd
    }

    print "\n\nConnecting to Juniper SRX...\n"
    a_device = Device(**juniper_srx)
    a_device.open()

    cfg = Config(a_device)

    print "Setting hostname using set notation"
    cfg.load("set system host-name test1", format="set", merge=True)

    print "Current config differences: "
    print cfg.diff()

    print "Performing rollback"
    cfg.rollback(0)

    print "\nSetting hostname using {} notation (external file)"
    cfg.load(path="load_hostname.conf", format="text", merge=True)

    print "Current config differences: "
    print cfg.diff()

    print "Performing commit"
    cfg.commit()

    print "\nSetting hostname using XML (external file)"
    cfg.load(path="load_hostname.xml", format="xml", merge=True)

    print "Current config differences: "
    print cfg.diff()

    print "Performing commit"
    cfg.commit()
    print
s2 = f2.read()
template = Template(s2)

print 'Start configuration building'
for ex in my_vars:
    print 'generate config file for device ' + ex[
        "host_name"] + ' : conf_file_build_phase_' + ex["host_name"] + '.conf'
    conffile = open('conf_file_build_phase_' + ex["host_name"] + '.conf', 'w')
    conffile.write(template.render(ex))
    conffile.close()
print 'done'

print 'applying the conf to the devices ...'
for ex in my_vars:
    dev = Device(host=ex["management_ip"],
                 user='******',
                 password='******')
    dev.open()
    cfg = Config(dev)
    cfg.rollback(
    )  # Execute Rollback to prevent commit change from old config session
    #cfg.load(template_path='template_for_ex.j2', template_vars=my_vars, format='text')
    cfg.load(path='conf_file_build_phase_' + ex["host_name"] + '.conf',
             format='text')
    if cfg.commit() == True:
        print('configuration commited on ' + dev.facts["hostname"])
    else:
        print('commit failed on ' + dev.facts["hostname"])
    dev.close()
print('done')
Exemple #27
0
class Netconf(object):

    def __init__(self):
        self.device = None
        self.config = None
        self._locked = False
        self._connected = False
        self.default_output = 'xml'

    def raise_exc(self, msg):
        if self.device:
            if self._locked:
                self.config.unlock()
            self.disconnect()
        raise NetworkError(msg)

    def connect(self, params, **kwargs):
        host = params['host']
        port = params.get('port') or 830

        user = params['username']
        passwd = params['password']

        try:
            self.device = Device(host, user=user, passwd=passwd, port=port,
                                 gather_facts=False)
            self.device.open()
        except ConnectError:
            exc = get_exception()
            self.raise_exc('unable to connect to %s: %s' % (host, str(exc)))

        self.config = Config(self.device)
        self._connected = True

    def disconnect(self):
        if self.device:
            self.device.close()
        self._connected = False

    ### Command methods ###

    def run_commands(self, commands):
        responses = list()

        for cmd in commands:
            meth = getattr(self, cmd.args.get('command_type'))
            responses.append(meth(str(cmd), output=cmd.output))

        for index, cmd in enumerate(commands):
            if cmd.output == 'xml':
                responses[index] = etree.tostring(responses[index])
            elif cmd.args.get('command_type') == 'rpc':
                responses[index] = str(responses[index].text).strip()

        return responses

    def cli(self, commands, output='xml'):
        '''Send commands to the device.'''
        try:
            return self.device.cli(commands, format=output, warning=False)
        except (ValueError, RpcError):
            exc = get_exception()
            self.raise_exc('Unable to get cli output: %s' % str(exc))

    def rpc(self, command, output='xml'):
        name, kwargs = rpc_args(command)
        meth = getattr(self.device.rpc, name)
        reply = meth({'format': output}, **kwargs)
        return reply

    ### Config methods ###

    def get_config(self, config_format="text"):
        if config_format not in SUPPORTED_CONFIG_FORMATS:
            self.raise_exc(msg='invalid config format.  Valid options are '
                               '%s' % ', '.join(SUPPORTED_CONFIG_FORMATS))

        ele = self.rpc('get_configuration', output=config_format)

        if config_format in ['text', 'set']:
            return str(ele.text).strip()
        else:
            return ele

    def load_config(self, candidate, update='merge', comment=None,
                    confirm=None, format='text', commit=True):

        merge = update == 'merge'
        overwrite = update == 'overwrite'

        self.lock_config()

        try:
            candidate = '\n'.join(candidate)
            self.config.load(candidate, format=format, merge=merge,
                             overwrite=overwrite)
        except ConfigLoadError:
            exc = get_exception()
            self.raise_exc('Unable to load config: %s' % str(exc))

        diff = self.config.diff()

        self.check_config()

        if all((commit, diff)):
            self.commit_config(comment=comment, confirm=confirm)

        self.unlock_config()

        return diff

    def save_config(self):
        raise NotImplementedError

    ### end of Config ###

    def get_facts(self, refresh=True):
        if refresh:
            self.device.facts_refresh()
        return self.device.facts

    def unlock_config(self):
        try:
            self.config.unlock()
            self._locked = False
        except UnlockError:
            exc = get_exception()
            raise NetworkError('unable to unlock config: %s' % str(exc))

    def lock_config(self):
        try:
            self.config.lock()
            self._locked = True
        except LockError:
            exc = get_exception()
            raise NetworkError('unable to lock config: %s' % str(exc))

    def check_config(self):
        if not self.config.commit_check():
            self.raise_exc(msg='Commit check failed')

    def commit_config(self, comment=None, confirm=None):
        try:
            kwargs = dict(comment=comment)
            if confirm and confirm > 0:
                kwargs['confirm'] = confirm
            return self.config.commit(**kwargs)
        except CommitError:
            exc = get_exception()
            raise NetworkError('unable to commit config: %s' % str(exc))

    def rollback_config(self, identifier, commit=True, comment=None):

        self.lock_config()

        try:
            self.config.rollback(identifier)
        except ValueError:
            exc = get_exception()
            self._error('Unable to rollback config: $s' % str(exc))

        diff = self.config.diff()
        if commit:
            self.commit_config(comment=comment)

        self.unlock_config()
        return diff
Exemple #28
0
env = Environment(loader=FileSystemLoader('.'), trim_blocks=True)
print(env.get_template('edge.conf.template').render(vars))
print('--------------------------------------------')
print('')


ip='140.117.181.202'
print('connecting to '+ip+'...')
dev = Device(host=ip, user='******', password='******')

try:
    dev.open()
except ConnectError as err:
    print('Cannot connect to device: {0}\n'.format(err))
    sys.exit()
print('connected')

cu = Config(dev)
cu.load(template_path='edge.conf.template', template_vars=vars, overwrite=True, format='text')
print('configuration loaded')
print('commit check: {0}'.format(cu.commit_check()))

if cu.commit(confirm=30, timeout=60):
    print('committed')
    print('warning: you have to commit again in 10 minutes to confirm changes,')
    print('         or it will rollback automatically')
else:
    print('commit check failed')

print('')
dev.close()
#!/usr/bin/python

from jnpr.junos import Device
from jinja2 import Template
import yaml
import sys
from glob import glob

from getpass import getpass
host = raw_input('hostname or address: ')
username = raw_input('username: '******'password: '******'datavars.yml')[0]) as fh:
    data = yaml.load(fh.read())

# Jinja2 template file.
with open(glob('config-example-template.conf')[0]) as t_fh:
    t_format = t_fh.read()

template = Template(t_format)
print (template.render(data))

rsp = cu.load( template_path="config-example-template.conf", template_vars=data )
cu.commit()
Exemple #30
0
    # Inventory Routes before the change

    ROUTES_BEFORE = list()

    for k in rib_table.keys():

        ROUTES_BEFORE.append(k)

# Adding the static routes

    cfg_static_routes = Config(srx2_device)

    cfg_static_routes.lock()

    cfg_static_routes.load(path="static_routes.conf",
                           format="text",
                           merge=True)

    cfg_static_routes.commit()

    # Checking the RIB after the change

    rib_table = gather_routes(srx2_device)

    print_rib(rib_table, "AFTER")

    # Inventory Routes after the change

    ROUTES_AFTER = list()

    for k in rib_table.keys():
Exemple #31
0
#-----------------------------------------------------------------------------------------------------------------------
# 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()
Exemple #32
0
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.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_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_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 _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')
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)
pwd = getpass()

# Create a Device instance
a_device = Device(host="50.76.53.27", user="******", password=pwd)

# Establish a connection with Juniper device
a_device.open()

# Create a Config instance
cfg = Config(a_device)

# Lock the Juniper device while you are doing the config changes
cfg.lock()

# 1. Load config via load-set command
cfg.load("set system host-name juniper-test-name", format="set", merge=True)

# Show the differences between running-config and candidate config
print cfg.diff()

# cfg.commit()

# Rollback the candidate config changes
cfg.rollback(0)


# 2. Load new config via 'test_config.conf' file (using curly braces)
# Create test_config.conf file first in the currently-running Linux directory
cfg.load(path="test_config.conf", format="text", merge=True)

# Show the differences between running-config and candidate config
dict1 = yaml.safe_load(open('template_vars.yml'))
#print(type(dict1))
#print(dict1)

baseline = ENV.get_template("bgp-template2.j2")
config = baseline.render(dict1)
f = open('updated-config.conf', 'w')
f.write(config)
print("Below config is getting pushed....")
print('~' * 100)
print(config)
print('~' * 100)
f.close()

try:
    cfg.load(path="updated-config.conf", format='set', merge=True)
except Exception as e:
    print("Exception Raised while loading config")
    print(e)
    sys.exit()
try:
    if cfg.commit_check():
        cfg.commit()
        print("\n>>>>>>>>Config is committed<<<<<<<<")
    else:
        print("Error while pushing config")
        a_device.close()
except Excetion as e:
    print(e)
    print("Error while pushing config")
    a_device.close()
Exemple #36
0
class Netconf(object):
    def __init__(self):
        if not HAS_PYEZ:
            raise NetworkError(
                msg=
                'junos-eznc >= 1.2.2 is required but does not appear to be installed.  '
                'It can be installed using `pip install junos-eznc`')
        if not HAS_JXMLEASE:
            raise NetworkError(
                msg='jxmlease is required but does not appear to be installed.  '
                'It can be installed using `pip install jxmlease`')
        self.device = None
        self.config = None
        self._locked = False
        self._connected = False
        self.default_output = 'xml'

    def raise_exc(self, msg):
        if self.device:
            if self._locked:
                self.config.unlock()
            self.disconnect()
        raise NetworkError(msg)

    def connect(self, params, **kwargs):
        host = params['host']
        port = params.get('port') or 830

        user = params['username']
        passwd = params['password']

        try:
            self.device = Device(host,
                                 user=user,
                                 passwd=passwd,
                                 port=port,
                                 gather_facts=False)
            self.device.open()
        except ConnectError:
            exc = get_exception()
            self.raise_exc('unable to connect to %s: %s' % (host, str(exc)))

        self.config = Config(self.device)
        self._connected = True

    def disconnect(self):
        try:
            self.device.close()
        except AttributeError:
            pass
        self._connected = False

    ### Command methods ###

    def run_commands(self, commands):
        responses = list()

        for cmd in commands:
            meth = getattr(self, cmd.args.get('command_type'))
            responses.append(meth(str(cmd), output=cmd.output))

        for index, cmd in enumerate(commands):
            if cmd.output == 'xml':
                responses[index] = etree.tostring(responses[index])
            elif cmd.args.get('command_type') == 'rpc':
                responses[index] = str(responses[index].text).strip()

        return responses

    def cli(self, commands, output='xml'):
        '''Send commands to the device.'''
        try:
            return self.device.cli(commands, format=output, warning=False)
        except (ValueError, RpcError):
            exc = get_exception()
            self.raise_exc('Unable to get cli output: %s' % str(exc))

    def rpc(self, command, output='xml'):
        name, kwargs = rpc_args(command)
        meth = getattr(self.device.rpc, name)
        reply = meth({'format': output}, **kwargs)
        return reply

    ### Config methods ###

    def get_config(self, config_format="text"):
        if config_format not in SUPPORTED_CONFIG_FORMATS:
            self.raise_exc(msg='invalid config format.  Valid options are '
                           '%s' % ', '.join(SUPPORTED_CONFIG_FORMATS))

        ele = self.rpc('get_configuration', output=config_format)

        if config_format == 'text':
            return str(ele.text).strip()
        else:
            return ele

    def load_config(self,
                    config,
                    commit=False,
                    replace=False,
                    confirm=None,
                    comment=None,
                    config_format='text'):

        if replace:
            merge = False
            overwrite = True
        else:
            merge = True
            overwrite = False

        if overwrite and config_format == 'set':
            self.raise_exc(
                'replace cannot be True when config_format is `set`')

        self.lock_config()

        try:
            candidate = '\n'.join(config)
            self.config.load(candidate,
                             format=config_format,
                             merge=merge,
                             overwrite=overwrite)

        except ConfigLoadError:
            exc = get_exception()
            self.raise_exc('Unable to load config: %s' % str(exc))

        diff = self.config.diff()

        self.check_config()

        if all((commit, diff)):
            self.commit_config(comment=comment, confirm=confirm)

        self.unlock_config()

        return diff

    def save_config(self):
        raise NotImplementedError

    ### end of Config ###

    def get_facts(self, refresh=True):
        if refresh:
            self.device.facts_refresh()
        return self.device.facts

    def unlock_config(self):
        try:
            self.config.unlock()
            self._locked = False
        except UnlockError:
            exc = get_exception()
            raise NetworkError('unable to unlock config: %s' % str(exc))

    def lock_config(self):
        try:
            self.config.lock()
            self._locked = True
        except LockError:
            exc = get_exception()
            raise NetworkError('unable to lock config: %s' % str(exc))

    def check_config(self):
        if not self.config.commit_check():
            self.raise_exc(msg='Commit check failed')

    def commit_config(self, comment=None, confirm=None):
        try:
            kwargs = dict(comment=comment)
            if confirm and confirm > 0:
                kwargs['confirm'] = confirm
            return self.config.commit(**kwargs)
        except CommitError:
            exc = get_exception()
            raise NetworkError('unable to commit config: %s' % str(exc))

    def confirm_commit(self, checkonly=False):
        try:
            resp = self.rpc('get_commit_information')
            needs_confirm = 'commit confirmed, rollback' in resp[0][4].text
            if checkonly:
                return needs_confirm
            return self.commit_config()
        except IndexError:
            # if there is no comment tag, the system is not in a commit
            # confirmed state so just return
            pass

    def rollback_config(self, identifier, commit=True, comment=None):

        self.lock_config()

        try:
            self.config.rollback(identifier)
        except ValueError:
            exc = get_exception()
            self.raise_exc('Unable to rollback config: $s' % str(exc))

        diff = self.config.diff()
        if commit:
            self.commit_config(comment=comment)

        self.unlock_config()
        return diff
Exemple #37
0
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)
Exemple #38
0
    config = Config(dev)
    '''
    LOCK DEVICE CONFIG
    '''
    print("Locking the configuration")
    try:
        config.lock()
    except LockError as err:
        print("Unable to lock configuration: {0}".format(err))
    '''
    LOAD DEVICE CONFIG
    '''
    print("Loading configuration changes")
    try:
        config.load(template_path=template_file,
                    template_vars=device_vars,
                    merge=True)
    except (ConfigLoadError, Exception) as err:
        print("Unable to load configuration changes: {0}".format(err))
    '''
    COMMIT DEVICE CONFIG
    '''
    print("Committing the configuration")
    try:
        config.commit(comment='Loaded by example.')
    except CommitError as err:
        print("Unable to commit configuration: {0}".format(err))
    '''
    GENERATE THE CONFIG STATUS & SEND IT TO THE GUI 
    '''
# Copyright 2017, Juniper Networks Pvt Ltd.
# All rights reserved.
#

from jnpr.junos import Device
from jnpr.junos.utils.config import Config

with Device(host='X.X.X.X', user='******', password='******', mode='telnet', port='XX', gather_facts=True) as dev:
    cu = Config(dev)
    cu.load(path='/var/tmp/mx001-svn.conf', format='text', overwrite=True)
    print "Configuration Committed:", cu.commit()

# Script output
# automation@automation:~/pyezcookbook$ python initialinstall.py
# Configuration Committed: True
Exemple #40
0
for router_id, router_vars in my_vars.items():
    template = jinja2.Template(bgp_templatej)
    rtr_cfg - template.render(my_vars['juniper1'])
    print(rtr_cfg)
    print("This is router: {}".format(router_id))

a_device.timeout = 90
cfg = Config(a_device)

template_file = 'build.j2'
with open(template_file) as f:
    bgp_template = f.read()


print "Setting hostname using set notation"
cfg.load("set system host-name test1", format="set", merge=True)

print "Current config differences: "
print cfg.diff()

print "Performing rollback"
cfg.rollback(0)

print "\nSetting hostname using {} notation (external file)"
cfg.load(path="load_hostname.conf", format="text", merge=True)

print "Current config differences: "
print cfg.diff()

print "Performing commit"
cfg.commit()
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from pprint import pprint

junos_hosts = ["172.25.11.1"]
for ip in junos_hosts:
    dev = Device(host=host, user="******", password="******")
    dev.open()
    config = Config(dev)
    config.lock()
    config.load(path="add_snmp.conf", merge=True)
    config.pdiff()
    config.commit()
    config.unlock()
    dev.close()
Exemple #42
0
#---------------------------------------
CFG = Config(device1)
CFG.lock()

from Exercise2 import gather_routes

print("\n")
print("4a.ROUTE TABLE Before changes")
print("-" * 30)
k = gather_routes()
pprint(k)

print("\n")
print("4b.stage a configuration from a file")
print("-" * 30)
CFG.load(path="merge_exercise4.conf", format='text', merge=True)
print(CFG.diff())
CFG.commit()

print("\n")
print("4c.ROUTE TABLE After changes")
print("-" * 30)
L = gather_routes()
pprint(L)
print("\n")

print("\n")
print("4d.Delete Static Routes")
print("-" * 30)
CFG.load(path="delete_exercise4.conf", format='set', merge=True)
print(CFG.diff())
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from getpass import getpass

a_device = Device(host="srx2.lasthop.io", user="******", password=getpass())
a_device.open()
a_device.timeout = 60

cfg = Config(a_device)
cfg.lock()

cfg.load("set system host-name test123", format="set", merge=True)
cfg.rollback(0)

cfg.load("set system host-name test123", format="set", merge=True)
print(cfg.diff())

# cfg.commit()
# cfg.commit(comment="Testing from pyez")

cfg.load(path="test_config.conf", format="text", merge=True)
cfg.unlock()
Exemple #44
0
class JUNOS(BasePlugin):

    configuration = None
    quantity_of_times_to_try_lock = 3
    seconds_to_wait_to_try_lock = 10

    # Variables defined at networkapi/database
    alternative_variable_base_path_list = ['path_to_tftpboot']
    detailed_log_level_var = 'detailed_junos_log_level'
    detailed_log_level_used = None

    alternative_static_base_path_list = ['/mnt/scripts/tftpboot/']
    ignore_warning_list = ['statement not found']

    def __init__(self, **kwargs):
        super(JUNOS, self).__init__(connect_port=830, **kwargs)
        if 'quantity_of_times_to_try_lock' in kwargs:
            self.quantity_of_times_to_try_lock = kwargs.get('quantity_of_times_to_try_lock')

        if 'seconds_to_wait_to_try_lock' in kwargs:
            self.seconds_to_wait_to_try_lock = kwargs.get('seconds_to_wait_to_try_lock')

        # Logger objects to be disabled. Remove or add objects to array below:
        loggers = [device_logger, ssh_logger, session_logger, rpc_logger]
        detailed_log_level_used = self.set_detailed_junos_log_level(loggers)
        log.info("Detailed Junos log level: {}".format(detailed_log_level_used))

    def connect(self):

        """
        Connects to equipment via ssh using PyEz
        and create connection with invoked shell object.

        :returns:
            True on success or raise an exception on any
            fail (will NOT return a false result, due project decision).
        """

        if self.equipment_access is None:
            try:
                # Collect the credentials (user and password) for equipment
                self.equipment_access = EquipamentoAcesso.search(None,
                                                                 self.equipment,
                                                                 'ssh').uniqueResult()
            except Exception as e:
                message = "Unknown error while accessing equipment {} in database.".format(
                    self.equipment.nome)
                log.error("{}: {}".format(message, e))
                raise exceptions.APIException(message)

        log.info("Trying to connect on host {} ... ".format(self.equipment_access.fqdn))

        try:
            self.remote_conn = Device(
                host=self.equipment_access.fqdn,
                user=self.equipment_access.user,
                passwd=self.equipment_access.password,
                port=self.connect_port)
            self.remote_conn.open()
            self.configuration = Config(self.remote_conn)

            if self.remote_conn.connected:
                log.info("The connection on host {} was opened successfully!".format(self.equipment_access.fqdn))
                return True

        except ConnectError as e:
            message = "Authentication failed trying to connect host {}.".format(self.equipment_access.fqdn)
            log.error("{}: {}".format(message, e))
            raise exceptions.ConnectionException(message)

        except Exception as e:
            message = "Unknown error while connecting to host {}.".format(self.equipment_access.fqdn)
            log.error("{}: {}".format(message, e))
            raise exceptions.APIException(message)

    def close(self):

        """
        Disconnect to equipment via ssh using PyEz.

        :returns:
            True on success or raise an exception on any fail (will NOT return a false result, due project decision).
        """

        log.info("Trying to close connection on host {} ... ".format(self.equipment_access.fqdn))

        try:
            if self.remote_conn is not None:
                self.remote_conn.close()
                log.info("The connection was closed successfully on host {}!".format(self.equipment_access.fqdn))
                return True
            else:
                log.warning("To connection couldn't be closed because object is None")

        except ConnectClosedError as e:
            message = "Cannot close connection on juniper host {}.".format(self.equipment_access.fqdn)
            log.error("{}: {}".format(message, e))
            raise exceptions.APIException(message)

        except Exception as e:
            message = "Unknown error while closing connection on host {}.".format(self.equipment_access.fqdn)
            log.error("{}: {}".format(message, e))
            raise exceptions.APIException(message)

    def copyScriptFileToConfig(self, filename, use_vrf='', destination=''):

        """
        Receives the file path (usually in /mnt/scripts/tftpboot/networkapi/generated_config/interface/)
        where contains the command to be executed in the equipment

        :param str filename: must contain the full path and file name
        :param str use_vrf: not used
        :param str destination: not used

        :returns:
            Returns a success message, otherwise, raise an exception. That means will NOT return a false result.
        """

        log.info("Trying to load file configuration for host {} ...".format(self.equipment_access.fqdn))

        # 'filename' was defined in super class, but in plugin junos the 'file_path' will be used instead
        file_path = filename
        file_path = self.check_configuration_file_exists(file_path)

        try:

            command_file = open(file_path, "r")
            command = command_file.read()
            log.info("Load configuration from file {} successfully!".format(file_path))
            return self.exec_command(command)

        except IOError as e:
            self.close()
            message = "Configuration file not found."  # Message to client
            log.error("{} {}: {}".format(message, file_path, e))  # Message to log
            raise exceptions.APIException(message)
        # Caution using generic exception here (like Exception). May cause unexpected exception overlaps

    def exec_command(self, command, success_regex='', invalid_regex=None, error_regex=None):

        """
        Execute a junos command 'set' in the equipment.

        :param str command: junos command 'set'
        :param str success_regex: not used
        :param str invalid_regex: not used
        :param str error_regex: not used

        :returns:
            Returns a success message, otherwise, raise an exception. That means will NOT return a false result.
        """

        log.info("Trying to execute a configuration on host {} ... ".format(self.equipment_access.fqdn))

        try:
            self.__try_lock()
            self.configuration.rollback()
            self.configuration.load(command, format='set', ignore_warning=self.ignore_warning_list)
            self.configuration.commit_check()
            self.configuration.commit()
            self.configuration.unlock()

            result_message = "Configuration junos was executed successfully on {}".format(self.equipment_access.fqdn)
            log.info(result_message)
            return result_message

        except LockError as e:
            self.close()
            message = "Couldn't lock host {}.".format(self.equipment_access.fqdn)
            log.error("{}: {}".format(message, e))
            raise exceptions.APIException(message)

        except UnlockError as e:
            message = "Couldn't unlock host {}.".format(self.equipment_access.fqdn)
            log.error("{} (rollback and close will be tried for safety): {}".format(message, e))
            self.configuration.rollback()
            self.close()
            raise exceptions.APIException(message)

        except ConfigLoadError as e:
            message = "Couldn't load configuration on host {}. Please check template syntax.".format(
                self.equipment_access.fqdn)
            log.error("{} (rollback, unlock and close will be tried for safety): {}".format(message, e))
            self.configuration.rollback()
            self.configuration.unlock()
            self.close()
            raise exceptions.APIException(message)

        except CommitError as e:
            message = "Couldn't commit configuration on host {}.".format(self.equipment_access.fqdn)
            log.error("{} (rollback, unlock and close will be tried for safety): {}".format(message, e))
            self.configuration.rollback()
            self.configuration.unlock()
            self.close()
            raise exceptions.APIException(message)

        except RpcError as e:
            message = "A remote procedure call exception occurred on host {} ".format(self.equipment_access.fqdn)
            log.error("{} (close will be tried for safety): {}".format(message, e))
            self.close()
            raise exceptions.APIException(message)
        # Caution to use generic exception here, may cause overlaps in specific exceptions in try_lock()
        # except Exception, e:

    def ensure_privilege_level(self, privilege_level=None):

        """
        Ensure privilege level verifying if the current user is super-user.

        :returns:
            Returns True if success, otherwise, raise an exception (it will NOT return a false result)
        """

        log.info("Trying to ensure privilege level for user {} on host {} ... ".format(
            self.equipment_access.user, self.equipment_access.fqdn))

        try:
            # timeout: duration of time in seconds must wait for the expected result
            ss = StartShell(self.remote_conn, timeout=2)
            ss.open()
            output = ss.run('cli -c "show cli authorization"')

            # output is a tuple [bool, string], example:
            # (False, u'cli -c "show cli authorization"\r\r\nCurrent user: \'root        \' class \'super-user\ ....)
            # This string will be parsed to get the user class:

            # get the target part and split it by \n
            result = output[1].split('\n')

            # get the target part; split by '; and get the target part
            current_user_class = result[1].split("'")[3]

            if current_user_class != 'super-user':
                message = "Couldn't validate user privileges on host {}.".format(self.equipment_access.fqdn)
                log.error("{}. User {} class is '{}' and need to be 'super-user'"
                          "(close connection will be executed for safety)"
                          .format(message, self.equipment_access.user, current_user_class))
                self.close()
                raise exceptions.APIException(message)
            else:
                log.info("The privilege for user {} ('super-user') was satisfied on host {}!".format(
                    self.equipment_access.user, self.equipment_access.fqdn))
                return True

        except Exception as e:
            message = "Unknown error while verifying user privilege on host {} ".format(self.equipment_access.fqdn)
            log.error("(close connection will be executed for safety): {}".format(message, e))
            self.close()
            raise exceptions.APIException(message)

    def __try_lock(self):

        """
        Try to lock equipment.

        :returns:
            Returns True if success, otherwise, raise an exception. That means will NOT return a false result.
        """

        log.info("Trying to lock host {} ...".format(self.equipment_access.fqdn))

        for x in range(self.quantity_of_times_to_try_lock):
            try:
                self.configuration.lock()
                log.info("Host {} was locked successfully!".format(self.equipment_access.fqdn))
                return True
            except LockError as e:
                count = x + 1
                log.warning(
                    "Host {} could not be locked. Automatic try in {} seconds ({}/{}): {}".format(
                        self.equipment_access.fqdn,
                        self.seconds_to_wait_to_try_lock,
                        count,
                        self.quantity_of_times_to_try_lock,
                        e))
                time.sleep(self.seconds_to_wait_to_try_lock)

            except Exception as e:
                log.error("Unknown error while trying to lock c the equipment on host {}: {}".format(
                    self.equipment_access.fqdn, e))

        message = "Errors occurred in all attempts to lock {}. Anybody has locked?".format(self.equipment_access.fqdn)
        log.error(message)
        raise exceptions.APIException(message)

    def check_configuration_file_exists(self, file_path):

        """
        This function try to find and build (if necessary) the configuration file path. The priorities are:
        (1) build the full path from system variable base and relative file path ('file_path'); or
        (2) build the full path from static variable base and relative file path ('file_path'); or
        (3) return the relative path it self ('file_path')

        :param str file_path: Relative path, examples:
            'networkapi/plugins/Juniper/JUNOS/samples/sample_command.txt' or
            'networkapi/generated_config/interface/int-d_24823_config_ROR9BX3ATQG93TALJAMO2G'

        :return: Return a valid configuration file path string. Ex.:
        'networkapi/plugins/Juniper/JUNOS/samples/sample_command.txt' or
        '/mnt/scripts/tftpboot/networkapi/generated_config/interface/int-d_24823_config_ROR9BX3ATQG93TALJAMO2G'
        """

        log.info("Checking configuration file exist: {}".format(file_path))

        # Check in system variables
        for variable in self.alternative_variable_base_path_list:
            try:
                base_path = get_value(variable)
                if base_path != "":
                    result_path = base_path + file_path
                    if os.path.isfile(result_path):
                        log.info("Configuration file {} was found by system variable {}!".format(result_path, variable))
                        return result_path
            except (DatabaseError, VariableDoesNotExistException):
                # DatabaseError means that variable table do not exist
                pass
            except Exception as e:
                log.warning("Unknown error while calling networkapi.system.facade.get_value({}): {} {} ".format(
                    variable, e.__class__, e))

        # Check possible static variables
        for static_path in self.alternative_static_base_path_list:
            result_path = static_path + file_path
            if os.path.isfile(result_path):
                log.info("Configuration file {} was found by static variable {}!".format(result_path, static_path))
                return result_path

        # Check if relative path is valid (for dev tests)
        if os.path.isfile(file_path):
            log.info("Configuration file {} was found by relative path".format(file_path))
            return file_path

        message = "An error occurred while finding configuration file."
        log.error("{} Could not find in: relative path ('{}'), system variables ({}) or static paths ({})".format(
            message, file_path, self.alternative_variable_base_path_list, self.alternative_static_base_path_list))
        raise exceptions.APIException(message)

    def set_detailed_junos_log_level(self, loggers):

        """
        Used to disable logs from detailed and specific libs used in Junos plugin, for example:
        If 'ERROR' is defined, higher log messages will be disabled, like 'WARNING', 'INFO' and 'DEBUG'.

        :param str loggers: Array of logger objects
        :return: A valid level error ('ERROR', 'INFO', etc.), otherwise None
        """

        default_log_level = 'ERROR'
        log_level = None

        # Trying to get the variable from networkapi.
        try:
            log_level = get_value(self.detailed_log_level_var)
        except DatabaseError as e:
            log.warning("Database error while getting '{}' variable: {}".format(
                self.detailed_log_level_var, e))
        except VariableDoesNotExistException as e:
            log.warning("Variable '{}' does not exist: {}".format(
                self.detailed_log_level_var, e))
        except Exception as e:
            log.warning("Unknown error while getting '{}' variable: {} ".format(
                self.detailed_log_level_var, e))

        # If could not get the value earlier, a default value will be used
        if log_level is None or log_level == "":
            log.warning("Could not get '{}' variable from networkapi. ".format(
                self.detailed_log_level_var, default_log_level))
            log_level = default_log_level

        # Trying to set the level to each log object.
        for logger in loggers:
            try:
                logger.setLevel(log_level)
            except Exception as e:
                log.error("Invalid log level '{}'. The default {} will be used: {}".format(
                    log_level, default_log_level, e))
                log_level = default_log_level  # to be used at next iteration too
                logger.setLevel(log_level)

        return log_level
Exemple #45
0
    dev_dictionnary.update(item_vars)
    f.close()
    # build the configuration file from a jinja2 template for this item using the variable item_vars
    print item["host_name"] + '.oc.bgp.conf'
    conffile = open(item["host_name"] + '.oc.bgp.conf', 'w')
    conffile.write(template_bgp.render(dev_dictionnary))
    conffile.close()
print 'Done for all the devices!\n'

# load and commit the configuration file for each device
print 'Pushing and committing the configuration files to the devices ...'
for item in my_list_of_devices:
    dev = Device(host=item["management_ip"], user='******', password='******')
    dev.open()
    cfg = Config(dev)
    cfg.load(path=item["host_name"] + '.oc.bgp.conf', format='text')
    if cfg.commit(comment="from PyEZ") == True:
        print('Configuration commited successfully on ' + item["host_name"])
    else:
        print('Commit failed on ' + item["host_name"])
    dev.close()
print 'Done for all the devices!\n'

# Wait for 20 seconds. so BGP sessions will be established.
print 'Waiting 20 seconds before starting to audit the BGP sessions state ...\n'
time.sleep(20)
'''
audit BGP states with tables and view
Please add table and view for bgp before as it is not provided by PyEZ.
'''
print 'Auditing the BGP states using PyEZ Tables and Views:'
Exemple #46
0
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)
Exemple #47
0
    # Change to delete to turn led off.
    config_light.append('set poe interface %s' % (new_interface))

# Puts the config in the format Junos is expecting.
set_add = '\n'.join(map(str,config_add))
# These are seperate due to the way config_script sets it.
light_add = '\n'.join(map(str,config_light))

# Probably could merge this with set_add but ¯\_(ツ)_/¯
config_script = """
edit ethernet-switching-options secure-access-port
%s
""" % (set_add)

# Load and Commit the configuration to the switch
cu = Config(dev)
# Merges the config with the currently running config. 
# Probably could've merged light_add with config_script but if it aint broke.
cu.load(config_script, format="set", merge=True)
cu.load(light_add, format="set", merge=True)
# This try catch is here in case there's no difference between the running config and the proposed one.
# If you never see a difference and the ports aren't locking you are on a different version of ODL.
try:
    print 'These are the changes:\n ' + cu.diff()
except:
    print 'Nothing changed?'
# Commits the config. This could be put in the try catch but it won't hurt Junos to commit one with no changes.
cu.commit()
print "Configuration Successful! Goodbye."
dev.close()
Exemple #48
0
dev = Device(host="10.117.97.39", user="******")
conf = Config(dev)

config = """
system {
    name-server {
        8.8.5.5;
        8.8.3.3;
    }
}
"""

dev.open()
conf.lock()

conf.load(config, format="text")

if ( conf.commit_check() & (conf.diff() is not None) ):
   print ("Configuration is valid and applied")
   conf.pdiff()
   conf.commit()
elif ( conf.commit_check() & (conf.diff() is None) ):
   print ("Configuration is already thier, nothing to be added!")
else:
   print ("Configuration is NOT valid and rollback issued")
   conf.rollback()

conf.unlock()
dev.close()

Exemple #49
0
jnpr_device.open()
jnpr_device.timeout = 60

jnpr_device_cfg = Config(jnpr_device)

try:
    jnpr_device_cfg.lock()
except LockError as e:
    print("Config session already locked, exiting")
    sys.exit()

# get current routing table
routing_table = gather_routes(jnpr_device)

# install routing from file
jnpr_device_cfg.load(path=routes_cfg_file, format="text", merge=True)

# commit change
jnpr_device_cfg.commit(comment="adding 2 discard routes")

# get routing table after config change
routing_table_new = gather_routes(jnpr_device)

# comparing routing tables
old_routes = []
new_routes = []
## build a list of dst routes for old table
for route in routing_table.items():
    old_routes.append(route[0])

for new_route in routing_table_new.items():
Exemple #50
0
# Create device Config object
my_device_cfg = Config(my_device)

# Lock device configuration
my_device_cfg.lock()

# Try to acquire Lock again
print()
try:
    my_device_cfg.lock()
    print("Lock acquired!")
except LockError:
    print("Device is already locked.")

# Stage a config to change the device hostname
my_device_cfg.load("set system host-name python4life", format="set", merge=True)

# Check the diff of the staged vs running config
print()
print("Check diff of staged-config vs running-config")
print("-" * 20)
print(my_device_cfg.diff())

# Rollback staged configuration
my_device_cfg.rollback(0)

# Check the diff after the rollback operation
print()
print("Check diff of staged-config vs running-config")
print("-" * 20)
print(my_device_cfg.diff())
#-----------------------------------------------------------------------------------------------------------------------
# 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()
Exemple #52
0
def push_config(conf_string, ip, user, pw):
    dev = get_device_reference(ip, user, pw)

    # try to determine the format of our config_string
    config_format = 'set'
    if re.search(r'^\s*<.*>$', conf_string, re.MULTILINE):
        config_format = 'xml'
    elif re.search(r'^\s*(set|delete|replace|rename)\s', conf_string):
        config_format = 'set'
    elif re.search(r'^[a-z:]*\s*\w+\s+{', conf_string, re.I) and re.search(
            r'.*}\s*$', conf_string):
        config_format = 'text'

    logger.debug("using format: " + config_format)
    cu = Config(dev)
    try:
        cu.lock()
    except LockError as le:
        logger.debug("Could not lock database!")
        logger.debug(str(le))
        dev.close()
        return False

    try:
        cu.load(conf_string, format=config_format)
    except Exception as e:
        logger.debug("Could not load configuration")
        logger.debug(str(e))
        dev.close()
        return False

    diff = cu.diff()
    logger.debug(diff)
    if diff is not None:
        try:
            cu.commit_check()
            logger.debug("Committing config!")
            cu.commit(comment="Commit via wistar")

        except CommitError as ce:
            logger.debug("Could not load config!")
            cu.rollback()
            logger.debug(repr(ce))
            return False

    else:
        # nothing to commit
        logger.debug("Nothing to commit - no diff found")
        return True

    try:
        logger.debug("Unlocking database!")
        cu.unlock()
    except UnlockError as ue:
        logger.debug("Could not unlock database")
        logger.debug(str(ue))
        return False

    logger.debug("Closing device handle")
    dev.close()
    return True
Exemple #53
0
from jnpr.junos.device import Device
from jnpr.junos.utils.config import Config
from pprint import pprint
from jnpr.junos.exception import *

junos_hosts = ['172.25.11.1', '1.1.1.1']
Device.auto_probe = 10

for ip in junos_hosts:
    try:
        dev = Device(host=ip, user='******', password='******')
        dev.open()
        config = Config(dev)
        config.lock()
        config.load(path='add_snmp.conf', merge=True)
        config.pdiff()
        config.commit()
        config.unlock()
        dev.close()
    except ConnectionTimeoutError as e:
        print('Connection time out!')
Exemple #54
0
class NetconfConnection(AbstractConnection):
    ''' Netconf connection class
    '''
    def __init__(self, host, username='******', password='******',
        logger=None, **kwargs):
        self.host = host
        self.username = username
        self.password = password
        self.handle = None
        self.logger = kwargs.get('logger', contrail_logging.getLogger(__name__))
        self.config_handle = None
        self.mode = kwargs.get('mode')
        self.port = kwargs.get('port',None)
    def connect(self):
        if self.port:
            self.handle = Device(host=self.host, user=self.username,
                password=self.password, mode=self.mode, port=self.port)
        else:
            self.handle = Device(host=self.host, user=self.username,
                password=self.password, mode=self.mode)
        try:
            self.handle.open(gather_facts=False)
            self.config_handle = Config(self.handle)
        except (ConnectAuthError,ConnectRefusedError, ConnectTimeoutError,
            ConnectError) as e:
            self.logger.exception(e)
        return self.handle
    # end connect

    def disconnect(self):
        with gevent.Timeout(15.0, False):
            self.handle.close()

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

    def zeroize(self):
        with gevent.Timeout(15.0, False):
            try:
                self.handle.zeroize()
            except Exception as e:
                pass

    def get_config(self, mode='set'):
        configs = self.handle.rpc.get_config(options={'database' : 'committed',
                                                      'format': mode})
        return configs.text

    def get_interfaces(self, terse=True):
        output = self.handle.rpc.get_interface_information(terse=terse)
        return EtreeToDict('physical-interface').get_all_entry(output)

    def config(self, stmts=[], commit=True, merge=True, overwrite=False,
               path=None, ignore_errors=False, timeout=30):
        if path:
            self.config_handle.load(path=path, overwrite=overwrite,
                                    timeout=timeout)
        else:
          for stmt in stmts:
            try:
                self.config_handle.load(stmt, format='set', merge=True)
            except ConfigLoadError as e:
                if ignore_errors:
                    self.logger.debug('Exception %s ignored' % (e))
                    self.logger.exception(e)
                else:
                    raise e
        if commit:
            try:
                self.config_handle.commit(timeout=timeout)
            except CommitError as e:
                self.logger.exception(e)
                return (False,e)
        return (True, None)
    
    def restart(self, process_name):
        #TODO Not sure of apis other than cli
        self.handle.cli('restart %s' % (process_name))

    def get_mac_address(self, interface):
        # Use physical interface
        interface = interface.split('.')[0]
        xml_resp = self.handle.rpc.get_interface_information(interface_name=interface)
        mac_address = xml_resp.findtext(
            'physical-interface/current-physical-address')
        return mac_address.rstrip('\n').lstrip('\n')
    # end get_mac_address

    def get_mac_in_arp_table(self, ip_address):
        # From 'show arp' output, get the MAC address 
        # of a IP 
        xml_resp = self.handle.rpc.get_arp_table_information(no_resolve=True)
        arp_entries = xml_resp.findall('arp-table-entry')
        for arp_entry in arp_entries:
            if arp_entry.find('ip-address').text.strip() == ip_address:
                mac = arp_entry.find('mac-address').text.strip()
                self.logger.debug('Found MAC %s for IP %s in arp table of '
                    '%s' % (mac, ip_address, self.host))
                return mac
        self.logger.warn('IP %s not found in arp table of %s' % (
            ip_address, self.host)) 
        return None
Exemple #55
0
def lPushConfig(lConfigList):
    with open('lAddTemplate.j2') as lTA_fh:
        lTAdd_format = lTA_fh.read()

    with open('lDelTemplate.j2') as lTD_fh:
        lTDel_format = lTD_fh.read()

    # This section is for logging
    lLgr = logging.getLogger('lync_pushconfig')
    lLgr.setLevel(logging.INFO)

    lLog_fh = logging.FileHandler('lync_pushconfig.log')
    lLog_fh.setLevel(logging.INFO)

    lFrmt = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    lLog_fh.setFormatter(lFrmt)
    lLgr.addHandler(lLog_fh)

    #Prepare the configuration that needs to be pushed to this switch
    lTempData = {}
    lAddTemplate = Template(lTAdd_format)
    lDelTemplate = Template(lTDel_format)

    lClistRoot = ET.fromstring(lConfigList)

    lSwitch = Device(host=lClistRoot[0][1].text,
                     user='******',
                     password='******')

    #Open connection to the switch
    lSwitch.open()
    lSwitchConf = Config(lSwitch)

    lLgr.info("\n\n\n\n")
    lLgr.info(lSwitch)

    for lConfig in lClistRoot:
        if lConfig[0].text == "Add":
            lTempData['lIP'] = lConfig[3].text
            lTempData['lPort'] = lConfig[4].text
            lTempData['lInt'] = lConfig[2].text
            lAllConfig = lAddTemplate.render(lTempData)
            #Push config to switch
            print "\nPushing Config to " + str(lSwitch) + "\n"
            print lAllConfig + "\n\n"
            lSwitchConf.load(lAllConfig, format='set')
            lLgr.info("\n")
            lLgr.info(lAllConfig)
        else:
            lTempData['lIP'] = lConfig[3].text
            lTempData['lPort'] = lConfig[4].text
            lTempData['lInt'] = lConfig[2].text
            lAllConfig = lDelTemplate.render(lTempData)
            #Push config to switch
            print "\nPushing Config to " + str(lSwitch) + "\n"
            print lAllConfig + "\n\n"
            lSwitchConf.load(lAllConfig, format='set')
            lLgr.info("\n")
            lLgr.info(lAllConfig)

    #Commit configuration changes
    lSwitchConf.commit()

    #Close connection to the switch
    lSwitch.close()
Exemple #56
0
from jnpr.junos.utils.config import Config
import time

f = open('configure_appformix/network_devices.yml', 'r')
my_vars = load(f.read())
f.close()

dev = Device(host="192.168.128.194",
             user=my_vars['jti']['username'],
             password=my_vars['jti']['password'])
dev.open(gather_facts=False)

conf = '''
set interfaces ge-0/0/1 mtu 1000
'''
cfg = Config(dev)
cfg.lock()
cfg.load(conf, format='set')
cfg.pdiff()
cfg.commit(comment="configured from pyez")

print 'wait 70 seconds'
time.sleep(70)

cfg.rollback(1)
cfg.pdiff()
cfg.commit(comment="rollbacked from pyez")

cfg.unlock()
dev.close()
Exemple #57
0
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()
Exemple #58
0
    ospf_cfg = dev.rpc.get_config(filter_xml=etree.XML(
        "<configuration><protocols><ospf/></protocols></configuration>"))
    # dump(ospf_cfg)

    interfaces = ospf_cfg.xpath("protocols/ospf/area/interface/name")

    # if_list = []
    # for interface in interfaces:
    #     iface = interface.text
    #     phy_ifa = iface.split(".")[0]
    #     if_list.append(phy_ifa)

    # Do the same with list comprehension
    if_list = [interface.text.split(".")[0] for interface in interfaces]

    print(if_list)

    config = ""
    for iface in if_list:
        config += 'set interfaces {} description "OSPF is enabled"\n'.format(
            iface)

    print(config)

    cu = Config(dev)
    cu.lock()
    cu.load(config, format="set")
    cu.pdiff()
    cu.commit()
    cu.unlock()
Exemple #59
0
class Netconf(object):

    def __init__(self):
        if not HAS_PYEZ:
            raise NetworkError(
                msg='junos-eznc >= 1.2.2 is required but does not appear to be installed.  '
                'It can be installed using `pip install junos-eznc`'
            )
        if not HAS_JXMLEASE:
            raise NetworkError(
                msg='jxmlease is required but does not appear to be installed.  '
                'It can be installed using `pip install jxmlease`'
            )
        self.device = None
        self.config = None
        self._locked = False
        self._connected = False
        self.default_output = 'xml'

    def raise_exc(self, msg):
        if self.device:
            if self._locked:
                self.config.unlock()
            self.disconnect()
        raise NetworkError(msg)

    def connect(self, params, **kwargs):
        host = params['host']

        kwargs = dict()
        kwargs['port'] = params.get('port') or 830

        kwargs['user'] = params['username']

        if params['password']:
            kwargs['passwd'] = params['password']

        if params['ssh_keyfile']:
            kwargs['ssh_private_key_file'] = params['ssh_keyfile']

        kwargs['gather_facts'] = False

        try:
            self.device = Device(host, **kwargs)
            self.device.open()
        except ConnectError:
            exc = get_exception()
            self.raise_exc('unable to connect to %s: %s' % (host, str(exc)))

        self.config = Config(self.device)
        self._connected = True

    def disconnect(self):
        try:
            self.device.close()
        except AttributeError:
            pass
        self._connected = False

    ### Command methods ###

    def run_commands(self, commands):
        responses = list()

        for cmd in commands:
            meth = getattr(self, cmd.args.get('command_type'))
            responses.append(meth(str(cmd), output=cmd.output))

        for index, cmd in enumerate(commands):
            if cmd.output == 'xml':
                responses[index] = xml_to_json(responses[index])
            elif cmd.args.get('command_type') == 'rpc':
                responses[index] = str(responses[index].text).strip()
            elif 'RpcError' in responses[index]:
                raise NetworkError(responses[index])


        return responses

    def cli(self, commands, output='xml'):
        '''Send commands to the device.'''
        try:
            return self.device.cli(commands, format=output, warning=False)
        except (ValueError, RpcError):
            exc = get_exception()
            self.raise_exc('Unable to get cli output: %s' % str(exc))

    def rpc(self, command, output='xml'):
        name, kwargs = rpc_args(command)
        meth = getattr(self.device.rpc, name)
        reply = meth({'format': output}, **kwargs)
        return reply

    ### Config methods ###

    def get_config(self, config_format="text"):
        if config_format not in SUPPORTED_CONFIG_FORMATS:
            self.raise_exc(msg='invalid config format.  Valid options are '
                               '%s' % ', '.join(SUPPORTED_CONFIG_FORMATS))

        ele = self.rpc('get_configuration', output=config_format)

        if config_format == 'text':
            return unicode(ele.text).strip()
        else:
            return ele

    def load_config(self, config, commit=False, replace=False, confirm=None,
                    comment=None, config_format='text', overwrite=False):

        if all([replace, overwrite]):
            self.raise_exc('setting both replace and overwrite to True is invalid')

        if replace:
            merge = False
            overwrite = False
        elif overwrite:
            merge = True
            overwrite = False
        else:
            merge = True
            overwrite = False

        if overwrite and config_format == 'set':
            self.raise_exc('replace cannot be True when config_format is `set`')

        self.lock_config()

        try:
            candidate = '\n'.join(config)
            self.config.load(candidate, format=config_format, merge=merge,
                             overwrite=overwrite)

        except ConfigLoadError:
            exc = get_exception()
            self.raise_exc('Unable to load config: %s' % str(exc))

        diff = self.config.diff()

        self.check_config()

        if all((commit, diff)):
            self.commit_config(comment=comment, confirm=confirm)

        self.unlock_config()

        return diff

    def save_config(self):
        raise NotImplementedError

    ### end of Config ###

    def get_facts(self, refresh=True):
        if refresh:
            self.device.facts_refresh()
        return self.device.facts

    def unlock_config(self):
        try:
            self.config.unlock()
            self._locked = False
        except UnlockError:
            exc = get_exception()
            raise NetworkError('unable to unlock config: %s' % str(exc))

    def lock_config(self):
        try:
            self.config.lock()
            self._locked = True
        except LockError:
            exc = get_exception()
            raise NetworkError('unable to lock config: %s' % str(exc))

    def check_config(self):
        if not self.config.commit_check():
            self.raise_exc(msg='Commit check failed')

    def commit_config(self, comment=None, confirm=None):
        try:
            kwargs = dict(comment=comment)
            if confirm and confirm > 0:
                kwargs['confirm'] = confirm
            return self.config.commit(**kwargs)
        except CommitError:
            exc = get_exception()
            raise NetworkError('unable to commit config: %s' % str(exc))

    def confirm_commit(self, checkonly=False):
        try:
            resp = self.rpc('get_commit_information')
            needs_confirm = 'commit confirmed, rollback' in resp[0][4].text
            if checkonly:
                return needs_confirm
            return self.commit_config()
        except IndexError:
            # if there is no comment tag, the system is not in a commit
            # confirmed state so just return
            pass

    def rollback_config(self, identifier, commit=True, comment=None):

        self.lock_config()

        try:
            self.config.rollback(identifier)
        except ValueError:
            exc = get_exception()
            self.raise_exc('Unable to rollback config: $s' % str(exc))

        diff = self.config.diff()
        if commit:
            self.commit_config(comment=comment)

        self.unlock_config()
        return diff
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.exception import *
from jinja2 import Template
import yaml
import sys

junos_hosts = ["vMX-1"]

for host in junos_hosts:
    with open(host + ".yml", "r") as yml_var:
        data = yaml.load(yml_var.read())
    with open("snmp.j2", "r") as j2_var:
        t_format = j2_var.read()
    template = Template(t_format)
    myConfig = template.render(data)
    print("\nResults for device " + host)
    print (myConfig)
    dev = Device(host=host, user="******", password="******")
    dev.open()
    config = Config(dev)
    config.lock()
    config.load(myConfig, merge=True, format ="text")
    config.pdiff()
    config.commit()
    config.unlock()
    dev.close()