Exemple #1
0
def main():
    parser = argparse.ArgumentParser(
        description='Add or remove vlan after checking for existence.')
    parser.add_argument(
        '--name',
        help=
        'supply a descriptive name for this vlan which should be different from the id'
    )
    parser.add_argument('vlanid',
                        help='VLAN number to create or remove',
                        action='store',
                        type=int)
    parser.add_argument(
        '--remove',
        help=
        'Use this command to remove the vlan from the switch. Only the vlan id is needed',
        action='store_true')
    args = parser.parse_args()

    vlanid = args.vlanid
    remove = args.remove
    name = args.name

    #verify existence of vlan in switch
    vlan_exists = check_vlan(vlanid)
    '''Actions are below. If the action is to remove a vlan, the switch is checked to see if it is configured.
    if not, the vlan is removed.
    '''
    if remove:
        if vlan_exists:
            cmd = 'no vlan {}'.format(vlanid)
            pynet_sw2 = pyeapi.connect_to('pynet-sw2')
            pynet_sw2.config(cmd)
            print 'VLAN {} removed'.format(vlanid)
        else:
            print 'Nothing to do here! VLAN {} does not exist on switch'.format(
                vlanid)
    #if action is not to remove but add a vlan, first check to see if it exists
    else:
        if vlan_exists:
            if name is not None and vlan_exists != name:
                cmd = []
                cmd1 = cmd.append('vlan {}'.format(vlanid))
                cmd2 = cmd.append('name {}'.format(name))
                pynet_sw2 = pyeapi.connect_to('pynet-sw2')
                pynet_sw2.config(cmd)
                print 'Vlan found on switch but without a name. Name added to vlan.'
            else:
                print 'Vlan found on switch with name. Nothing to do here'
        else:
            cmd = []
            cmd1 = cmd.append('vlan {}'.format(vlanid))
            cmd2 = cmd.append('name {}'.format(name))
            pynet_sw2 = pyeapi.connect_to('pynet-sw2')
            pynet_sw2.config(cmd)
            print 'Vlan NOT found on switch Adding Vlan.'
Exemple #2
0
def main():
    parser = argparse.ArgumentParser(description='Add or remove vlan after checking for existence.')
    parser.add_argument('--name', help='supply a descriptive name for this vlan which should be different from the id')
    parser.add_argument('vlanid', help='VLAN number to create or remove', action='store', type=int)
    parser.add_argument(
        '--remove',
        help='Use this command to remove the vlan from the switch. Only the vlan id is needed',
        action='store_true'
    )
    args=parser.parse_args()


    vlanid = args.vlanid
    remove = args.remove
    name = args.name

    #verify existence of vlan in switch
    vlan_exists=check_vlan(vlanid)

    '''Actions are below. If the action is to remove a vlan, the switch is checked to see if it is configured.
    if not, the vlan is removed.
    '''
    if remove:
       if vlan_exists:
           cmd='no vlan {}'.format(vlanid)
           pynet_sw2 = pyeapi.connect_to('pynet-sw2')
           pynet_sw2.config(cmd)
           print 'VLAN {} removed'.format(vlanid)
       else:
           print 'Nothing to do here! VLAN {} does not exist on switch'.format(vlanid)
    #if action is not to remove but add a vlan, first check to see if it exists
    else:
        if vlan_exists:
            if name is not None and vlan_exists != name:
                cmd=[]
                cmd1 = cmd.append('vlan {}'.format(vlanid))
                cmd2 = cmd.append('name {}'.format(name))
                pynet_sw2 = pyeapi.connect_to('pynet-sw2')
                pynet_sw2.config(cmd)
                print 'Vlan found on switch but without a name. Name added to vlan.'
            else:
                print 'Vlan found on switch with name. Nothing to do here'
        else:
            cmd = []
            cmd1 = cmd.append('vlan {}'.format(vlanid))
            cmd2 = cmd.append('name {}'.format(name))
            pynet_sw2 = pyeapi.connect_to('pynet-sw2')
            pynet_sw2.config(cmd)
            print 'Vlan NOT found on switch Adding Vlan.'
def main():

    # connect back to my switch
    connect = pyeapi.connect_to("pynet-sw4")

    # argparse stuff
    parser = argparse.ArgumentParser(
        "Adding and Removing of a VLAN to Arista swiches uing pyeapi")
    parser.add_argument("vlan_id",
                        help="VLAN number to create or remove",
                        action="store",
                        type=int)
    parser.add_argument("--name",
                        help="Specify VLAN name",
                        action="store",
                        dest="vlan_name",
                        type=str)
    parser.add_argument("--remove",
                        help="Remove the given VLAN ID",
                        action="store_true",
                        dest="remove_vlan")

    args = parser.parse_args()

    # pprint(vlan_CHECK(args.vlan_id))
    # vlan_CHECK(connect, args.vlan_id)

    if args.remove_vlan:
        vlan_REMOVE(args.vlan_id, connect)
    else:
        if vlan_CHECK(args.vlan_id, connect):
            vlan_ADD(args.vlan_id, args.vlan_name, connect)
        else:
            print "VLAN Already Present, no action"
Exemple #4
0
def check_vlan_exist(vlan_id):
    pynet_sw1 = pyeapi.connect_to("pynet-sw1")
    output = pynet_sw1.enable("show vlan brief")
    if vlan_id in output[0]['result']['vlans'].keys():
        return True

    return False
Exemple #5
0
 def __init__(self, config_file_location, device):
     # loads the config file
     pyeapi.client.load_config(config_file_location)
     self.node = pyeapi.connect_to(device)
     self.hostname = self.node.enable(
         'show hostname')[0]['result']['hostname']
     self.running_config = self.node.enable('show running-config')
Exemple #6
0
def main():
    """

  Execute 'show interfaces' on the Arista Switch using eapi.

  Extract the interfaceCounters inOctets/outOctetc for all the interfaces
  that have this information.

  """

    pynet_sw = pyeapi.connect_to("pynet-sw1")
    show_int = pynet_sw.enable("show interfaces")
    show_int = show_int[0]['result']['interfaces']
    print "\n{:>15} {:>15} {:>15}".format("Interface", "inOctets", "outOctets")
    sep = "-" * 15
    print "\n{:>15} {:>15} {:>15}".format(sep, sep, sep)
    for intf, v in show_int.items():
        intf_counters = v.get('interfaceCounters', 'N/A')
        if intf_counters != 'N/A':
            in_octets = intf_counters.get('inOctets')
            out_octets = intf_counters.get('outOctets')
        else:
            in_octets = 0
            out_octets = 0
        print "\n{:>15} {:>15} {:>15}".format(intf, in_octets, out_octets)
    print
Exemple #7
0
def main():
    '''
    Simple Ansible module to create an Arista VLAN
    '''
    module = AnsibleModule(argument_spec=dict(
        arista_sw=dict(required=True),
        vlan_id=dict(required=True),
        vlan_name=dict(required=False),
    ))

    vlan_id = module.params['vlan_id']
    vlan_name = module.params.get('vlan_name')
    arista_sw = module.params.get('arista_sw')
    print arista_sw

    eapi_conn = pyeapi.connect_to(arista_sw)

    # Check if VLAN already exists
    check_vlan = check_vlan_exists(eapi_conn, vlan_id)

    if check_vlan:
        if vlan_name is not None and check_vlan != vlan_name:
            configure_vlan(eapi_conn, vlan_id, vlan_name)
            module.exit_json(msg="VLAN already exists, setting VLAN name",
                             changed=True)
        else:
            module.exit_json(msg="VLAN already exists, no action required",
                             changed=False)

    else:
        configure_vlan(eapi_conn, vlan_id, vlan_name)
        module.exit_json(msg="Adding VLAN including vlan_name (if present)",
                         changed=True)
Exemple #8
0
def main():
    '''
    grab "show interface" from switch side
    '''

    conn1 = pyeapi.connect_to("pynet-sw1")

    interfaces = conn1.enable("show interfaces")
    interfaces = interfaces[0]['result']

    interfaces = interfaces['interfaces']


    data = {}
    for interface, meta in interfaces.items():
        interfaceCounters = meta.get('interfaceCounters', {})
        data[interface] = (interfaceCounters.get('inOctets'), interfaceCounters.get('outOctets'))


    '''
    print out formatted data, I don't know how to print it beautifully, so I referred the solution of teacher
    '''
    print "\n{:20} {:<20} {:<20}".format("Interface:", "inOctets", "outOctets")
    for intf, octets in data.items():
        print "{:20} {:<20} {:<20}".format(intf, octets[0], octets[1])
Exemple #9
0
def main():

    # Use pyeapi to login to the switch.
    pynet_sw2 = pyeapi.connect_to("pynet-sw2")

    # Use pyeapi to issue the 'show interfsces' command.
    interfaces = pynet_sw2.enable("show interfaces")

    # The output is in a dictionary called 'result'.
    interfaces = interfaces[0]['result']

    # Get the dictionary called 'interfaces' from the result.
    interfaces = interfaces['interfaces']
    #pprint(interfaces)

    # InOctets and OutOctets are in another dictionary 'interfaceCounters'.
    data_stats = {}  # Empty dictionary.
    for interface, int_value in interfaces.items():
        int_counter = int_value.get('interfaceCounters', {})
        data_stats[interface] = (int_counter.get('inOctets'),
                                 int_counter.get('outOctets'))

    # Print output data
    print "\n{:20} {:<20} {:<20}".format("Interface:", "inOctets", "outOctets")
    for intf, octets in data_stats.items():
        print "{:20} {:<20} {:<20}".format(intf, octets[0], octets[1])

    print
Exemple #10
0
def main():
    '''
    Main Loop
    '''
    parser = argparse.ArgumentParser(description='Test of argparse')
    parser.add_argument('--add', action="store", dest="add", help="Add a Vlan with color ex: --add 100")
    parser.add_argument('--color', action="store", dest="color", help="Sepecify a VLAN description, ex: --color BLUE")
    parser.add_argument('--rem', action="store", dest="rem", help="Remove a VLAN, ex: --rem 100")
    parser.add_argument('--version', action='version', version='%(prog)s 0.01')
    parseresults = parser.parse_args()
    if parseresults.add and parseresults.rem:
        sys.exit('You should not specify --add and --rem at the same time')
    if parseresults.add and not parseresults.color:
        sys.exit('When using --add, you also need to specify the --color argument')

    try:
        sw_conn = pyeapi.connect_to(SWITCH)
    except AttributeError:
        sys.exit('Unable to connect to the remote switch')
    commands = []
    if parseresults.add:
        if not check_vlan_exist(sw_conn, parseresults.add):
            commands = ['vlan '+parseresults.add, 'name '+parseresults.color]
        else:
            print 'Vlan %s is already configured on %s' % (parseresults.add, SWITCH)
    if parseresults.rem:
        if check_vlan_exist(sw_conn, parseresults.rem):
            commands = ['no vlan '+parseresults.rem]
        else:
            print 'Vlan %s not found on %s' % (parseresults.rem, SWITCH)
    sw_conn.config(commands)
Exemple #11
0
def main():
    '''
    Use Arista's eAPI to obtain 'show vlans' from the switch.
    '''
    pynet_sw2 = pyeapi.connect_to("pynet-sw2")
    vlans = pynet_sw2.enable("show vlan")
    vlans = pyeapi_result(vlans)
    parser = argparse.ArgumentParser(' Valn Manipulation')
    parser.add_argument('--name', '--list', nargs='+', action='store', dest='list',
                        help='Add a Vlan')
    parser.add_argument('--remove', action='store', dest='remove',
                        help='Remove a Vlan')
    results = parser.parse_args()

    if results.list != None:
        cmds = ['vlan ' + results.list[1], 'name ' + results.list[0]]
        if  not search_vlan(vlans, results.list[1]):
            pynet_sw2.config(cmds)
            print " vlan {}, name {} was added successfully ".\
format(results.list[1], results.list[0])
        else:
            print " vlan {} already exist ".format(results.list[1])
    if results.remove != None:
        cmds = ['no vlan ' + results.remove]
        if search_vlan(vlans, results.remove):
            pynet_sw2.config(cmds)
            print " vlan {} was removed successfully ".format(results.remove)
        else:
            print " vlan {} is abscent from the Vlan Data base ".format(results.remove)
def main():
    module = AnsibleModule(
        argument_spec = dict(
            arista_sw=dict(required=True),
            vlan_id=dict(required=True),
            vlan_name=dict(required=False),
        ),
        supports_check_mode=True
    )

    vlan_id = module.params['vlan_id']
    vlan_name = module.params.get('vlan_name')
    arista_sw = module.params.get('arista_sw')

    eapi_conn = pyeapi.connect_to(arista_sw)
    check_vlan = check_vlan_exists(eapi_conn, vlan_id)

    if module.check_mode:
        # Check if any changes would be made but don't actually make those changes
        module.exit_json(changed=
                         check_if_system_state_would_be_changed(check_vlan, vlan_name))

    if check_vlan:
        # VLAN name needs to be set 
        if vlan_name is not None and vlan_name != check_vlan:
            configure_vlan(eapi_conn, vlan_id, vlan_name)
            module.exit_json(msg="VLAN already exists, VLAN name set.", changed=True)
        else:
            module.exit_json(msg="VLAN already exists, no action.", changed=False)

    else:   # Vlan does not exist 
        configure_vlan(eapi_conn, vlan_id, vlan_name)
        module.exit_json(msg="Add VLAN including vlan_name (if present)", changed=True)
Exemple #13
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--name", type=str, default="")
    parser.add_argument("vlan", type=str)
    parser.add_argument("--remove", action="store_true", default=False)
    args = parser.parse_args()
    print("Checking for VLAN...")

    #print(args.name)
    #print(args.vlan)
    #print(args.remove)

    vlan_id = args.vlan
    vlan_name = args.name
    pynet_sw2 = pyeapi.connect_to('pynet-sw2')
    config = get_config(pynet_sw2)

    vlan_status = check_vlan(config,vlan_id)
    if args.remove == False:
        if vlan_status == False:
            print("VLAN does not exist...")
            create_vlan(pynet_sw2,vlan_id,vlan_name)
            print("\nVLAN has been created.")
        else:
            print("This VLAN is currently in use.")

    else:
        if vlan_status == False:
            print("No VLAN to remove.")
        else:
            remove_vlan(pynet_sw2,vlan_id,vlan_name)
            print("\nVLAN has been removed.")            
def main():
    '''
    Ansible module to manipulate an Arista VLAN
    '''

    module = AnsibleModule(
        argument_spec=dict(
            switch=dict(required=True),
            vlanid=dict(required=True),
            name=dict(required=False),
        )
    )

    vlan_id = module.params.get('vlanid')
    vlan_name = module.params.get('name')
    switch = module.params.get('switch')
    eapi_conn = pyeapi.connect_to(switch)
    vlans = eapi_conn.enable("show vlan")
    vlans = vlans[0]
    vlans = vlans['result']
    vlans = vlans['vlans']
    if  vlan_manipulation(vlans, vlan_id, vlan_name) != 0:
        configure(eapi_conn, vlan_id, vlan_name)
        if vlan_manipulation(vlans, vlan_id, vlan_name) == 1:
            module.exit_json(msg="VLAN already exists, setting VLAN name", changed=True)
        if vlan_manipulation(vlans, vlan_id, vlan_name) == 2:
            module.exit_json(msg="Adding VLAN including vlan_name (if present)", changed=True)
    else:
        module.exit_json(msg="VLAN already exists, no action required", changed=False)
Exemple #15
0
def executecommands(commandlist):
    """
    Execute comman list parsed in.
    """
    arista_connection = pyeapi.connect_to("pynet-sw2")
    result = arista_connection.config(commandlist)
    print "Result of commmand execution: %r" % result
Exemple #16
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("vlan_id", help="vlan_id ",type=int)

    parser.add_argument("--remove", help="option to remove the vlan",action="store_true")

    args = parser.parse_args()
    vlan_id=args.vlan_id
    remove=args.remove
    data={}
    pynet_sw1=pyeapi.connect_to('pynet-sw1')
    show_vlan_data=pynet_sw1.enable('show vlan')
    result=check_vlan(show_vlan_data,vlan_id)
    
    if remove:
        if result:
            print 'VLAN exists, we will remove it \n'
            command_str = 'no vlan {}'.format(vlan_id)
            pynet_sw1.config([command_str])

        else:
            print 'VLAN doesn\'t exist, thus there is no point to remove it'

    else:
        if result:
             print 'VLAN exists, we will not create it'
        else:
             print 'Adding VLAN'
             command_str = 'vlan {}'.format(vlan_id)
             pynet_sw1.config([command_str])
Exemple #17
0
def main():
    """
    Use eapi to retrieve 'show ip route' from your arista switch.
    From the returned data structure retrieve the prefixes, the output
    interfaces, and the next hops (if available).

    Print these routes and the associated information to stdout.
    """
    pynet_sw = pyeapi.connect_to("pynet-sw4")
    output = pynet_sw.enable("show ip route")

    # Strip off unneeded information
    output = output[0]
    output = output['result']['vrfs']['default']

    # Get the routes
    routes = output['routes']
    print("\n{:>15} {:>15} {:>15}".format("prefix", "interface", "next_hop"))
    filler = "-" * 15
    print("{:>15} {:>15} {:>15}".format(filler, filler, filler))
    for prefix, attr in routes.items():
        intf_nexthop = attr['vias'][0]
        interface = intf_nexthop.get('interface', 'N/A')
        next_hop = intf_nexthop.get('nexthopAddr', 'N/A')
        print("{:>15} {:>15} {:>15}".format(prefix, interface, next_hop))
    print()
def executecommands(commandlist):
    """
    Execute comman list parsed in.
    """
    arista_connection = pyeapi.connect_to("pynet-sw2")
    result = arista_connection.config(commandlist)
    print "Result of commmand execution: %r" % result
Exemple #19
0
def main(args=None):
    """Main execution routine for eapish command

    Parse the command line options, create a pyeapi connection to each host,
    send the commands, print the output from each host.
    """

    args = cmd_line_parser(args)

    # Build the command
    cmds = ' '.join(args.cmd)

    # Set the response encoding
    encoding = 'text' if args.text else 'json'

    # Parse the list of hosts
    hosts = args.hosts.split(',')

    # For each host send the commands and store in the responses dict:
    for host in hosts:
        print '\nHost: %s' % host

        # Create connection to host
        node = pyeapi.connect_to(host)

        if node is None:
            print 'Error: "%s" connection profile not found' % host
            return 2

        for cmd in cmds.split(','):
            # Run command and print output
            run_cmd(node, args.config, cmd, encoding)

    return 0
Exemple #20
0
def main():
    parser = argparse.ArgumentParser("ex2.py")
    parser.add_argument('--check', action="store_true", dest="check_only", default=False, help='Do not make changes, check only')
    parser.add_argument('--remove', action="store_true", dest="remove_vlan", default=False, help='Delete the VLAN')
    parser.add_argument('--name', action="store", dest="vlan_name", help='VLAN name')
    parser.add_argument('device', action="store", help='device hostname as found in ~/.eapi.conf, see https://eos.arista.com/introducing-the-python-client-for-eapi-pyeapi/')
    parser.add_argument('vlan_id', type=valid_id, action="store", help='The VLAN ID to work with')
    args = parser.parse_args()
    try:
        args.vlan_id
    except NameError:
        args.vlan_id = 100
    try:
        args.vlan_name
    except NameError:
        args.vlan_name = 'VLAN' + str(vlan_id)
    device = pyeapi.connect_to(args.device)
    if not args.remove_vlan or args.check_only:
        if check_vlan(args.vlan_id, args.vlan_name, device):
            pass #VLAN Check is ok, go ahead and add it
            add_vlan(args.vlan_id, args.vlan_name, device)
        else:
            print "ERR: 123, this should never happen"
    else:
        remove_vlan(args.vlan_id, device)
Exemple #21
0
def main():
    # Arista switch definition
    pynet_sw3 = pyeapi.connect_to('pynet-sw3')
    print pynet_sw3, '\n'

    parser = argparse.ArgumentParser(
        description='Add or remove Vlan depending on the option used')
    parser.add_argument('--name',
                        help='Configure new Vlan',
                        action='store',
                        dest='vlan_name',
                        type=str)
    parser.add_argument('--remove',
                        help='Remove the given Vlan ID',
                        action='store_true')
    parser.add_argument('vlan_id',
                        help='Specify Vlanid i.e. Vlan number',
                        action='store',
                        type=int)

    cli_args = parser.parse_args()
    vlan_id = cli_args.vlan_id
    vlan_name = cli_args.vlan_name
    remove = cli_args.remove

    show_current_vlan_config(pynet_sw3)
    vlan_config_change(pynet_sw3, vlan_id, vlan_name)
def main():
    """
    Use eapi to retrieve 'show ip route' from your arista switch.
    From the returned data structure retrieve the prefixes, the output interfaces, and the next hops
    (if available).
    Print these routes and associated information to standard out.
    """
    pynet_sw1 = pyeapi.connect_to("pynet-sw1")
    output = pynet_sw1.enable("show ip route")

    # Strip off unneeded information
    output = output[0]
    output = output['result']['vrfs']['default']

    # Get the routes
    routes = output['routes']
    print "\n{:>15} {:>15} {:>15}".format("prefix", "interface", "next_hop")
    filler = "-" * 15
    print "{:>15} {:>15} {:>15}".format(filler, filler, filler)
    for prefix, attr in routes.items():
        intf_nexthop = attr['vias'][0]
        interface = intf_nexthop.get('interface', 'N/A')
        next_hop = intf_nexthop.get('nexthopAddr', 'N/A')
        print "{:>15} {:>15} {:>15}".format(prefix, interface, next_hop)
    print
Exemple #23
0
def main():

    arista_sw = pyeapi.connect_to("pynet-sw2")
    output = arista_sw.enable("show ip route")
    #pprint (output)

    #Output comes as a list with only one item in it. Stripping the list off to have only the dictionary:
    output = output[0]
    #pprint (output)
    #print "\n" *5

    #The dictionary comes with outer useless layers, stripping those off too:
    output = output["result"]["vrfs"]["default"]
    #pprint (output)
    #print "\n" *5

    #Getting the routes:
    routes = output["routes"]
    pprint(routes)
    print "\n" * 5
    print "{:>15} {:>15} {:>15}".format("prefix", "interface", "next_hop")

    for k, v in routes.items():
        int_nexthop = v["vias"][0]
        pprint(int_nexthop)
Exemple #24
0
def main():

   # create the node instance
   node = pyeapi.connect_to('pynet-sw1')

   # go out and grab the "show interfaces" output
   show_int = node.enable('show interfaces')

   # Output from above returns a list; striping off list
   # leaving me a dictionary
   show_int = show_int[0]

   # I just want the output of the result key from the
   # dictionary above
   interfaces = show_int['result']

   interfaces = interfaces['interfaces']

   print "\n{:20} {:<20} {:<20}".format("Interface", "In Octets", "Out Octets")

   for i in interfaces.keys():
      list_of_interfaces = interfaces.get(i)
      int_c = list_of_interfaces.get('interfaceCounters', {})
      inOct = int_c.get('inOctets')
      ouOct = int_c.get('outOctets')
      print "{:20} {:<20} {:<20}".format(i, inOct, ouOct)
def main():
    '''
    Simple Ansible module to create an Arista VLAN
    '''
    module = AnsibleModule(
        argument_spec=dict(
            arista_sw=dict(required=True),
            vlan_id=dict(required=True),
            vlan_name=dict(required=False),
        )
    )

    vlan_id = module.params['vlan_id']
    vlan_name = module.params.get('vlan_name')
    arista_sw = module.params.get('arista_sw')
    print arista_sw

    eapi_conn = pyeapi.connect_to(arista_sw)

    # Check if VLAN already exists
    check_vlan = check_vlan_exists(eapi_conn, vlan_id)

    if check_vlan:
        if vlan_name is not None and check_vlan != vlan_name:
            configure_vlan(eapi_conn, vlan_id, vlan_name)
            module.exit_json(msg="VLAN already exists, setting VLAN name", changed=True)
        else:
            module.exit_json(msg="VLAN already exists, no action required", changed=False)

    else:
        configure_vlan(eapi_conn, vlan_id, vlan_name)
        module.exit_json(msg="Adding VLAN including vlan_name (if present)", changed=True)
Exemple #26
0
def main():
    '''
    Use Arista's eAPI to obtain 'show interfaces' from the switch.
    '''
    eapi_conn = pyeapi.connect_to("pynet-sw3")

    interfaces = eapi_conn.enable("show interfaces")

    # Strip off outer list
    interfaces = interfaces[0]
    # Only use result dictionary
    interfaces = interfaces["result"]
    # Go one more step down to the interfaces
    interfaces = interfaces['interfaces']

    # From Kirk's code
    data_stats = {}
    # inOctets/outOctets are fields inside 'interfaceCounters' dict
    for interface, int_values in interfaces.items():
        int_counters = int_values.get('interfaceCounters', {})
        data_stats[interface] = (int_counters.get('inOctets'), int_counters.get('outOctets'))

    # Print output data
    print "\n{:20} {:<20} {:<20}".format("Interface:", "inOctets", "outOctets")
    for intf, octets in data_stats.items():
        print "{:20} {:<20} {:<20}".format(intf, octets[0], octets[1])
def Connect():
    """Connects to the Arista router.
  
  Returns: pyeapi.Node, the connected router.
  """
    pyeapi.load_config('eapi.conf')
    return pyeapi.connect_to('arista')
def main():
    """Use Arista's eAPI to obtain 'show interfaces' from the switch."""
    eapi_conn = pyeapi.connect_to("pynet-sw2")

    interfaces = eapi_conn.enable("show interfaces")
    interfaces = pyeapi_result(interfaces)

    # Strip off unneeded dictionary
    interfaces = interfaces['interfaces']

    # inOctets/outOctets are fields inside 'interfaceCounters' dict
    data_stats = {}
    for interface, int_values in interfaces.items():
        int_counters = int_values.get('interfaceCounters', {})
        data_stats[interface] = (int_counters.get('inOctets'),
                                 int_counters.get('outOctets'))

    # Print output data
    print("\n{:20} {:<20} {:<20}".format("Interface:", "inOctets",
                                         "outOctets"))
    for intf, octets in sorted(data_stats.items()):
        print("{:20} {:<20} {:<20}".format(intf, six.text_type(octets[0]),
                                           six.text_type(octets[1])))

    print()
Exemple #29
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("vlan_id", help="vlan_id ",type=int)
    parser.add_argument("--name", help="vlan_name_option",type = str)
    parser.add_argument("--remove", help="option to remove the vlan",action="store_true")
    
    args = parser.parse_args()
    vlan_id=args.vlan_id
    remove=args.remove
    vlan_name=args.name
    print vlan_name
    data={}
    pynet_sw1=pyeapi.connect_to('pynet-sw1')
    show_vlan_data=pynet_sw1.enable('show vlan')
    my_list=check_vlan(show_vlan_data,vlan_id)
    if my_list:
        result=True
        vlan_name_current=my_list[1]
    else:
        result=False    
        vlan_name_current=None  
    


    if remove:
        if result:
            print 'VLAN exists, we will remove it \n'
            command_str = 'no vlan {}'.format(vlan_id)
            pynet_sw1.config(command_str)

        else:
            print 'VLAN doesnt exist, thus there is no point to remove it'

    else:
        if result:
             if str(vlan_name) != str(vlan_name_current):
                    print type(vlan_name),type(vlan_name_current)
                    print 'VLAN exists Adding VLAN name'
                    command_str1 = 'vlan {}'.format(vlan_id)
                    cmd=[command_str1]
                    command_str2 = 'name {}'.format(vlan_name)
                    cmd.append(command_str2)
                    print cmd
                    pynet_sw1.config(cmd)
             else:
                    print ' VLAN with same ID and name exists'
        else:
             
             if vlan_name != None:
                    print 'VLAN doesnt exist pushing VLAN ID and name'
                    command_str1 = 'vlan {}'.format(vlan_id)
                    cmd=[command_str1]
                    command_str2 = 'name {}'.format(vlan_name)
                    cmd.append(command_str2)
                    pynet_sw1.config(cmd)
             else: 
                    print 'No VLAN name is passed, pushign VLAN ID'
                    command_str = 'vlan {}'.format(vlan_id)
                    pynet_sw1.config([command_str])
Exemple #30
0
    def eos_connect(self):
        """
        This function creates a connection to the Arista switch.
        This will be used for other requests for AAA functions.

        :return: Returns an open connection to the switch.
        """
        return pyeapi.connect_to(self.host)
def vlan_delete(vlan_delete):
  connection = pyeapi.connect_to("pynet-sw3")
  vlans_api = connection.api("vlans")
  if vlans_api.get(vlan_delete):
    vlans_api.delete(vlan_delete)
    print("Deleting VLAN {}".format(vlan_delete))
  else:
    print("VLAN {} does not exist".format(vlan_delete))
Exemple #32
0
def show_current_vlan_config():
    '''The below section refers to a list, so no .keys, .values, .items methods apply'''
    pynet_sw3 = pyeapi.connect_to('pynet-sw3')
    global show_vlan
    show_vlan = pynet_sw3.enable('show vlan')
    show_vlan = show_vlan[0]['result']['vlans']
    pprint(show_vlan)
    print '\n'
def main():
    conn1 = pyeapi.connect_to("pynet-sw1")

    parser = argparse.ArgumentParser(description="Add/Delete VLAN")
    parser.add_argument(
            "--vlan_id",
            help="VLAN number",
            action="store",
            dest="vlan_id",
            type=int
    )
    parser.add_argument(
            "--name",
            help="VLAN name",
            action="store",
            dest="vlan_name",
            type=str
    )
    parser.add_argument(
            "--add",
            help="add the given VLAN",
            action="store_true",
            dest="to_add"
    )
    parser.add_argument(
            "--delete",
            help="delete the given VLAN",
            action="store_true",
            dest="to_delete"
    )

    meta_args = parser.parse_args()
    vlan_id = meta_args.vlan_id
    vlan_name = meta_args.vlan_name
    to_add = meta_args.to_add
    to_delete = meta_args.to_delete

    vlan_existence = vlan_existence_checker(conn1, vlan_id)

    if to_delete:
        print vlan_existence
        if vlan_existence:
            print "Removing this VLAN"
            vlan_command = 'no vlan {}'.format(vlan_id)
            conn1.config(vlan_command)
        else:
            print "Action aborted because there's no such a VLAN"
    if to_add:
        if vlan_existence:
            if vlan_name != None and vlan_existence != vlan_name:
                print "Setting new name for an existed VLAN"
                config_vlan(conn1, vlan_id, vlan_name)
            else:
                print "VLAN exists, no action's required"
        else:
            print "Adding a new VLAN"
            config_vlan(conn1, vlan_id, vlan_name)
Exemple #34
0
 def __init__(self, module, switch1):
     '''Initialize class instance.'''
     self.module = module
     self.state = module.params['state']
     self.vlan = module.params['vlan']
     self.name = module.params['name']
     #self.conn = None
     '''Establish connection to switch.'''
     self.conn = pyeapi.connect_to(switch1)
Exemple #35
0
def check_vlan(vlan):
    eapi_conn = pyeapi.connect_to("pynet-sw3")
    result = eapi_conn.enable("show vlan")
    vlan_list = result[0]['result']['vlans']

    if vlan in vlan_list:
        return True

    return False
Exemple #36
0
def check_vlan(vlan):
    eapi_conn = pyeapi.connect_to("pynet-sw3")
    result = eapi_conn.enable("show vlan")
    vlan_list = result[0]['result']['vlans']

    if vlan in vlan_list:
        return True

    return False
Exemple #37
0
def main():
    conn = pyeapi.connect_to('pynet-sw3')
    out = conn.run_commands("show interfaces")
    for i in out[0]['interfaces']:
        if out[0]['interfaces'][i].has_key('interfaceCounters'):
            print "Interface: " + i + "\n\tinOctets: " + str(out[0]['interfaces'][i]['interfaceCounters']['inOctets'])
            print "\toutOctets: " + str(out[0]['interfaces'][i]['interfaceCounters']['outOctets'])
        else:
            continue
Exemple #38
0
def main():

    opcodes = [
        '--name',
        '--remove'
    ]

    opcode=sys.argv.pop(1)
    if not opcode in opcodes:
        print "INVALID OPERATION: USE --name or --remove"

    if opcode == '--name':
        vlan_num=sys.argv.pop(1)
        vlan_name=sys.argv.pop(1)
    elif opcode == '--remove':
        vlan_num = sys.argv.pop(1)
        vlan_name = None
    vlan_string = "vlan %s" %vlan_num
    name_string = "name %s" %vlan_name


    ssl._create_default_https_context = ssl._create_unverified_context

    remote_connect=pyeapi.connect_to("pynet-sw4")
    response=remote_connect.enable("show running-config")
    config=response[0]['result']['cmds']
    if vlan_string in config.keys():
        is_configured = True
        vlan_config = config[vlan_string]
    else:
        is_configured = False

    if opcode == '--name':
        if is_configured:
            print "vlan %s IS CONFIGURED" %vlan_num
            print "  NAME IS %s" %name_string
            if not name_string in vlan_config.keys():
                print "    BUT NAME IS INCORRECT"
                print "RECONFIGURE VLAN NAME"
                commands = [vlan_string,name_string]
                print "COMMANDS=%s" %commands
                remote_connect.config(commands)
        else:
            print "vlan %s IS NOT CONFIGURED" %vlan_num
            commands = [vlan_string,name_string]
            print "COMMANDS=%s" %commands
            remote_connect.config(commands)
            print "vlan %s CONFIGURED" %vlan_num

    elif opcode=='--remove':
        if is_configured:
             commands = ['no %s' %vlan_string]
             remote_connect.config(commands)
             print "vlan %s REMOVED" %vlan_num
        else:
            print "vlan %s IS NOT CONFIGURED" %vlan_num
Exemple #39
0
    def __init__(self, module, switch1):
        '''Initialize class instance.'''
        self.module = module
        self.state = module.params['state']
        self.vlan = module.params['vlan']
        self.name = module.params['name']
        #self.conn = None

        '''Establish connection to switch.'''
        self.conn = pyeapi.connect_to(switch1)
Exemple #40
0
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument(
        "-s",
        "--switch",
        required=True,
        help="Switch Hostname as input into .eapi.conf in the root directory")
    ap.add_argument("-n", "--name", required=True, help="Name of the ACL")
    ap.add_argument("-i",
                    "--ipsrc",
                    required=True,
                    help="First IP address in the ACL")
    ap.add_argument("-m", "--mask", required=True, help="Subnet mask")
    ap.add_argument("-r",
                    "--rules",
                    required=True,
                    help="Number of rules to add")
    ap.add_argument("-a",
                    "--action",
                    required=True,
                    help="Rule action = 'permit' or 'deny'")
    ap.add_argument("-d",
                    "--ipdst",
                    required=False,
                    help="Destination IP, default = 0.0.0.0")
    ap.add_argument("-M",
                    "--dmask",
                    required=False,
                    help="Destination Mask, default = 0")
    args = vars(ap.parse_args())

    hostname = (args['switch'])
    acl_name = (args['name'])
    first_src = (args['ipsrc'])
    src_netmask = int(args['mask'])
    max_rules = int(args['rules'])
    rule_action = (args['action'])

    try:
        dst_ip = (args['ipdst'])
        dst_mask = int(args['dmask'])
    except:
        dst_ip = '0.0.0.0'
        dst_mask = 0

    try:
        node = pyeapi.connect_to(
            hostname)  #needs the .eapi.conf file in the /home/ directory
        connect_to_switch(node)
        acl_loop(acl_name, first_src, src_netmask, max_rules, rule_action,
                 dst_ip, dst_mask, node)
    except:
        print("Execution Failed:")
        print("check the .eapi.conf file for the correct hostname")
def main():
    connection = pyeapi.connect_to("pynet-sw3")
    existing_vlans = connection.api("vlans")
    my_vlans = range(100, 999, 50)
    for curr_vlan in my_vlans:
        if existing_vlans.get(curr_vlan):
            print("VLAN {} already exists".format(curr_vlan))
        else:
            existing_vlans.create(curr_vlan)
            name = "TEST_VLAN_" + str(curr_vlan)
            existing_vlans.set_name(str(curr_vlan), name)
Exemple #42
0
def delete_vlan(vlan):
    pynet_sw1 = pyeapi.connect_to("pynet-sw1")
    cmds = ['no vlan ' + vlan]
    try:
        pynet_sw1.config(cmds)
    except pyeapi.eapilib.CommandError as e:
        print "Run into an error during vlan deletion:"
        print str(e)
        exit(1)

    print "Vlan-id %s was deleted." % vlan
    return True
def main():

   '''
    Simple Ansible module to create an Arista VLAN
    '''

    module = AnsibleModule(
        argument_spec=dict(
            arista_sw=dict(required=True),
            vlan_id=dict(required=True),
            vlan_name=dict(required=False),
        )
    )

    vlan_string = "vlan %s" %vlan_id
    name_string = "name %s" %vlan_name


    ssl._create_default_https_context = ssl._create_unverified_context

    remote_connect=pyeapi.connect_to("pynet-sw4")
    response=remote_connect.enable("show running-config")
    config=response[0]['result']['cmds']
    if vlan_string in config.keys():
        is_configured = True
        vlan_config = config[vlan_string]
    else:
        is_configured = False

    if opcode == '--name':
        if is_configured:
            print "vlan %s IS CONFIGURED" %vlan_num
            print "  NAME IS %s" %name_string
            if not name_string in vlan_config.keys():
                print "    BUT NAME IS INCORRECT"
                print "RECONFIGURE VLAN NAME"
                commands = [vlan_string,name_string]
                print "COMMANDS=%s" %commands
                remote_connect.config(commands)
        else:
            print "vlan %s IS NOT CONFIGURED" %vlan_num
            commands = [vlan_string,name_string]
            print "COMMANDS=%s" %commands
            remote_connect.config(commands)
            print "vlan %s CONFIGURED" %vlan_num

    elif opcode=='--remove':
        if is_configured:
             commands = ['no %s' %vlan_string]
             remote_connect.config(commands)
             print "vlan %s REMOVED" %vlan_num
        else:
            print "vlan %s IS NOT CONFIGURED" %vlan_num
Exemple #44
0
def vlanexist(vlanid):
    """
    Check if the VLAN exists on the device.
    """
    vlantocheck = str(vlanid)
    arista_connection = pyeapi.connect_to("pynet-sw2")
    vlanapi = arista_connection.api('vlans')
    result = vlanapi.get(vlantocheck)
    if result is None:
        return False
    else:
        return True
def vlanexist(vlanid):
    """
    Check if the VLAN exists on the device.
    """
    vlantocheck = str(vlanid)
    arista_connection = pyeapi.connect_to("pynet-sw2")
    vlanapi = arista_connection.api('vlans')
    result = vlanapi.get(vlantocheck)
    if result is None:
        return False
    else:
        return True
def main():
  #pynet_sw3_raw = pyeapi.connect(transport='https', host='50.76.53.27', username='******', password='******', port=8443, timeout=60, return_node=False)
  pynet_sw3 = pyeapi.connect_to("pynet-sw3")
  show_interfaces = pynet_sw3.enable("show interfaces")
  response_list = show_interfaces[0]
  #print response_list.keys()
  #print response_list['result'].keys()
  #for dict in response_list['result']
  for interface in response_list['result'][u'interfaces']:
    if u'interfaceCounters' in response_list['result'][u'interfaces'][interface].keys():
      print("{} InOctets: {}".format(interface, response_list['result'][u'interfaces'][interface][u'interfaceCounters'][u'inOctets']))
      print("{} OutOctets: {}".format(interface, response_list['result'][u'interfaces'][interface][u'interfaceCounters'][u'outOctets']))
def main() :

    action = validate_args()

    conn = pyeapi.connect_to( 'pynet-sw2' )
    if action == 'R' :
        vlan_id = sys.argv[2]
        remove_vlan( conn, vlan_id )
    else:
        vlan_name = sys.argv[2]
        vlan_id = sys.argv[3]
        add_vlan( conn, vlan_id, vlan_name )
Exemple #48
0
def create_vlan(vlan):
    pynet_sw1 = pyeapi.connect_to("pynet-sw1")
    cmds = ['vlan ' + vlan[0], 'name ' + vlan[1]]
    try:
        pynet_sw1.config(cmds)
    except pyeapi.eapilib.CommandError as e:
        print "Run into an error during vlan creation:"
        print str(e)
        exit(1)

    print "Vlan-id %s was succesfully created." % vlan[0]
    return True
Exemple #49
0
def remove_vlan(a_switch, vlanid):
    a_connection = pyeapi.connect_to(MY_SWITCH)
    whole_result = a_connection.enable("show vlan")
    vlans = whole_result[0]["result"]["vlans"]
    cmds = ['no vlan '+vlanid]
    if vlanid in vlans:
        print "vlan exists"
        a_connection.config(cmds)
        whole_result = a_connection.enable("show vlan")
        vlans = whole_result[0]["result"]["vlans"]
        pprint(vlans)
    else:
        print "vlan doesn't exist"
Exemple #50
0
def add_vlan(a_switch, vlanid, name):
    a_connection = pyeapi.connect_to(MY_SWITCH)
    whole_result = a_connection.enable("show vlan")
    vlans = whole_result[0]["result"]["vlans"]
    cmds = ['vlan '+vlanid, 'name '+name]
    if vlanid in vlans:
        print "vlan exists"
    else:
        a_connection.config(cmds) 
        print "vlan doesn't exist"
        whole_result = a_connection.enable("show vlan")
        vlans = whole_result[0]["result"]["vlans"]
        pprint(vlans)
Exemple #51
0
def main(args):
    '''Acquire necessary input options, connect to Arista switch, add/remove/list VLANs
    per CLI args.'''
    help_str = 'VLAN ID ({}-{})'.format(VLAN_MIN, VLAN_MAX)
    parser = argparse.ArgumentParser(
        description='Add/Remove/List VLANs on Arista switch')
    parser.add_argument('--version', action='version', version=__version__)
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='display verbose output',
                        default=False)
    parser.add_argument('vlanid',
                        nargs='?',
                        help='Add (-a implied) {}'.format(help_str),
                        default='-')
    groupx = parser.add_mutually_exclusive_group()
    groupx.add_argument('-a', '--add', help='Add {}'.format(help_str))
    groupx.add_argument('-r', '--remove', help='Remove {}'.format(help_str))
    groupx.add_argument('-l',
                        '--list',
                        action='store_true',
                        help='List current VLANs and their names')
    parser.add_argument('-n', '--name', help='Name of VLAN to add/remove')
    args = parser.parse_args()

    # Debugging:
    ##print 'args:  {}'.format(args)

    if is_int(args.vlanid) and args.add:
        print 'Error:  Use either {} <VLAN_ID> -or- {} -a <VLAN_ID>'.format(
            sys.argv[0], sys.argv[0])
        sys.exit(1)

    # Connect to Arista switch
    pynet_sw = pyeapi.connect_to(MY_SWITCH)

    if args.list:
        vlan_list(pynet_sw, args.verbose)
    elif is_int(args.vlanid):
        vlan_add(pynet_sw, args.vlanid, args.name, args.verbose)
    elif args.add:
        vlan_add(pynet_sw, args.add, args.name, args.verbose)
    elif args.remove:
        vlan_remove(pynet_sw, args.remove, args.name, args.verbose)
    else:
        print 'Usage:  {} {{[-a] <VLAN_ID> | -r <VLAN_ID> '.format(sys.argv[0]) + \
                 '[-n <VLAN_Name>]} | [-l] | [--version]'
        print '            [-v] (Must be paired with a | r | l)'
        sys.exit(1)
def main():
    change = False
    module = AnsibleModule(
        argument_spec=dict(vlanid=dict(required=True), name=dict(required=True), sw=dict(required=True))
    )
    vlan_id = module.params["vlanid"]
    vlan_name = module.params.get("name")
    sw = module.params["sw"]

    conn = pyeapi.connect_to(sw)
    change = run(conn, "add", vlan_id, vlan_name)

    ms = "vlan_id " + str(vlan_id) + " name " + str(vlan_name)
    module.exit_json(msg=ms, changed=change)
Exemple #53
0
def main():
    conn1 = pyeapi.connect_to("pynet-sw1")

    parser = argparse.ArgumentParser(description="Add/Delete VLAN")
    parser.add_argument("--vlan_id",
                        help="VLAN number",
                        action="store",
                        dest="vlan_id",
                        type=int)
    parser.add_argument("--name",
                        help="VLAN name",
                        action="store",
                        dest="vlan_name",
                        type=str)
    parser.add_argument("--add",
                        help="add the given VLAN",
                        action="store_true",
                        dest="to_add")
    parser.add_argument("--delete",
                        help="delete the given VLAN",
                        action="store_true",
                        dest="to_delete")

    meta_args = parser.parse_args()
    vlan_id = meta_args.vlan_id
    vlan_name = meta_args.vlan_name
    to_add = meta_args.to_add
    to_delete = meta_args.to_delete

    vlan_existence = vlan_existence_checker(conn1, vlan_id)

    if to_delete:
        print vlan_existence
        if vlan_existence:
            print "Removing this VLAN"
            vlan_command = 'no vlan {}'.format(vlan_id)
            conn1.config(vlan_command)
        else:
            print "Action aborted because there's no such a VLAN"
    if to_add:
        if vlan_existence:
            if vlan_name != None and vlan_existence != vlan_name:
                print "Setting new name for an existed VLAN"
                config_vlan(conn1, vlan_id, vlan_name)
            else:
                print "VLAN exists, no action's required"
        else:
            print "Adding a new VLAN"
            config_vlan(conn1, vlan_id, vlan_name)
Exemple #54
0
def main():
    eapi_conn = pyeapi.connect_to("pynet-sw2")
    parser = argparse.ArgumentParser(
        description="Idempotent addition/removal of VLAN to Arista switch")
    parser.add_argument("vlan_id",
                        help="VLAN number to create or remove",
                        action="store",
                        type=int)
    parser.add_argument("--name",
                        help="Specify VLAN name",
                        action="store",
                        dest="vlan_name",
                        type=str)
    parser.add_argument("--remove",
                        help="Remove the given VLAN ID",
                        action="store_true")

    cli_args = parser.parse_args()
    vlan_id = cli_args.vlan_id
    remove = cli_args.remove
    vlan_name = six.text_type(cli_args.vlan_name)

    check_vlan = sh_vlan_check(eapi_conn, vlan_id)

    if remove:
        if check_vlan:
            try:
                question = raw_input(
                    "VLAN exists, are you sure you want to remove?[Y/N]")
            except NameError:
                question = input(
                    "VLAN exists, are you sure you want to remove?[Y/N]")

            if (question == "y" or question == "Y"):
                print("OK, removing it")
                command_str = 'no vlan {}'.format(vlan_id)
                eapi_conn.config([command_str])
        else:
            print("VLAN does not exist, no action required")
    else:
        if check_vlan:
            if vlan_name is not None and check_vlan != vlan_name:
                print("VLAN already exists, setting VLAN name")
                config_vlan(eapi_conn, vlan_id, vlan_name)
            else:
                print("VLAN already exists, no action required")
        else:
            print("Adding VLAN including vlan_name (if present)")
            config_vlan(eapi_conn, vlan_id, vlan_name)
Exemple #55
0
def main():
    pynet_sw1 = pyeapi.connect_to("pynet-sw1")
    show_if = pynet_sw1.enable("show interfaces")
    interfaces = show_if[0]["result"]["interfaces"]
    print "******** Switch Interface Counters ********\n"
    for intf in interfaces:
        if intf.startswith("Vlan"):
            continue
        else:
            print intf + " >>> ",
            print "  InOctets:",
            print interfaces[intf]["interfaceCounters"]["inOctets"], 
            print "  OutOctets:",
            print interfaces[intf]["interfaceCounters"]["outOctets"]
    print "\n"    
Exemple #56
0
def main():
    con_establish = pyeapi.connect_to("pynet-sw2")
    interfaces = con_establish.enable("show interfaces")
    interfaces = output_result(interfaces)
    interfaces = interfaces['interfaces']
    statistics = {}
    for interface, items in interfaces.items():
        int_counters = items.get('interfaceCounters', {})
        statistics[interface] = (int_counters.get('inOctets'),
                                 int_counters.get('outOctets'))
    print("\n{:20} {:<20} {:<20}".format("Interface:", "inOctets",
                                         "outOctets"))
    for ints, octets in sorted(statistics.items()):
        print("{:20} {:<20} {:<20}".format(ints, six.text_type(octets[0]),
                                           six.text_type(octets[1])))
Exemple #57
0
def main():

    connect = pyeapi.connect_to("pynet-sw4")

    raw_output = connect.enable("show interfaces")
    interfaces = raw_output[0]['result']['interfaces']

    for interface in interfaces:
        if 'interfaceCounters' in interfaces[interface]:
            print "  Interface: " + str(interfaces[interface]['name'])
            print "  In Octets: " + str(
                interfaces[interface]['interfaceCounters']['inOctets'])
            print " Out Octets: " + str(
                interfaces[interface]['interfaceCounters']['outOctets'])
            print ""
Exemple #58
0
def main():
    '''
    Add/remove vlans from Arista switch in an idempotent manner
    '''
    eapi_conn = pyeapi.connect_to("pynet-sw2")

    # Argument parsing
    parser = argparse.ArgumentParser(
        description="Idempotent addition/removal of VLAN to Arista switch")
    parser.add_argument("vlan_id",
                        help="VLAN number to create or remove",
                        action="store",
                        type=int)
    parser.add_argument("--name",
                        help="Specify VLAN name",
                        action="store",
                        dest="vlan_name",
                        type=str)
    parser.add_argument("--remove",
                        help="Remove the given VLAN ID",
                        action="store_true")

    cli_args = parser.parse_args()
    vlan_id = cli_args.vlan_id
    remove = cli_args.remove
    vlan_name = cli_args.vlan_name

    # Check if VLAN already exists
    check_vlan = check_vlan_exists(eapi_conn, vlan_id)

    # check if action is remove or add
    if remove:
        if check_vlan:
            print "VLAN exists, removing it"
            command_str = 'no vlan {}'.format(vlan_id)
            eapi_conn.config([command_str])
        else:
            print "VLAN does not exist, no action required"
    else:
        if check_vlan:
            if vlan_name is not None and check_vlan != vlan_name:
                print "VLAN already exists, setting VLAN name"
                configure_vlan(eapi_conn, vlan_id, vlan_name)
            else:
                print "VLAN already exists, no action required"
        else:
            print "Adding VLAN including vlan_name (if present)"
            configure_vlan(eapi_conn, vlan_id, vlan_name)
Exemple #59
0
def main():
    '''main'''
    node = pyeapi.connect_to('pynet-sw3')

    #Creating parser for run-time variables
    parser = argparse.ArgumentParser(description="Add/remove VLAN")
    parser.add_argument("vlan_id",
                        help="VLAN number to create or remove",
                        action="store",
                        type=int)
    parser.add_argument('--name',
                        action='store',
                        dest='vlan_name',
                        help='Name of VLAN')
    parser.add_argument("--remove",
                        action="store_true",
                        help="Remove the supplied VLAN ID")

    #Parsing input
    c_args = parser.parse_args()
    vlan_id = c_args.vlan_id
    vlan_name = c_args.vlan_name
    remove = c_args.remove

    #Check if vlan exists
    vlan_exists = enable_cmds(node, 'show vlan id %s' % vlan_id)
    if vlan_exists is not False:
        vlan_exists = vlan_exists['vlans']

    if remove:
        #if the remove flag was specified and the vlan exists, delete it.
        if vlan_exists:
            print("VLAN %s is configured. Deleting." % vlan_id)
            conf_cmds(node, ['no vlan %s' % vlan_id])
        #if the vlan does not exist, nothing to delete...
        else:
            print("VLAN %s is not configured. Nothing to delete." % vlan_id)
    else:
        #if the remove flag was not specified and vlan exists, do nothing
        if vlan_exists:
            print("VLAN %s is already configured." % vlan_id)
        #if the vlan does not exist, create it.
        else:
            print("VLAN %s is not configured. Adding." % vlan_id)
            if vlan_name is not None:
                conf_cmds(node, ['vlan %s' % vlan_id, 'name %s' % vlan_name])
            else:
                conf_cmds(node, ['vlan %s' % vlan_id])
def main():
    pynet_sw4 = pyeapi.connect_to("pynet-sw4")
    command_result = pynet_sw4.enable('show interfaces')
    show_int_output = command_result[0]['result']
    interface_dict = show_int_output['interfaces']
    #pprint(interface_dict)
    sorted_ints = sorted(interface_dict.keys())
    print("")
    print("{:16}{:16}{:16}".format("Interface", "InOctets", "OutOctets"))
    print("{:-<16}{:-<16}{:-<16}".format("", "", ""))
    for int in sorted_ints:
        # Use .get() instead of a direct reference to have option of specifying a default if key not found
        in_octets = interface_dict[int].get('interfaceCounters', {}).get('inOctets', "")
        out_octets = interface_dict[int].get('interfaceCounters', {}).get('outOctets', "")
        print("{:16}{:<16}{:<16}".format(int, in_octets, out_octets))
    print("")