Python jnpr.junos.Device() Examples

The following are 26 code examples of jnpr.junos.Device(). 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 , or try the search function .
Example #1
Source File: ex3_pyez_facts.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    """Connect to Juniper device using PyEZ. Display device facts."""
    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()
    pprint(a_device.facts)
    print() 
Example #2
Source File: get-interface-from-arp-ip.py    From nrelabs-curriculum with Apache License 2.0 6 votes vote down vote up
def myfunc(*args):

    devices = args[0]["devices"]
    username = args[0]["username"][0]
    secret = args[0]["password"][0]
    hosts = args[0]["hosts"]

    arpinfo = {}
    for device in devices:
        dev, port = device.split(":")

        handle = Device(host=dev, port=port, user=username, passwd=secret)
        handle.open()
        devname = handle.rpc.get_system_information().find('host-name').text


        for host in hosts:
            arptable = handle.rpc.get_arp_table_information(hostname=str(host))
            for intname in arptable.findall("./arp-table-entry/interface-name"):
                if devname in arpinfo:
                    arpinfo[devname].append(intname.text.strip())
                else:
                    arpinfo[devname] = [intname.text.strip()]

    out(arpinfo) 
Example #3
Source File: Junos.py    From assimilator with MIT License 6 votes vote down vote up
def __init__(self,firewall_config):
		self.firewall_config = firewall_config
		try:
			assert self.firewall_config['privatekey']
			assert self.firewall_config['privatekeypass']
		except:
			#User password connection
			logger.info("Juniper User/Password connection.")
			self.dev = Device(host=self.firewall_config['primary'], password=self.firewall_config['pass'],\
								user=self.firewall_config['user'], port=self.firewall_config['port'], gather_facts=False)
		else:
			#RSA SSH connection
			logger.info("Juniper RSA SSH connection.")
			self.dev = Device(host=self.firewall_config['primary'], passwd=self.firewall_config['privatekeypass'],\
								ssh_private_key_file=self.firewall_config['privatekey'],user=self.firewall_config['user'],\
								port=self.firewall_config['port'], gather_facts=False)
		self.dev.open(normalize=True)
		try:
			self.dev.timeout = int(self.firewall_config['timeout']) if self.firewall_config['timeout'] else 15
		except (ValueError, KeyError):
			logger.warning("Firewall timeout is not an int, setting default value.")
			self.dev.timeout = 15
		self.primary = self.firewall_config['primary'] 
Example #4
Source File: ex1_display_facts.py    From pynet with Apache License 2.0 6 votes vote down vote up
def main():
    '''
    Connect to Juniper device using PyEZ. Display device facts.
    '''
    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()
    pprint(a_device.facts)
    print 
Example #5
Source File: ex1_display_facts.py    From pynet with Apache License 2.0 6 votes vote down vote up
def main():
    '''
    Connect to Juniper device using PyEZ. Display device facts.
    '''
    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()
    pprint(a_device.facts)
    print 
Example #6
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 #7
Source File: ex2_eth_stats.py    From pynet with Apache License 2.0 5 votes vote down vote up
def main():
    '''
    Connect to Juniper device using PyEZ. Display operational state and pkts_in, pkts_out for all
    of the interfaces.
    '''
    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()

    eth_ports = EthPortTable(a_device)
    eth_ports.get()

    print "{:>15} {:>12} {:>12} {:>12}".format("INTF", "OPER STATE", "IN PACKETS", "OUT PACKETS")
    for intf, eth_stats in eth_ports.items():
        eth_stats = dict(eth_stats)
        oper_state = eth_stats['oper']
        pkts_in = eth_stats['rx_packets']
        pkts_out = eth_stats['tx_packets']
        print "{:>15} {:>12} {:>12} {:>12}".format(intf, oper_state, pkts_in, pkts_out)
    print 
Example #8
Source File: JunosDevice.py    From nrelabs-curriculum with Apache License 2.0 5 votes vote down vote up
def connect_device(self,host, user, password):
        self.device = Device(host, user=user, password=password, port=22)
        self.device.open() 
Example #9
Source File: JunosDevice.py    From nrelabs-curriculum with Apache License 2.0 5 votes vote down vote up
def connect_device(self,host, user, password):
        self.device = Device(host, user=user, password=password, port=22)
        self.device.open() 
Example #10
Source File: ex7_rpc_show_version.py    From python_course with Apache License 2.0 5 votes vote down vote up
def main():
    """Use Juniper PyEZ and direct RPC to retrieve the XML for 'show version' from the SRX."""
    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()

    # show version | display xml rpc
    # get-software-information
    show_version = a_device.rpc.get_software_information()
    print()
    print("Print show version XML out as a string (retrieved via PyEZ RPC):")
    print("-" * 20)
    print(etree.tostring(show_version, pretty_print=True).decode())
    model = show_version.xpath("product-model")[0].text
    print()
    print("-" * 20)
    print("SRX Model: {}".format(model))
    print() 
Example #11
Source File: ex5_pyez_routes.py    From python_course with Apache License 2.0 5 votes vote down vote up
def main():
    '''
    Connect to Juniper device using PyEZ. Display the routing table.
    '''
    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()

    routes = RouteTable(a_device)
    routes.get()

    print("\nJuniper SRX Routing Table: ")
    for a_route, route_attr in routes.items():
        print("\n" + a_route)
        for attr_desc, attr_value in route_attr:
            print("  {} {}".format(attr_desc, attr_value))

    print("\n") 
Example #12
Source File: junos_bgp_summary.py    From ansible-junos-extras with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def connect(args):
    dev = Device(args['host'], user=args['user'], passwd=args['passwd'])
    try:
        dev.open()
    except Exception as err:
        msg = "Unable to conntect to {}.\n" \
              "Error: {}".format(args['host'], str(err))
        module.fail(msg=msg)
        return
    else:
        return dev 
Example #13
Source File: junos_lldp.py    From ansible-junos-extras with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            user=dict(required=False, default=os.getenv('USER')),
            passwd=dict(required=False, default=None)),
        supports_check_mode=False)

    m_args = module.params
    m_results = dict(changed=False)
    dev = Device(m_args['host'], user=m_args['user'], passwd=m_args['passwd'])
    try:
        dev.open()
    except Exception as err:
        msg = 'unable to connect to {}: {}'.format(m_args['host'], str(err))
        module.fail_json(msg=msg)
        return
    results = {}
    lldp_results = []
    try:
        lldp = LLDPNeighborTable(dev)
        lldp.get()
        lldp = json.loads(json.dumps(lldp, cls=TableJSONEncoder))
    except Exception as err:
        dev.close()
        module.fail_json(msg=err)
        return
    dev.close()
    module.exit_json(results=lldp) 
Example #14
Source File: junos_ospf.py    From ansible-junos-extras with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def connect(args):
    dev = Device(args['host'], user=args['user'], passwd=args['passwd'])
    try:
        dev.open()
    except Exception as err:
        msg = "Unable to conntect to {}.\n" \
              "Error: {}".format(args['host'], str(err))
        module.fail(msg=msg)
        return
    else:
        return dev 
Example #15
Source File: pyez_mock.py    From open-nti with Apache License 2.0 5 votes vote down vote up
def mocked_device(rpc_reply_dict, mock_connect):
    """Juniper PyEZ Device Fixture"""
    def mock_manager(*args, **kwargs):
        if 'device_params' in kwargs:
            # open connection
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)
        elif args:
            # rpc request
            rpc_request = args[0].tag
            rpc_command = str(args[0].text)
            rpc_command = rpc_command.strip()
            rpc_command = rpc_command.replace(" ", "_")
            if rpc_request in rpc_reply_dict:
                xml = rpc_reply_dict[rpc_request]
            elif 'dir' in rpc_reply_dict:
                fname = os.path.join(rpc_reply_dict['dir'], 'rpc-reply', rpc_command, rpc_request + '.xml')
                with open(fname, 'r') as f:
                    xml = f.read()
            else:
                _rpc_reply_dict['dir']
                fname = os.path.join(os.path.dirname(__file__), 'rpc-reply', rpc_command, rpc_request + '.xml')
                with open(fname, 'r') as f:
                    xml = f.read()
            rpc_reply = NCElement(xml, dev._conn._device_handler.transform_reply())
            return rpc_reply
    mock_connect.side_effect = mock_manager
    dev = Device(host='1.1.1.1', user='juniper', gather_facts=False)
    dev.open()
    dev._conn.rpc = MagicMock(side_effect=mock_manager)
    dev.close = MagicMock()
    return dev 
Example #16
Source File: pyez_unittest.py    From nwkauto with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.dev = Device(
            host='127.0.0.1', user='root', password='Juniper', port='2222'
        )
        self.dev.open() 
Example #17
Source File: ex4_pyez_eth.py    From python_course with Apache License 2.0 5 votes vote down vote up
def main():
    '''
    Connect to Juniper device using PyEZ. Display operational state and pkts_in, pkts_out for all
    of the interfaces.
    '''
    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()

    eth_ports = EthPortTable(a_device)
    eth_ports.get()

    print("{:>15} {:>12} {:>12} {:>12}".format("INTF", "OPER STATE", "IN PACKETS", "OUT PACKETS"))
    for intf, eth_stats in eth_ports.items():
        eth_stats = dict(eth_stats)
        oper_state = eth_stats['oper']
        pkts_in = eth_stats['rx_packets']
        pkts_out = eth_stats['tx_packets']
        print("{:>15} {:>12} {:>12} {:>12}".format(intf, oper_state, pkts_in, pkts_out))
    print() 
Example #18
Source File: ex2_eth_stats.py    From pynet with Apache License 2.0 5 votes vote down vote up
def main():
    '''
    Connect to Juniper device using PyEZ. Display operational state and pkts_in, pkts_out for all
    of the interfaces.
    '''
    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()

    eth_ports = EthPortTable(a_device)
    eth_ports.get()

    print "{:>15} {:>12} {:>12} {:>12}".format("INTF", "OPER STATE", "IN PACKETS", "OUT PACKETS")
    for intf, eth_stats in eth_ports.items():
        eth_stats = dict(eth_stats)
        oper_state = eth_stats['oper']
        pkts_in = eth_stats['rx_packets']
        pkts_out = eth_stats['tx_packets']
        print "{:>15} {:>12} {:>12} {:>12}".format(intf, oper_state, pkts_in, pkts_out)
    print 
Example #19
Source File: ex3_route_table.py    From pynet with Apache License 2.0 5 votes vote down vote up
def main():
    '''
    Connect to Juniper device using PyEZ. Display the routing table.
    '''
    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()

    routes = RouteTable(a_device)
    routes.get()

    print "\nJuniper SRX Routing Table: "
    for a_route, route_attr in routes.items():
        print "\n" + a_route
        for attr_desc, attr_value in route_attr:
            print "  {} {}".format(attr_desc, attr_value)

    print "\n" 
Example #20
Source File: ex2_jnpr_tables.py    From pyplus_course with Apache License 2.0 5 votes vote down vote up
def check_connected(device):
    print("\n\n")
    if device.connected:
        print(f"Device {device.hostname} is connected!")
    else:
        print(f"Device {device.hostname} failed to connect :(.")
        # If device is *not* connected; exit script
        sys.exit(1) 
Example #21
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 #22
Source File: example.py    From network-programmability-stream with MIT License 5 votes vote down vote up
def do_something(params):
    device_connection = Device(**params)
    device_connection.open()
    # device_connection.facts_refresh()
    facts = device_connection.facts

    # response_xml_element = device_connection.rpc.get_software_information(normalize=True)
    # print(etree.tostring(response_xml_element))
    # pprint(facts)


    print("{0} {1} {0}".format('=' * 37, facts['hostname']))

    routing_table = RouteTable(device_connection)
    routing_table.get()
    print("RIB:")
    for prefix in routing_table:
        print(f"Destination : {prefix.key}\n"
              f"Via: {prefix.via}\n"
              f"Nexthop: {prefix.nexthop}\n"
              f"Protocol: {prefix.protocol}\n\n")

    print("{}".format('=' * 80))

    arp_table = ArpTable(device_connection)
    arp_table.get()
    print("ARP table:")
    for entry in arp_table:
        print(f"IP : {entry.ip_address}\n"
              f"MAC: {entry.mac_address}\n"
              f"Interface: {entry.interface_name}\n\n")


    device_connection.close()
    # return facts 
Example #23
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 #24
Source File: junos_ping.py    From ansible-junos-extras with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            targets=dict(required=False, default=None),
            checktype=dict(required=False, default='pre'),
            user=dict(required=False, default=os.getenv('USER')),
            passwd=dict(required=False, default=None)),
        supports_check_mode=False)

    m_args = module.params
    m_results = dict(changed=False)
    dev = Device(m_args['host'], user=m_args['user'], passwd=m_args['passwd'])
    try:
        dev.open()
        results = {}
        ping_results = []
        if m_args['checktype'] == 'pre':
            try:
                arp = ArpTable(dev)
                arp.get()
                arp_json = json.loads(json.dumps(arp, cls=TableJSONEncoder))
                for entry in arp_json:
                    ping_results.append(dev.rpc.ping
                                        (host=arp_json[entry]['ip_address'],
                                         count='3', rapid=True))
                for entry in ping_results:
                    ip = entry.findtext('target-ip').replace('\n', '')
                    results[ip] = {}
                    if entry.findtext('ping-success') is not None:
                        results[ip]['success'] = True
                    else:
                        results[ip]['success'] = False
            except Exception as err:
                module.fail_json(msg=err)
        elif m_args['targets'] is not None:
            import ast
            m_args['targets'] = ast.literal_eval(m_args['targets'])
            for entry in m_args['targets']:
                if m_args['targets'][entry]['success'] == True:
                    ping_results.append(dev.rpc.ping
                                        (host=entry, count='3', rapid=True))
            for entry in ping_results:
                ip = entry.findtext('target-ip').replace('\n', '')
                results[ip] = {}
                if entry.findtext('ping-success') is not None:
                    results[ip]['success'] = True
                else:
                    results[ip]['success'] = False
        else:
            module.fail_json(msg='You specified a post-check \
                             but did not specify targets.')
    except Exception as err:
        msg = 'unable to connect to {}: {}'.format(m_args['host'], str(err))
        module.fail_json(msg=msg)
        return
    else:
        dev.close()
        module.exit_json(results=results) 
Example #25
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 #26
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()