def param_check(self, **params): """Checks given parameters against the interface for various errors. Args: **params: see Keyword Args Keyword Args: admin (str): The up/down state of the interface. 'up' or 'down'. speed (str): The speed of the interface, in Mbps. duplex (str): The duplex of the interface. 'full', 'half', or 'auto'. description (str): The textual description of the interface. type (str): Whether the interface is in layer 2 or layer 3 mode. 'bridged' or 'routed'. Raises: InterfaceTypeError: if the given interface isn't a valid type. InterfaceAbsentError: if the given interface is of type is_ethernet and doesn't exist. InterfaceParamsError: if 'speed' or 'duplex' are supplied for a non ethernet interface. InterfaceVlanMustExist: if the interface is of type 'Vlan-interface' and the the associated vlan doesn't exist. """ if not self.iface_type: raise InterfaceTypeError(self.interface_name, list(self._iface_types)) if not self.iface_exists: if self.iface_type in { 'FortyGigE', 'GigabitEthernet', 'TwentyGigE', 'Ten-GigabitEthernet', 'HundredGigE' }: raise InterfaceAbsentError(self.interface_name) if not self.is_ethernet: param_names = [] if params.get('speed'): param_names.append('speed') if params.get('duplex'): param_names.append('duplex') if param_names: raise InterfaceParamsError(self.interface_name, param_names) if self.iface_type == 'Vlan-interface': number = self.interface_name.split('Vlan-interface')[1] vlan = Vlan(self.device, number) if not vlan.get_config(): raise InterfaceVlanMustExist(self.interface_name, number)
def param_check(self, **params): """Checks given parameters against the interface for various errors. Args: **params: see Keyword Args Keyword Args: admin (str): The up/down state of the interface. 'up' or 'down'. speed (str): The speed of the interface, in Mbps. duplex (str): The duplex of the interface. 'full', 'half', or 'auto'. description (str): The textual description of the interface. type (str): Whether the interface is in layer 2 or layer 3 mode. 'bridged' or 'routed'. Raises: InterfaceTypeError: if the given interface isn't a valid type. InterfaceAbsentError: if the given interface is of type is_ethernet and doesn't exist. InterfaceParamsError: if 'speed' or 'duplex' are supplied for a non ethernet interface. InterfaceVlanMustExist: if the interface is of type 'Vlan-interface' and the the associated vlan doesn't exist. """ if not self.iface_type: raise InterfaceTypeError( self.interface_name, list(self._iface_types)) if not self.iface_exists: if self.iface_type in {'FortyGigE', 'GigabitEthernet', 'TwentyGigE', 'Ten-GigabitEthernet', 'HundredGigE'}: raise InterfaceAbsentError(self.interface_name) if not self.is_ethernet: param_names = [] if params.get('speed'): param_names.append('speed') if params.get('duplex'): param_names.append('duplex') if param_names: raise InterfaceParamsError(self.interface_name, param_names) if self.iface_type == 'Vlan-interface': number = self.interface_name.split('Vlan-interface')[1] vlan = Vlan(self.device, number) if not vlan.get_config(): raise InterfaceVlanMustExist(self.interface_name, number)
def main(): module = AnsibleModule(argument_spec=dict( vlanid=dict(required=True, type='str'), name=dict(required=False), descr=dict(required=False), 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) vlanid = module.params['vlanid'] name = module.params['name'] descr = module.params['descr'] state = module.params['state'] changed = False args = dict(vlanid=vlanid, name=name, descr=descr) 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)) try: vlan = Vlan(device, vlanid) vlan.param_check(**proposed) except LengthOfStringError as lose: safe_fail(module, device, msg=str(lose)) except VlanIDError as vie: safe_fail(module, device, msg=str(vie)) except PYHPError as e: safe_fail(module, device, msg=str(e)) try: existing = vlan.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='error getting vlan config') if state == 'present': delta = dict( set(proposed.iteritems()).difference(existing.iteritems())) if delta: vlan.build(stage=True, **delta) elif state == 'absent': if existing: vlan.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 = vlan.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 main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True), link_type=dict(required=True, choices=['access', 'trunk']), pvid=dict(type='str'), permitted_vlans=dict(type='str'), state=dict(choices=['present', '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') 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('link_type') == 'access': if module.params.get('permitted_vlans'): safe_fail(module, msg='Access interfaces don\'t take' + ' permitted vlan lists.') try: device.open() except ConnectionError as e: safe_fail(module, device, msg=str(e), descr='Error opening connection to device.') # Make sure vlan exists pvid = module.params.get('pvid') if pvid and state != 'default': try: vlan = Vlan(device, pvid) if not vlan.get_config(): safe_fail(module, device, msg='Vlan {0} does not exist,'.format(pvid) + ' Use vlan module to create it.') except PYHPError as e: module.fail_json(msg=str(e), descr='Error initializing Vlan object' + ' or getting current vlan config.') # Make sure port is not part of port channel try: portchannel = Portchannel(device, '99', 'bridged') pc_list = portchannel.get_all_members() except PYHPError as e: module.fail_json(msg=str(e), descr='Error getting port channel information.') if name in pc_list: safe_fail(module, device, msg='{0} is currently part of a port channel.'.format(name) + ' Changes should be made to the port channel interface.') try: switchport = Switchport(device, name) except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error initialzing Switchport object.') # Make sure interface exists and is ethernet if not switchport.interface.iface_exists: safe_fail(module, device, msg='{0} doesn\'t exist on the device.'.format(name)) # Make sure interface is in bridged mode try: if_info = switchport.interface.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error getting current interface config.') if if_info.get('type') != 'bridged': safe_fail(module, device, msg='{0} is not in bridged mode.'.format(name) + ' Please use the interface module to change that.') try: existing = switchport.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error getting switchpot config.') proposed = dict((k, v) for k, v in module.params.items() if v is not None and k not in filtered_keys) if state == 'present': delta = dict(set(proposed.items()) - set(existing.items())) if delta: delta['link_type'] = proposed.get('link_type') pvid = proposed.get('pvid') if pvid: delta['pvid'] = pvid switchport.build(stage=True, **delta) elif state == 'default': defaults = switchport.get_default() delta = dict(set(existing.items()) - set(defaults.items())) if delta: switchport.default(stage=True) 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 = switchport.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error during command 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( name=dict(required=True), link_type=dict(required=True, choices=['access', 'trunk']), pvid=dict(type='str'), permitted_vlans=dict(type='str'), state=dict(choices=['present', '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') 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('link_type') == 'access': if module.params.get('permitted_vlans'): safe_fail(module, msg='Access interfaces don\'t take' + ' permitted vlan lists.') try: device.open() except ConnectionError as e: safe_fail(module, device, msg=str(e), descr='Error opening connection to device.') # Make sure vlan exists pvid = module.params.get('pvid') if pvid and state != 'default': try: vlan = Vlan(device, pvid) if not vlan.get_config(): safe_fail(module, device, msg='Vlan {0} does not exist,'.format(pvid) + ' Use vlan module to create it.') except PYHPError as e: module.fail_json(msg=str(e), descr='Error initializing Vlan object' + ' or getting current vlan config.') # Make sure port is not part of port channel try: portchannel = Portchannel(device, '99', 'bridged') pc_list = portchannel.get_all_members() except PYHPError as e: module.fail_json(msg=str(e), descr='Error getting port channel information.') if name in pc_list: safe_fail(module, device, msg='{0} is currently part of a port channel.'.format(name) + ' Changes should be made to the port channel interface.') try: switchport = Switchport(device, name) except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error initialzing Switchport object.') # Make sure interface exists and is ethernet if not switchport.interface.iface_exists: safe_fail(module, device, msg='{0} doesn\'t exist on the device.'.format(name)) # Make sure interface is in bridged mode try: if_info = switchport.interface.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error getting current interface config.') if if_info.get('type') != 'bridged': safe_fail(module, device, msg='{0} is not in bridged mode.'.format(name) + ' Please use the interface module to change that.') try: existing = switchport.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error getting switchpot config.') proposed = dict((k, v) for k, v in module.params.iteritems() if v is not None and k not in filtered_keys) if state == 'present': delta = dict(set(proposed.iteritems()).difference( existing.iteritems())) if delta: delta['link_type'] = proposed.get('link_type') pvid = proposed.get('pvid') if pvid: delta['pvid'] = pvid switchport.build(stage=True, **delta) elif state == 'default': defaults = switchport.get_default() delta = dict(set(existing.iteritems()).difference( defaults.iteritems())) if delta: switchport.default(stage=True) 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 = switchport.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='Error during command 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( vlanid=dict(required=True, type='str'), name=dict(required=False), descr=dict(required=False), 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) vlanid = module.params['vlanid'] name = module.params['name'] descr = module.params['descr'] state = module.params['state'] changed = False args = dict(vlanid=vlanid, name=name, descr=descr) 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)) try: vlan = Vlan(device, vlanid) vlan.param_check(**proposed) except LengthOfStringError as lose: safe_fail(module, device, msg=str(lose)) except VlanIDError as vie: safe_fail(module, device, msg=str(vie)) except PYHPError as e: safe_fail(module, device, msg=str(e)) try: existing = vlan.get_config() except PYHPError as e: safe_fail(module, device, msg=str(e), descr='error getting vlan config') if state == 'present': delta = dict(set(proposed.iteritems()).difference( existing.iteritems())) if delta: vlan.build(stage=True, **delta) elif state == 'absent': if existing: vlan.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 = vlan.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 setUp(self, mock_device): self.device = mock_device self.vlan = Vlan(self.device, vlanid='77')
class VlanTestCase(BaseFeatureCase): @mock.patch('pyhpecw7.comware.HPCOM7') def setUp(self, mock_device): self.device = mock_device self.vlan = Vlan(self.device, vlanid='77') def test_get_vlan_list(self): expected_get, get_reply = self.xml_get_and_reply('vlan_list') self.device.get.return_value = get_reply expected = ['1', '20', '77'] vlan_list = self.vlan.get_vlan_list() self.assertEqual(vlan_list, expected) self.assert_get_request(expected_get) def test_get_config(self): expected_get, get_reply = self.xml_get_and_reply('vlan') self.device.get.return_value = get_reply expected = {'name': 'hello', 'vlanid': '77', 'descr': 'goodbye'} vlan = self.vlan.get_config() self.assertEqual(vlan, expected) self.assert_get_request(expected_get) def test_build_config(self): result = self.vlan._build_config(state='present') expected = self.read_config_xml('vlan') self.assert_elements_equal(result, expected) result = self.vlan._build_config(state='present', name='hello') expected = self.read_config_xml('vlan_name') self.assert_elements_equal(result, expected) result = self.vlan._build_config('present', name='hello', descr='goodbye') expected = self.read_config_xml('vlan_name_descr') self.assert_elements_equal(result, expected) result = self.vlan._build_config('absent') expected = self.read_config_xml('vlan_absent') self.assert_elements_equal(result, expected) def test_param_check(self): with self.assertRaises(LengthOfStringError): self.vlan.param_check(name=('a' * 255)) with self.assertRaises(LengthOfStringError): self.vlan.param_check(descr=('b' * 255)) @mock.patch.object(Vlan, '_build_config') def test_build(self, mock_build_config): self.vlan.build(name='a', descr='b') mock_build_config.assert_called_with(state='present', name='a', descr='b') self.device.edit_config.assert_called_with(mock_build_config.return_value) self.vlan.build(stage=False, name='a', descr='b') mock_build_config.assert_called_with(state='present', name='a', descr='b') self.device.edit_config.assert_called_with(mock_build_config.return_value) self.vlan.build(stage=True, name='a', descr='b') mock_build_config.assert_called_with(state='present', name='a', descr='b') self.device.stage_config.assert_called_with(mock_build_config.return_value, 'edit_config') @mock.patch.object(Vlan, '_build_config') def test_remove(self, mock_build_config): self.vlan.remove() mock_build_config.assert_called_with(state='absent') self.device.edit_config.assert_called_with(mock_build_config.return_value) self.vlan.remove(stage=False) mock_build_config.assert_called_with(state='absent') self.device.edit_config.assert_called_with(mock_build_config.return_value) self.vlan.remove(stage=True) mock_build_config.assert_called_with(state='absent') self.device.stage_config.assert_called_with(mock_build_config.return_value, 'edit_config')
from pyhpecw7.comware import HPCOM7 from pyhpecw7.features.vlan import Vlan args = dict(host='192.168.10.2', username='******', password='******', port=830, ssh_config=None) device = HPCOM7(**args) print('device.open()') print(device.open()) vlan = Vlan(device, 10) for i in range(10, 21): vlan = Vlan(device, str(i)) if vlan.get_config() == {}: print(str(i) + ' VLAN does not exist') else: print(vlan.get_config())
#!/usr/bin/env python3 from pyhpecw7.comware import HPCOM7 from pyhpecw7.features.vlan import Vlan ''' *** args removed for privacy *** ''' device = HPCOM7(**args) device.open() if not device.connected: print("Unable to connect to target switch, exiting ... ") quit(1) # print list of vlans vlan = Vlan(device, '') vlans = vlan.get_vlan_list() print(vlans) # print config of vlan 100 vlan = Vlan(device, '100') print(vlan.get_config())
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