Python jnpr.junos.utils.config.Config() Examples

The following are 9 code examples of jnpr.junos.utils.config.Config(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module jnpr.junos.utils.config , or try the search function .
Example #1
Source File: example.py    From network-programmability-stream with MIT License 6 votes vote down vote up
def configure_device(connection_params, variables):
    device_connection = Device(**connection_params)
    device_connection.open()
    # device_connection.facts_refresh()
    facts = device_connection.facts

    hostname = facts['hostname']

    config_variables = variables['devices'][hostname]

    with Config(device_connection, mode='private') as config:
        config.load(template_path='templates/candidate.conf', template_vars=config_variables, merge=True)
        print("Config diff:")
        config.pdiff()
        config.commit()
        print(f'Configuration was updated successfully on {hostname}')

    device_connection.close() 
Example #2
Source File: ex4_jnpr_cfg_routes.py    From pyplus_course with Apache License 2.0 6 votes vote down vote up
def cleanup_routes(dev):
    """Remove the static routes that were added in this exercise."""
    # Create Config object
    cfg = Config(dev)
    cfg.lock()
    # Use set format to delete previously created static routes
    cfg.load(
        "delete routing-options static route 203.0.113.5/32", format="set", merge=True
    )
    cfg.load(
        "delete routing-options static route 203.0.113.200/32", format="set", merge=True
    )
    print()
    print("Cleaning up routes that were added in this exercise.")
    print("\n\n")
    if cfg.diff() is not None:
        cfg.commit()
    cfg.unlock() 
Example #3
Source File: enable_a_disabled_interface.py    From junos_monitoring_with_healthbot with MIT License 5 votes vote down vote up
def enable_interface(int, **kwargs):
	junos_details = get_junos_details(kwargs['device_id'])
	junos_host = junos_details['host']
	junos_user = junos_details['authentication']['password']['username']
	# junos_password = junos_details['authentication']['password']['password']
	junos_password = 'Juniper!1'
	device=Device(host=junos_host, user=junos_user, password=junos_password)
	device.open()
	cfg=Config(device)
	my_template = Template('delete interfaces {{ interface }} disable')
	cfg.load(my_template.render(interface = int), format='set')
	cfg.commit()
	device.close() 
Example #4
Source File: change-mtu-config.py    From junos_monitoring_with_healthbot with MIT License 5 votes vote down vote up
def add_config(router,interface,mtu,**kwargs):
    r = requests.get('http://api_server:9000/api/v1/device/%s/' % router, verify=False)
    device_info = r.json()
    hostname = device_info['host']
    userid = device_info['authentication']['password']['username']
    password = device_info['authentication']['password']['password']
    dev = Device(host=hostname, user=userid, password=password, normalize=True)
    dev.open()
    cu = Config(dev)
    data = "set interfaces %s mtu %s" % (interface,mtu)
    cu.load(data, format='set')
    cu.commit()
    dev.close() 
Example #5
Source File: ex4_jnpr_cfg_routes.py    From pyplus_course with Apache License 2.0 5 votes vote down vote up
def config_from_file(path, dev, merge=True):
    """Function to load config from file and commit it to a device."""
    # Create Config object
    cfg = Config(dev)
    cfg.lock()
    # Load configuration from file; default to merge operation
    cfg.load(path=path, format="text", merge=merge)
    if cfg.diff() is not None:
        cfg.commit()
    cfg.unlock() 
Example #6
Source File: ex6_pyez_change_hostname.py    From python_course with Apache License 2.0 4 votes vote down vote up
def main():
    '''
    Exercise using Juniper's PyEZ to make changes to device in various ways
    '''
    pwd = getpass()
    try:
        ip_addr = raw_input("Enter Juniper SRX IP: ")
    except NameError:
        ip_addr = input("Enter Juniper SRX IP: ")
    ip_addr = ip_addr.strip()

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

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

    cfg = Config(a_device)

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

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

    print("Performing rollback")
    cfg.rollback(0)

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

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

    print("Performing commit")
    cfg.commit()

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

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

    print("Performing commit")
    cfg.commit()
    print() 
Example #7
Source File: ex4_change_hostname.py    From pynet with Apache License 2.0 4 votes vote down vote up
def main():
    '''
    Exercise using Juniper's PyEZ to make changes to device in various ways
    '''
    pwd = getpass()
    ip_addr = raw_input("Enter Juniper SRX IP: ")
    ip_addr = ip_addr.strip()

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

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

    cfg = Config(a_device)

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

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

    print "Performing rollback"
    cfg.rollback(0)

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

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

    print "Performing commit"
    cfg.commit()

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

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

    print "Performing commit"
    cfg.commit()
    print 
Example #8
Source File: ex4_change_hostname.py    From pynet with Apache License 2.0 4 votes vote down vote up
def main():
    '''
    Exercise using Juniper's PyEZ to make changes to device in various ways
    '''
    pwd = getpass()
    ip_addr = raw_input("Enter Juniper SRX IP: ")
    ip_addr = ip_addr.strip()

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

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

    cfg = Config(a_device)

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

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

    print "Performing rollback"
    cfg.rollback(0)

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

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

    print "Performing commit"
    cfg.commit()

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

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

    print "Performing commit"
    cfg.commit()
    print 
Example #9
Source File: Junos.py    From assimilator with MIT License 4 votes vote down vote up
def post(self,comment):
		if not self.dev.connected:
			logger.error("{0}: Firewall timed out or incorrect device credentials.".format(self.firewall_config['name']))
			return {'error' : 'Could not connect to device.'}, 504
		else:
			logger.info("{0}: Connected successfully.".format(self.firewall_config['name']))
		self.dev.bind(cu=Config)
		try:	
			#self.dev.cu.lock()
			pass
		except LockError:
			logger.error("Configuration locked.")
			self.dev.close()
			return {'error' : 'Could not lock configuration.'}, 504
		else:
			logger.info("Locked configuration.")
		try:
			if comment:
				self.dev.cu.commit(comment=comment)
			else:
				self.dev.cu.commit()
		except CommitError:
			logger.error("Unable to commit.")
			try:
				logger.info("Unlocking configuration...")
				#self.dev.cu.unlock()
				pass
			except UnlockError:
				logger.error("Unable to unlock configuration: {0}".format(str(err)))
				return {'error' : 'Unable to commit and unlock configuration.'}, 504
			else:
				logger.info("Configuration unlocked.")
				return {'error' : 'Unable to commit.'}, 504
		else:
			logger.info("Configuration commited successfully.")
			logger.info("Unlocking configuration...")
			try:
				#self.dev.cu.unlock()
				pass
			except UnlockError:
				logger.error("Unable to unlock configuration: {0}".format(str(err)))
				return {'error' : 'Configuration commited but cannot unlock configuration.'}, 504
			else:
				logger.info("Configuration unlocked.")
				return {'commit' : 'success'}
		finally:
			logger.info("Closing connection...")
			self.dev.close()