Example #1
0
def main():

    juniper_srx = {
        "host": "184.105.247.76",
        "user": "******",
        "password": "******"
    }

    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 #2
0
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": '******', "password": pwd}

    print "\n\nConnecting to Juniper SRX...\n"
    # create device object with all the arguments in the dictionary
    a_device = Device(**juniper_srx)
    a_device.open()
    # get the ethernet port table
    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 #3
0
def getports(thedevice):
    """
    Retrieve ports list
    """
    ports = EthPortTable(thedevice)
    ports.get()
    return ports
Example #4
0
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": "******", "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 #5
0
    def _get_interfaces(self):
        eth_ifaces = EthPortTable(self.native)
        eth_ifaces.get()

        loop_ifaces = LoopbackTable(self.native)
        loop_ifaces.get()

        ifaces = eth_ifaces.keys()
        ifaces.extend(loop_ifaces.keys())

        return ifaces
Example #6
0
def main(args):
    '''Acquire necessary input options, interact with SRX device as specified per CLI args.'''
    parser = argparse.ArgumentParser(
        description='Interact with specified SRX device as specified')
    parser.add_argument('--version', action='version', version=__version__)
    parser.add_argument('-d', '--datafile', help='specify YAML file to read router info from',
                        default=SRX_FILE)
    parser.add_argument('--prompt', action='store_true',
                        help='prompt for router info (do not try to read in from file)',
                        default=False)
    parser.add_argument('-v', '--verbose', action='store_true', help='display verbose output',
                        default=False)
    args = parser.parse_args()
    # Debugging
    #if args.verbose:
    #    print 'Args = {}'.format(args)

    # Initialize data structures
    mysrx = {}
    if not args.prompt:
        mysrx = yaml_input(args.datafile, args.verbose)
        # Debugging
        #if args.verbose:
        #    print 'mysrx = {}'.format(mysrx)
    else:
        if args.verbose:
            print 'Prompting specified - asking user for all connection details'
    check_input(mysrx, args.verbose)

    mysrx_conn = Device(host=mysrx['HOST'], user=mysrx['USER'], password=mysrx['PASSWORD'])
    if args.verbose:
        print 'Opening NETCONF connection to {}...'.format(mysrx['HOST'])
    mysrx_conn.open()
    # Set timeout - default of 30 seconds can be problematic, must set after open()
    mysrx_conn.timeout = TIMEOUT

    ethports = EthPortTable(mysrx_conn)
    if args.verbose:
        print 'Gathering EthPortTable info from {}...'.format(mysrx['HOST'])
    ethports.get()

    print 'Device Ethernet Port information for {}:'.format(mysrx['HOST'])
    for int_key in ethports.keys():
        print '{}:'.format(int_key)
        for int_subkey in ethports[int_key].keys():
            if int_subkey == 'oper':
                print '  \\Operational Status:   {}'.format(ethports[int_key][int_subkey])
            elif int_subkey == 'rx_packets':
                print '  \\Received Packets:     {}'.format(ethports[int_key][int_subkey])
            elif int_subkey == 'tx_packets':
                print '  \\Transmitted Packets:  {}'.format(ethports[int_key][int_subkey])
    mysrx_conn.close()
Example #7
0
def main():
    password = getpass()
    device = Device(host = '184.105.247.76', user = '******', password = password)
    
    device.open()
    eth = EthPortTable(device)
    eth.get()
    
    for interface,v in eth.items():
        if interface == "fe-0/0/7":
            print "interface {}".format(interface)
            for field, value in v:
                if 'bytes' in field:
                    print "{} equals {}".format(field, value)
Example #8
0
def main():
    """Using Juniper's pyez for get interface operations."""
    password = getpass()
    a_device = Device(host='184.105.247.76', user='******', password=password)
    a_device.open()

    eth = EthPortTable(a_device)
    eth.get()
    print
    for intf, v in eth.items():
        if intf == 'fe-0/0/7':
            print 'intf {}: '.format(intf)
            for field_name, field_value in v:
                if 'bytes' in field_name:
                    print "    {:<15} {:<30}".format(field_name, field_value)
    print
Example #9
0
def main():
    '''
    Main function
    '''
    a_device = remote_conn(HOST, USER, PWD)
    if not a_device:
        sys.exit('Fix the above errors. Exiting...')

    ports = EthPortTable(a_device)
    ports.get()
    for port in ports.keys():
        print port
        port_items = dict(ports[port].items())
        print '   Oper: %s' % (port_items['oper'])
        print '   rx: %s' % (port_items['rx_packets'])
        print '   tx: %s' % (port_items['tx_packets'])
        print
def get_port_list(host, username, pwd, total_ports_open_lock,
                  device_dict_lock):
    count_up = 0
    connect_timeout = 10

    #global resources shared by all threads
    global total_ports_open
    global device_dict

    try:
        # Connect to devices in devices file using username and password provided above
        dev = Device(host=host.strip(),
                     user=username,
                     password=pwd,
                     port_no=22)
        dev.open(auto_probe=connect_timeout)
        dev.timeout = connect_timeout
        eths = EthPortTable(dev).get()

        # for every port on this device
        for port in eths:
            status = port.oper
            descrip = port.description

            # if the port is a wifi port don't add it
            if descrip not in ["WAPS"] and status in ["up"]:
                count_up += 1

#update our global variables safetly
        with total_ports_open_lock:
            total_ports_open += count_up

        with device_dict_lock:
            device_dict[host] = count_up

        dev.close()

    except ConnectAuthError:
        print "\nAuthentication error on: ", host
    except ConnectError as err:
        print("Cannot connect to device: ".format(err))
    except Exception, e:
        print "\nError ", e, "on host: ", host
Example #11
0
def add_vlan_and_port(dev):
    from jnpr.junos.op.ethport import EthPortTable
    ports_dict = {}
    eths = EthPortTable(dev).get()
    for port in eths:
        ports_dict[port.name] = port.description

    uplinks = [
        k for k, v in ports_dict.items() if v != None and v.startswith('TRUNK')
    ]
    config_vars = {
        'uplinks': uplinks,
        'client_port': [parser.parse_args().port[0]],
        'interfaces': uplinks + [parser.parse_args().port[0]],
        'vlan': parser.parse_args().vlan[0],
        'trunk_bool': parser.parse_args().tag
    }

    config_file = "templates/junos-config-add-vlans.conf"
    cu = Config(dev, mode='private')
    cu.load(template_path=config_file, template_vars=config_vars, replace=True)
    cu.pdiff()
    apply_config(dev, cu)
Example #12
0
def main():
    pwd = getpass()

    a_device = Device(host='184.105.247.76', user=USER, password=pwd)
    a_device.open()

    ports = EthPortTable(a_device)
    ports.get()

    print
    print "{:<20} {:<10} {:>20} {:>20}".format('interface', 'state',
                                               'RX packets', 'TX packets')
    for intfc, tuple_list in ports.items():
        for info, stat in tuple_list:
            if info == 'oper':
                oper = stat
            elif info == 'rx_packets':
                rx_packets = stat
            elif info == 'tx_packets':
                tx_packets = stat
        print "{:<20} {:<10} {:>20} {:>20}".format(intfc, oper, rx_packets,
                                                   tx_packets)

    print
Example #13
0
from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from getpass import getpass
from pprint import pprint
import ipdb

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

ipdb.set_trace()
ports = EthPortTable(a_device)
ports.get()

print(ports)
print(ports.keys())
pprint(ports.values())
pprint(ports.items())
Example #14
0
#!/usr/bin/python

import sys
from getpass import getpass
from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from pprint import pprint

devlist = ['192.168.2.254']
username = raw_input('username: '******'password: '******'connecting to %s ... ' % hostname)
    #  sys.stdout.flush()

    dev = Device(host=hostname, user=username, password=passwd)
    dev.open()

    ints = EthPortTable(dev).get()
    for int in ints:
        print("%s,%s" % (int.key, int.oper))

    dev.close()
Example #15
0
 def test_optable_view_get_astype_bool(self, mock_execute):
     mock_execute.side_effect = self._mock_manager
     et = EthPortTable(self.dev)
     et.get()
     v = et['ge-0/0/0']
     self.assertEqual(v['present'], True)
Example #16
0
# EthPortTable을 이용한 ethernet interface 상태 확인

from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from lxml import etree
from pprint import pprint

with Device(host='172.27.14.72', user='******', passwd='jun2per') as dev:
    eth = EthPortTable(dev)
    eth_get = eth.get()

    #print(eth.keys())
    #pprint(eth.values())
    pprint(eth.items())

    for item in eth:
        print("{} : {}".format(item.name, item.oper))
Example #17
0
def assert_interfaces_up(conn, interface):
    with Device(**conn) as dev:
        eths = EthPortTable(dev)
        eths.get(interface)
        for eth in eths:
            assert (eth.oper == 'up' and eth.admin == 'up')
Example #18
0
#!/usr/bin/python

from jnpr.junos import Device
from pprint import pprint
device1 = Device(host='10.1.2.3', user='******', password='******')
device1.open()
pprint(device1.facts)

from jnpr.junos.op.ethport import EthPortTable
ports = EthPortTable(device1)
ports = get()

for k, v in ports['fe-0/0/1'].items():
    print k, v
Example #19
0
device_ip = "192.168.229.185"
user_name = "test"
password = "******"

from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from time import sleep
from influxdb.influxdb08 import client

device = Device(host=device_ip, port=22, user=user_name, passwd=password)
device.open()
switch_name = device.facts['fqdn']
print 'Connected to', switch_name, '(', device.facts[
    'model'], 'running', device.facts['version'], ')'
ports_table = EthPortTable(device)

db = client.InfluxDBClient('localhost', 8086, 'root', 'root', 'network')
print 'Connected to InfluxDB'

print 'Collecting metrics...'
columns = ['rx_packets', 'rx_bytes', 'tx_packets', 'tx_bytes']
while True:
    ports = ports_table.get()
    for port in ports:
        point = {
            'name':
            switch_name + '.' + port['name'],
            'columns':
            columns,
            'points': [[
                int(port['rx_packets']),
Example #20
0
from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from getpass import getpass
from pprint import pprint

srx1 = Device(host="srx1.lasthop.io", user="******", password=getpass())
srx1.open()

ports = EthPortTable(srx1)
ports.get()

print(ports)
pprint(ports.keys())
#pprint(ports.values())
#pprint(ports.items())
Example #21
0
from jnpr.junos import Device
# Do not worry if your IDE flags the next import up.
# It will work.
from jnpr.junos.op.ethport import EthPortTable

with Device(host='10.4.4.41', user='******',
            password='******') as dev:
    eths = EthPortTable(dev)
    eths.get()
    for port in eths:
        print("{}: {}".format(port.name, port.oper))
Example #22
0
#### Getter operations
print "\nLLDP Get"
print '-' * 50
lldp = LLDPNeighborTable(a_device)
lldp.get()

for k, v in lldp.items():
    print k
    for entry in v:
        print entry

#### Getter operations
print "\nEth Port Get"
print '-' * 50
eth = EthPortTable(a_device)
eth.get()
pprint(eth.items())

#### Getter operations
print "\nRoute Table Get"
print '-' * 50
z_routes = RouteTable(a_device)
z_routes.get()
pprint(z_routes.items())

#### Config operations
print
print "Current static routes"
print '-' * 50
pprint(z_routes.keys())
Example #23
0
 def __get_ports(self):
     self.ports = EthPortTable(self.conn)
     self.ports.get()