Best Python code snippet using avocado_python
slxos_l2_interface.py
Source:slxos_l2_interface.py  
...265                result.extend(range(start, stop + 1))266            else:267                result.append(int(part))268    return sorted(result)269def get_list_of_vlans(module):270    config = run_commands(module, ['show vlan brief'])[0]271    vlans = set()272    lines = config.strip().splitlines()273    for line in lines:274        line_parts = line.split()275        if line_parts:276            try:277                int(line_parts[0])278            except ValueError:279                continue280            vlans.add(line_parts[0])281    return list(vlans)282def flatten_list(commands):283    flat_list = []284    for command in commands:285        if isinstance(command, list):286            flat_list.extend(command)287        else:288            flat_list.append(command)289    return flat_list290def map_params_to_obj(module):291    obj = []292    aggregate = module.params.get('aggregate')293    if aggregate:294        for item in aggregate:295            for key in item:296                if item.get(key) is None:297                    item[key] = module.params[key]298            obj.append(item.copy())299    else:300        obj.append({301            'name': module.params['name'],302            'mode': module.params['mode'],303            'access_vlan': module.params['access_vlan'],304            'native_vlan': module.params['native_vlan'],305            'trunk_vlans': module.params['trunk_vlans'],306            'trunk_allowed_vlans': module.params['trunk_allowed_vlans'],307            'state': module.params['state']308        })309    return obj310def main():311    """ main entry point for module execution312    """313    element_spec = dict(314        name=dict(type='str', aliases=['interface']),315        mode=dict(choices=['access', 'trunk'], default='access'),316        access_vlan=dict(type='str'),317        native_vlan=dict(type='str'),318        trunk_vlans=dict(type='str'),319        trunk_allowed_vlans=dict(type='str'),320        state=dict(choices=['absent', 'present', 'unconfigured'], default='present')321    )322    aggregate_spec = deepcopy(element_spec)323    # remove default in aggregate spec, to handle common arguments324    remove_default_spec(aggregate_spec)325    argument_spec = dict(326        aggregate=dict(type='list', elements='dict', options=aggregate_spec),327    )328    argument_spec.update(element_spec)329    module = AnsibleModule(argument_spec=argument_spec,330                           mutually_exclusive=[['access_vlan', 'trunk_vlans'],331                                               ['access_vlan', 'native_vlan'],332                                               ['access_vlan', 'trunk_allowed_vlans']],333                           supports_check_mode=True)334    warnings = list()335    commands = []336    result = {'changed': False, 'warnings': warnings}337    want = map_params_to_obj(module)338    for w in want:339        name = w['name']340        mode = w['mode']341        access_vlan = w['access_vlan']342        state = w['state']343        trunk_vlans = w['trunk_vlans']344        native_vlan = w['native_vlan']345        trunk_allowed_vlans = w['trunk_allowed_vlans']346        args = dict(name=name, mode=mode, access_vlan=access_vlan,347                    native_vlan=native_vlan, trunk_vlans=trunk_vlans,348                    trunk_allowed_vlans=trunk_allowed_vlans)349        proposed = dict((k, v) for k, v in args.items() if v is not None)350        name = name.lower()351        if mode == 'access' and state == 'present' and not access_vlan:352            module.fail_json(msg='access_vlan param is required when mode=access && state=present')353        if mode == 'trunk' and access_vlan:354            module.fail_json(msg='access_vlan param not supported when using mode=trunk')355        if not is_switchport(name, module):356            module.fail_json(msg='Ensure interface is configured to be a L2'357                             '\nport first before using this module. You can use'358                             '\nthe slxos_interface module for this.')359        if interface_is_portchannel(name, module):360            module.fail_json(msg='Cannot change L2 config on physical '361                             '\nport because it is in a portchannel. '362                             '\nYou should update the portchannel config.')363        # existing will never be null for Eth intfs as there is always a default364        existing = get_switchport(name, module)365        # Safeguard check366        # If there isn't an existing, something is wrong per previous comment367        if not existing:368            module.fail_json(msg='Make sure you are using the FULL interface name')369        if trunk_vlans or trunk_allowed_vlans:370            if trunk_vlans:371                trunk_vlans_list = vlan_range_to_list(trunk_vlans)372            elif trunk_allowed_vlans:373                trunk_vlans_list = vlan_range_to_list(trunk_allowed_vlans)374                proposed['allowed'] = True375            existing_trunks_list = vlan_range_to_list((existing['trunk_vlans']))376            existing['trunk_vlans_list'] = existing_trunks_list377            proposed['trunk_vlans_list'] = trunk_vlans_list378        current_vlans = get_list_of_vlans(module)379        if state == 'present':380            if access_vlan and access_vlan not in current_vlans:381                module.fail_json(msg='You are trying to configure a VLAN'382                                 ' on an interface that\ndoes not exist on the '383                                 ' switch yet!', vlan=access_vlan)384            elif native_vlan and native_vlan not in current_vlans:385                module.fail_json(msg='You are trying to configure a VLAN'386                                 ' on an interface that\ndoes not exist on the '387                                 ' switch yet!', vlan=native_vlan)388            else:389                command = get_switchport_config_commands(name, existing, proposed, module)390                commands.append(command)391        elif state == 'unconfigured':392            is_default = is_switchport_default(existing)...pn_igmp_snooping.py
Source:pn_igmp_snooping.py  
1#!/usr/bin/python2# Copyright: (c) 2018, Pluribus Networks3# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)4from __future__ import absolute_import, division, print_function5__metaclass__ = type6ANSIBLE_METADATA = {'metadata_version': '1.1',7                    'status': ['preview'],8                    'supported_by': 'community'}9DOCUMENTATION = """10---11module: pn_igmp_snooping12author: "Pluribus Networks (@rajaspachipulusu17)"13version_added: "2.8"14short_description: CLI command to modify igmp-snooping15description:16  - This module can be used to modify Internet Group Management Protocol (IGMP) snooping.17options:18  pn_cliswitch:19    description:20      - Target switch to run the CLI on.21    required: False22    type: str23  state:24    description:25      - State the action to perform. Use C(update) to modify the igmp-snooping.26    required: True27    type: str28    choices: ['update']29  pn_enable:30    description:31      - enable or disable IGMP snooping.32    required: False33    type: bool34  pn_query_interval:35    description:36      - IGMP query interval in seconds.37    required: False38    type: str39  pn_igmpv2_vlans:40    description:41      - VLANs on which to use IGMPv2 protocol.42    required: False43    type: str44  pn_igmpv3_vlans:45    description:46      - VLANs on which to use IGMPv3 protocol.47    required: False48    type: str49  pn_enable_vlans:50    description:51      - enable per VLAN IGMP snooping.52    required: False53    type: str54  pn_vxlan:55    description:56      - enable or disable IGMP snooping on vxlans.57    required: False58    type: bool59  pn_query_max_response_time:60    description:61      - maximum response time, in seconds, advertised in IGMP queries.62    required: False63    type: str64  pn_scope:65    description:66      - IGMP snooping scope - fabric or local.67    required: False68    choices: ['local', 'fabric']69  pn_no_snoop_linklocal_vlans:70    description:71      - Remove snooping of link-local groups(224.0.0.0/24) on these vlans.72    required: False73    type: str74  pn_snoop_linklocal_vlans:75    description:76      - Allow snooping of link-local groups(224.0.0.0/24) on these vlans.77    required: False78    type: str79"""80EXAMPLES = """81- name: 'Modify IGMP Snooping'82  pn_igmp_snooping:83    pn_cliswitch: 'sw01'84    state: 'update'85    pn_vxlan: True86    pn_enable_vlans: '1-399,401-4092'87    pn_no_snoop_linklocal_vlans: 'none'88    pn_igmpv3_vlans: '1-399,401-4092'89- name: 'Modify IGMP Snooping'90  pn_igmp_snooping:91    pn_cliswitch: 'sw01'92    state: 'update'93    pn_vxlan: False94    pn_enable_vlans: '1-399'95    pn_no_snoop_linklocal_vlans: 'none'96    pn_igmpv3_vlans: '1-399'97"""98RETURN = """99command:100  description: the CLI command run on the target node.101  returned: always102  type: str103stdout:104  description: set of responses from the igmp-snooping command.105  returned: always106  type: list107stderr:108  description: set of error responses from the igmp-snooping command.109  returned: on error110  type: list111changed:112  description: indicates whether the CLI caused changes on the target.113  returned: always114  type: bool115"""116from ansible.module_utils.basic import AnsibleModule117from ansible.module_utils.network.netvisor.pn_nvos import pn_cli, run_cli, booleanArgs118def main():119    """ This section is for arguments parsing """120    state_map = dict(121        update='igmp-snooping-modify'122    )123    module = AnsibleModule(124        argument_spec=dict(125            pn_cliswitch=dict(required=False, type='str'),126            state=dict(required=True, type='str',127                       choices=state_map.keys()),128            pn_enable=dict(required=False, type='bool'),129            pn_query_interval=dict(required=False, type='str'),130            pn_igmpv2_vlans=dict(required=False, type='str'),131            pn_igmpv3_vlans=dict(required=False, type='str'),132            pn_enable_vlans=dict(required=False, type='str'),133            pn_vxlan=dict(required=False, type='bool'),134            pn_query_max_response_time=dict(required=False, type='str'),135            pn_scope=dict(required=False, type='str',136                          choices=['local', 'fabric']),137            pn_no_snoop_linklocal_vlans=dict(required=False, type='str'),138            pn_snoop_linklocal_vlans=dict(required=False, type='str'),139        ),140        required_one_of=[['pn_enable', 'pn_query_interval',141                          'pn_igmpv2_vlans',142                          'pn_igmpv3_vlans',143                          'pn_enable_vlans',144                          'pn_vxlan',145                          'pn_query_max_response_time',146                          'pn_scope',147                          'pn_no_snoop_linklocal_vlans',148                          'pn_snoop_linklocal_vlans']]149    )150    # Accessing the arguments151    cliswitch = module.params['pn_cliswitch']152    state = module.params['state']153    enable = module.params['pn_enable']154    query_interval = module.params['pn_query_interval']155    igmpv2_vlans = module.params['pn_igmpv2_vlans']156    igmpv3_vlans = module.params['pn_igmpv3_vlans']157    enable_vlans = module.params['pn_enable_vlans']158    vxlan = module.params['pn_vxlan']159    query_max_response_time = module.params['pn_query_max_response_time']160    scope = module.params['pn_scope']161    no_snoop_linklocal_vlans = module.params['pn_no_snoop_linklocal_vlans']162    snoop_linklocal_vlans = module.params['pn_snoop_linklocal_vlans']163    command = state_map[state]164    # Building the CLI command string165    cli = pn_cli(module, cliswitch)166    if command == 'igmp-snooping-modify':167        cli += ' %s ' % command168        cli += booleanArgs(enable, 'enable', 'disable')169        cli += booleanArgs(vxlan, 'vxlan', 'no-vxlan')170        if query_interval:171            cli += ' query-interval ' + query_interval172        if igmpv2_vlans:173            cli += ' igmpv2-vlans ' + igmpv2_vlans174        if igmpv3_vlans:175            cli += ' igmpv3-vlans ' + igmpv3_vlans176        if enable_vlans:177            cli += ' enable-vlans ' + enable_vlans178        if query_max_response_time:179            cli += ' query-max-response-time ' + query_max_response_time180        if scope:181            cli += ' scope ' + scope182        if no_snoop_linklocal_vlans:183            cli += ' no-snoop-linklocal-vlans ' + no_snoop_linklocal_vlans184        if snoop_linklocal_vlans:185            cli += ' snoop-linklocal-vlans ' + snoop_linklocal_vlans186    run_cli(module, cli, state_map)187if __name__ == '__main__':...create_vlans.py
Source:create_vlans.py  
1import yaml2def create_vlan():3    '''creates vlans from user input and saves in a config file'''4    vlans_list = []5    #get the number of vlans from the user6    num_vlans = int(input('\nEnter the number of vlans to create: '))7    for c in range(1, num_vlans+1):8        vlans = {}9        print(f'\nVLAN setup {c}\n')10        vlan_id = input('vlan id: ')11        vlan_name = input('vlan name: ')12        vlans['id'] = vlan_id13        vlans['name'] = vlan_name14        vlans_list.append(vlans)15    with open('yaml-configs/vlan_commands.yaml', 'a') as vlan_commands_file:16        vlans_list = yaml.dump(vlans_list, vlan_commands_file)17if __name__ == "__main__":...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
