def setUp(self, mock_is_eth, mock_get_index, mock_device): self.device = mock_device mock_get_index.return_value = IFACE_INDEX mock_is_eth.return_value = True, False self.eth_iface = Interface(self.device, ETH_IFACE) mock_is_eth.return_value = False, True self.lo_iface = Interface(self.device, LOGICAL_IFACE)
def convert_iface_list(device, iface_list): converted_list = [] for iface_name in iface_list: iface = Interface(device, iface_name) converted_list.append(iface.interface_name) return converted_list
def param_check(self, **portchannel): """Param validation for portchannel Args: state (str): present or absent portchannel: see Keyword Args Keyword Args: members (list): members by interface name being configured Raises: InvalidPortType: when existing port type does not match desired type of portchannel AggregationGroupError: when an interface is already a member of a different portchannel than the one being configured. """ if portchannel.get('members'): members = portchannel.get('members') for each in members: interf = Interface(self.device, each) configured_type = interf.get_config().get('type') # if configured_type == 'bridged': # configured_type = 'bridged' if configured_type != self.pc_type: raise InvalidPortType(each, configured_type, self.pc_type) member_dict = self.get_all_members(asdict=True) existing_group = member_dict.get(each) if existing_group: if existing_group != self._xgroupid: raise AggregationGroupError(each)
def _build_iface_updown(self, iface_list, updown): """Stage commands to bring the interfaces up or down. """ for iface_name in iface_list: iface = Interface(self.device, iface_name) if not iface.iface_exists: raise InterfaceAbsentError(iface.interface_name) iface.build(stage=True, admin=updown)
def _build_mad_exclude(self, iface_list): """Build the configuration for adding interfaces to the mad exclude list. """ for iface_name in iface_list: iface = Interface(self.device, iface_name) if not iface.iface_exists: raise InterfaceAbsentError(iface.interface_name) if not self.device.stage_config( 'mad exclude interface {0}'.format(iface.interface_name), 'cli_config'): return False return True
def get_index_from_interface(self, interface): """Get IfIndex from interface name Args: interface (str): name of the interface Returns: This returns the IfIndex for an interface. """ local_index = self._members_map_interface_key.get(interface) if local_index: index = local_index else: intf = Interface(self.device, interface) index = str(intf.iface_index) self._members_map_interface_key[interface] = index return index
def main(): module = AnsibleModule( argument_spec=dict(name=dict(required=True), admin=dict(choices=['up', 'down']), description=dict(), type=dict(choices=['bridged', 'routed']), duplex=dict(choices=['auto', 'full']), speed=dict(type='str'), state=dict(choices=['present', 'absent', 'default'], default='present'), hostname=dict(required=True), username=dict(required=True), password=dict(required=True), port=dict(type='int', default=830)), supports_check_mode=True) if not HAS_PYHP: safe_fail(module, msg='There was a problem loading from the pyhpecw7 ' + 'module.', error=str(ie)) filtered_keys = ('state', 'hostname', 'username', 'password', 'port', 'CHECKMODE', 'name') hostname = socket.gethostbyname(module.params['hostname']) username = module.params['username'] password = module.params['password'] port = module.params['port'] device = HPCOM7(host=hostname, username=username, password=password, port=port) name = module.params['name'] state = module.params['state'] changed = False if state == 'present': if module.params.get('type'): if module.params.get('admin') or module.params.get('description')\ or module.params.get('duplex') or module.params.get('speed'): module.fail_json(msg='The type parameter is incompatible with:' '\nadmin, description, duplex, speed.' '\nPlease configure type first by itself,' '\nthen run again.') proposed = dict((k, v) for k, v in module.params.iteritems() if v is not None and k not in filtered_keys) try: device.open() except ConnectionError as e: safe_fail(module, device, msg=str(e), descr='Error opening connection to device.') try: interface = Interface(device, name) except PYHPError as e: safe_fail(module, device, descr='There was problem recognizing that interface.', msg=str(e)) try: interface.param_check(**proposed) except PYHPError as e: safe_fail(module, device, descr='There was problem with the supplied parameters.', msg=str(e)) try: existing = interface.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error getting existing config.') if state == 'present': delta = dict( set(proposed.iteritems()).difference(existing.iteritems())) if delta or not existing: original = existing if not interface.iface_exists: try: interface.create_logical() interface.update() changed = True existing = interface.get_config() except PYHPError as e: safe_fail(module, device, msg='Exception message ' + str(e), descr='There was a problem creating' + ' the logical interface.') delta = dict( set(proposed.iteritems()).difference(existing.iteritems())) if delta: interface.build(stage=True, **delta) elif state == 'default': defaults = interface.get_default_config() delta = dict( set(existing.iteritems()).difference(defaults.iteritems())) if delta: interface.default(stage=True) elif state == 'absent': if interface.iface_exists: if interface.is_ethernet: defaults = interface.get_default_config() delta = dict( set(existing.iteritems()).difference(defaults.iteritems())) if delta: try: interface.default(stage=True) except InterfaceError as e: safe_fail(module, device, msg=str(e), descr='Error getting default configuration.') else: try: interface.remove_logical(stage=True) except InterfaceError as e: safe_fail(module, device, msg=str(e), descr='Error removing logical interface.') commands = None end_state = existing if device.staged: commands = device.staged_to_string() if module.check_mode: safe_exit(module, device, changed=True, commands=commands) else: try: device.execute_staged() end_state = interface.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error on device execution.') changed = True results = {} results['proposed'] = proposed results['existing'] = existing results['state'] = state results['commands'] = commands results['changed'] = changed results['end_state'] = end_state safe_exit(module, device, **results)
def main(): module = AnsibleModule(argument_spec=dict( vrid=dict(required=True, type='str'), interface=dict(required=True), vip=dict(required=False), priority=dict(required=False, type='str'), auth_mode=dict(required=False, choices=['simple', 'md5']), key_type=dict(required=False, choices=['cipher', 'plain']), key=dict(required=False, type='str'), preempt=dict(required=False, choices=['yes', 'no']), state=dict(choices=['present', 'absent', 'shutdown', 'undoshutdown'], default='present'), port=dict(default=830, type='int'), hostname=dict(required=True), username=dict(required=True), password=dict(required=True), ), supports_check_mode=True) if not HAS_PYHP: module.fail_json(msg='There was a problem loading from the pyhpecw7 ' + 'module.', error=str(ie)) username = module.params['username'] password = module.params['password'] port = module.params['port'] hostname = socket.gethostbyname(module.params['hostname']) device_args = dict(host=hostname, username=username, password=password, port=port) device = HPCOM7(**device_args) vrid = module.params['vrid'] interface = module.params['interface'].lower() vip = module.params['vip'] priority = module.params['priority'] preempt = module.params['preempt'] auth_mode = module.params['auth_mode'] key_type = module.params['key_type'] key = module.params['key'] if auth_mode: if not key_type or not key: module.fail_json(msg='params key_type and key are required') if key_type or key: if not auth_mode: module.fail_json(msg='auth_mode is required when setting auth') state = module.params['state'] changed = False args = dict(vrid=vrid, priority=priority, preempt=preempt, vip=vip, interface=interface, auth_mode=auth_mode, key_type=key_type, key=key) proposed = dict((k, v) for k, v in args.iteritems() if v is not None) try: device.open() except ConnectionError as e: safe_fail(module, device, msg=str(e), descr='error opening device conn') try: vrrp = VRRP(device, interface, vrid) vrrp_interface = Interface(device, interface) except PYHPError as e: safe_fail(module, device, msg=str(e)) if not vrrp_interface.iface_exists: safe_fail(module, device, msg='interface does not exist.') is_eth, is_rtd = vrrp_interface._is_ethernet_is_routed() if not is_rtd: safe_fail(module, device, msg='interface needs to be a layer 3 interface') try: existing = vrrp.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='could not get existing config') if state == 'present': delta = dict( set(proposed.iteritems()).difference(existing.iteritems())) if delta or auth_mode or \ existing.get('admin') == 'down': delta['vrid'] = vrid if delta.get('key'): delta['auth_mode'] = auth_mode delta['key_type'] = key_type vrrp.build(stage=True, state=state, **delta) elif state == 'absent': if existing: vrrp.remove(stage=True) elif state == 'shutdown': if existing.get('admin') == 'Up': vrrp.shutdown(stage=True) elif state == 'undoshutdown': if existing.get('admin') == 'Down': vrrp.undoshutdown(stage=True) commands = None end_state = existing response = None if device.staged: commands = device.staged_to_string() if module.check_mode: device.close() safe_exit(module, device, changed=True, commands=commands) else: try: response = device.execute_staged() end_state = vrrp.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='error during execution') changed = True results = {} results['proposed'] = proposed results['existing'] = existing results['state'] = state results['commands'] = commands results['changed'] = changed results['end_state'] = end_state results['response'] = response safe_exit(module, device, **results)
def main(): module = AnsibleModule(argument_spec=dict( vsi=dict(required=True, type='str'), interface=dict(required=True, type='str'), instance=dict(required=True, type='str'), encap=dict( required=False, choices=['default', 'tagged', 'untagged', 'only-tagged', 's-vid'], default='default'), vlanid=dict(required=False, type='str'), access_mode=dict(required=False, choices=['ethernet', 'vlan'], default='vlan'), state=dict(choices=['present', 'absent'], default='present'), port=dict(default=830, type='int'), hostname=dict(required=True), username=dict(required=True), password=dict(required=True), ), supports_check_mode=True) if not HAS_PYHP: module.fail_json(msg='There was a problem loading from the pyhpecw7 ' + 'module.', error=str(ie)) username = module.params['username'] password = module.params['password'] port = module.params['port'] hostname = socket.gethostbyname(module.params['hostname']) device_args = dict(host=hostname, username=username, password=password, port=port) device = HPCOM7(**device_args) vsi = module.params['vsi'] interface = module.params['interface'] instance = module.params['instance'] encap = module.params['encap'] vlanid = module.params['vlanid'] access_mode = module.params['access_mode'] state = module.params['state'] if encap in ['only-tagged', 's-vid']: if not vlanid: safe_fail(module, device, msg='vlanid must be set when using only-tagged' + 'and s-vid as the encap') changed = False args = dict(encap=encap, vlanid=vlanid, access_mode=access_mode) proposed = dict((k, v) for k, v in args.items() if v is not None) try: device.open() except ConnectionError as e: safe_fail(module, device, msg=str(e), descr='error opening device conn') try: l2vpn = L2VPN(device) is_l2vpn_enabled = l2vpn.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='L2VPN config check failed') if is_l2vpn_enabled == 'disabled': safe_fail(module, device, msg='l2vpn needs to be enabled.') try: intf = Interface(device, interface) except PYHPError as e: safe_fail(module, device, msg=str(e), descr='could not instantiate interface') if intf.is_routed: safe_fail(module, device, msg='interface needs to be an L2 interface') try: eth = L2EthService(device, interface, instance, vsi) except PYHPError as e: safe_fail(module, device, msg=str(e), descr='L2EthService failure') if not eth.vsi_exist(): safe_fail(module, device, msg='VSI needs to be created before using' + ' this module') try: existing = eth.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='error getting L2EthService config') # existing = {} when service instance doesn't exist on interface # keys: interface, instance, and index exist when an instance is # configured. pretty much means, there won't be a delta at that point # keys: encap and optionally svid/cvid are added based when encap # command is issued on box # keys: vsi added when xconnect command exists on interface for # this instance delta = dict(set(proposed.items()) - set(existing.items())) if state == 'present': if existing: checks(existing, proposed, module) if delta or not existing: eth.build(stage=True, **delta) elif state == 'absent': if existing: eth.remove(stage=True) commands = None end_state = existing if device.staged: commands = device.staged_to_string() if module.check_mode: device.close() safe_exit(module, device, changed=True, commands=commands) else: try: device.execute_staged() end_state = eth.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='error during execution') changed = True results = {} results['proposed'] = proposed results['existing'] = existing results['state'] = state results['commands'] = commands results['changed'] = changed results['end_state'] = end_state safe_exit(module, device, **results)
def _index_from_interface(self, interface): """Returns IfIndex from a given Interface name """ intf = Interface(self.device, interface) return intf.iface_index
device.open() if not device.connected: print("Unable to connect to target switch, exiting ... ") quit(1) E = data_element_maker() top = E.top(E.Ifmgr(E.Interfaces(E.Interface()))) nc_get_reply = device.get(('subtree', top)) # Gets an array of interface names from XML reply_data_names = findall_in_data('Name', nc_get_reply.data_ele) # Constructs interfaces list for reply using only interfaces names for ifname in reply_data_names: interface = Interface(device, ifname.text) iface_config = interface.get_default_config() print(iface_config['admin']) # Show the switchport configs for each interface for ifname in reply_data_names: switchport = Switchport(device, ifname.text) swport_config = switchport.get_config() print(f'name: {ifname.text} -- {swport_config}') # Trunk building example # paramaters for configuring the interface build_args = dict(link_type='trunk', permitted_vlans='1,100-250', pvid='1') # Ten-GigabitEthernet1/0/2 is the test case
def __init__(self, device, interface_name, version=V4): self.device = device self.interface = Interface(device, interface_name) self.interface_name = self.interface.interface_name self.is_routed = self.interface.is_routed self.version = version
from pyhpecw7.comware import HPCOM7 from pyhpecw7.features.vlan import Vlan from pyhpecw7.features.interface import Interface from getpass import getpass ip = raw_input("Enter IP address") device = HPCOM7(host=ip, username='******', password=getpass()) print device.open() vlan = Vlan(device, '1') print vlan.get_config() print vlan.get_vlan_list() interface = Interface(device, 'FortyGigE1/0/50') print interface.get_config() #vlan = Vlan(device, '20') # Add a new vlan #vlan.build() # Stage the Vlan #device.execute() # Execute the chagne #vlan.build(name='NEWV20', descr='DESCR_20') #device.execute() # Execute the chagne #vlan.remove() #device.execute() #interface.default() #response = device.execute() #interface.build(admin='down', description='TEST_DESCR') #rsp = device.execute() # cleanerase - Factory default # config - manage comware configs
def __init__(self, device, interface_name): self.device = device self.interface = Interface(device, interface_name) self.interface_name = self.interface.interface_name self.link_type = 'unknown'