def inventory_connect(time_out=10.0, time_interval=0.2): """ Mount all unmounted devices and wait for the (asynchronous) connection to occur. Parameters: time_out -- Number of seconds to elapse before time out. time_interval -- Initial time interval between checks. Raise: Exception if any connections are not verified during the time allocated. """ unmounted_device_names = set(inventory_unmounted()) if unmounted_device_names: for device_name in unmounted_device_names: mount_from_settings(device_name) time_accum = 0.0 num_checks = 0 while time_accum < time_out: unconnected_device_names = unmounted_device_names - set(inventory_connected()) num_checks += 1 if not unconnected_device_names: print('%s network device connection(s) verified after %s check(s) and %s seconds.' % (len(unmounted_device_names), num_checks, time_accum)) return else: # Don't hammer the Controller or it will crash. # This not a denial-of-service (DOS) attack ;-) # Print a message explaining the pause, otherwise user might terminate. expanding_interval = time_interval * num_checks time_accum += expanding_interval print('sleep(%s) seconds pending connection to %s network device(s).' % (expanding_interval, len(unconnected_device_names))) time.sleep(expanding_interval) unconnected_device_names = unmounted_device_names - set(inventory_connected()) if unconnected_device_names: raise Exception('Expected connection after %s check(s) and %s seconds to network device(s): ' % (num_checks, time_accum) + ', '.join(unconnected_device_names))
def main(): if mounted(device_name): print('Preparation.') print('device_dismount(', device_name, sep='', end=')\n') device_dismount(device_name) time.sleep(1) print() print('Verify absence of unreachable device.') in_inventory = device_name in inventory() in_mounted = device_name in inventory_mounted() print(device_name + ' in inventory', in_inventory, sep=': ') print(device_name + ' is mounted', in_mounted, sep=': ') assert not in_inventory assert not in_mounted del in_inventory, in_mounted print() print('Discover effect of mounting unreachable device.') print('device_mount(' + device_name, device_address, device_port, sep=', ', end=')\n') device_mount(device_name, device_address, device_port, device_username, device_password) time.sleep(1) in_connected = device_name in inventory_connected() in_mounted = device_name in inventory_mounted() print(device_name + ' is connected', in_connected, sep=': ') print(device_name + ' is mounted', in_mounted, sep=': ') assert not in_connected assert in_mounted
def test_description_absent(self): """ Configure any interface to have no description. Attempt the task exactly once. Restore the original description to the interface. """ for device_name in inventory_connected(): for interface_name in interface_names(device_name): original_info = interface_configuration_tuple( device_name, interface_name) interface_configuration_update(device_name, interface_name, None, original_info.address, original_info.netmask, original_info.active, original_info.shutdown) modified_info = interface_configuration_tuple( device_name, interface_name) self.assertIsNone(modified_info.description) interface_configuration_update(device_name, interface_name, original_info.description, original_info.address, original_info.netmask, original_info.active, original_info.shutdown) return self.fail( "Expected (at least) one connected device with (at least) one interface." )
def inventory_purge(): """ Dismount any mounted network device that is unconnected. """ device_names = set(inventory_mounted()) - set(inventory_connected()) for device in device_names: device_dismount(device)
def test_discover_none(self): self.assertFalse(mounted(unmounted_device_name)) discoveries = capability_discovery(device_name=unmounted_device_name) self.assertFalse(discoveries, "Expected no capabilities for unmounted device.") discoveries = capability_discovery(capability_name=fictional_capability_name) self.assertFalse(discoveries, "Expected to find zero fictional capabilities.") discoveries = capability_discovery(capability_ns=fictional_capability_namespace) self.assertFalse(discoveries, "Expected to find no capabilities for fictional name-space.") discoveries = capability_discovery(capability_revision=fictional_capability_revision) self.assertFalse(discoveries, "Expected to find no capabilities for fictional revision.") device_names = inventory_connected() self.assertTrue(device_names, "Expected at least one connected device.") device_name = device_names[0] discoveries = capability_discovery(device_name=device_name, capability_name=fictional_capability_name) self.assertFalse(discoveries, "Expected to find zero fictional capabilities.") discoveries = capability_discovery(device_name=device_name, capability_ns=fictional_capability_namespace) self.assertFalse(discoveries, "Expected to find no capabilities for fictional name-space.") discoveries = capability_discovery(device_name=device_name, capability_revision=fictional_capability_revision) self.assertFalse(discoveries, "Expected to find no capabilities for fictional revision.")
def draw(): """ Select a device/interface and demonstrate.""" print(plain(doc(interface_configuration))) foundInterface = False G = nx.Graph() for device_name in sorted(inventory_connected()): G.add_node(device_name) print("%s:" % device_name) mgmt_name = management_interface(device_name) for interface_name in sorted(interface_names(device_name)): # Choose interface on 'data plane' not 'control plane'. if interface_name == mgmt_name: continue else: match(device_name, interface_name) foundInterface = True demonstrate(device_name, interface_name) to_interface = interface_configuration(device_name, interface_name)[1].split(" ")[1] print("interface:%s" % to_interface) G.add_edge(device_name, to_interface) if not foundInterface: print("There are no suitable network interfaces for this device.") print(G.nodes()) print(G.edges()) # nx.draw(G) nx.draw_networkx(G, with_labels=True) plt.show()
def link_info(): #def main(): ii = 0 link_info_dic = {} for device_name in inventory_connected(): response = odl_http_get(url_neighbors, {'node-id': device_name}, 'application/json', expected_status_code=(200, 404)) l = json.loads(response.text) container_l = l["cdp"]["nodes"]["node"][0] mgmt_name = management_interface(device_name) if "neighbors" in container_l: neighbors = container_l["neighbors"] # print(json.dumps(neighbors, indent=2)) if "summaries" in neighbors: summary = neighbors["summaries"]["summary"] for device_info in summary: neighbor_id = device_info["device-id"] if neighbor_id == "kcy": neighbor_id = 'iosxrv-1' elif neighbor_id == "lax": neighbor_id = 'iosxrv-2' elif neighbor_id == "min": neighbor_id = 'iosxrv-3' elif neighbor_id == "por": neighbor_id = 'iosxrv-4' elif neighbor_id == "san": neighbor_id = 'iosxrv-5' elif neighbor_id == "sea": neighbor_id = 'iosxrv-6' elif neighbor_id == "sfc": neighbor_id = 'iosxrv-7' else: neighbor_id = 'iosxrv-8' device_interface = device_info["interface-name"] if device_interface in mgmt_name: continue link_info = (device_name, neighbor_id.encode('utf8')) link_info_re = (neighbor_id.encode('utf8'), device_name) jj = 0 flag = 1 while ii > jj: if link_info_dic[jj] == link_info or link_info_dic[ jj] == link_info_re: flag = 0 jj = jj + 1 else: jj = jj + 1 if flag == 1: link_info_dic[ii] = link_info ii = ii + 1 else: jj = 0 # return link_info_set return link_info_dic
def test_interface_names(self): for device_name in inventory_connected(): print('test: interface_names(' + device_name, end=')') interfaces = interface_names(device_name) print(', got:', *interfaces) self.assertGreater( len(interfaces), 1, 'Expected multiple interfaces, got %d' % len(interfaces))
def cdp_get_nei(): for device_name in inventory_connected(): neighbor = cdp_neighbors_json(device_name) Neighbor_link_set[device_name] = neighbor # print(Neighbor_link_set[device_name]) return Neighbor_link_set
def cdp_enable_network(): ''' Description: This function will check every connected device and enable them one by one. ''' for device_name in inventory_connected(): if device_name: cdp_enable_device(device_name)
def main(): ''' Select a device and demonstrate.''' print(plain(doc(interface_names))) mounted_list = inventory_mounted() connected_list = inventory_connected() device_list = list(set(connected_list) & set(mounted_list)) for device_name in device_list: return demonstrate(device_name) print('There are no mounted, connected devices to examine. Demonstration cancelled.')
def topodetect(): ''' Description: This function first will enable cdp of all the connected devices, and then iterate them to set up the topology. ''' cdp_enable_network() for device_name in inventory_connected(): findneighbor(device_name)
def link_info(): # def main(): ii = 0 link_info_dic = {} for device_name in inventory_connected(): response = odl_http_get( url_neighbors, {"node-id": device_name}, "application/json", expected_status_code=(200, 404) ) l = json.loads(response.text) container_l = l["cdp"]["nodes"]["node"][0] mgmt_name = management_interface(device_name) if "neighbors" in container_l: neighbors = container_l["neighbors"] # print(json.dumps(neighbors, indent=2)) if "summaries" in neighbors: summary = neighbors["summaries"]["summary"] for device_info in summary: neighbor_id = device_info["device-id"] if neighbor_id == "kcy": neighbor_id = "iosxrv-1" elif neighbor_id == "lax": neighbor_id = "iosxrv-2" elif neighbor_id == "min": neighbor_id = "iosxrv-3" elif neighbor_id == "por": neighbor_id = "iosxrv-4" elif neighbor_id == "san": neighbor_id = "iosxrv-5" elif neighbor_id == "sea": neighbor_id = "iosxrv-6" elif neighbor_id == "sfc": neighbor_id = "iosxrv-7" else: neighbor_id = "iosxrv-8" device_interface = device_info["interface-name"] if device_interface in mgmt_name: continue link_info = (device_name, neighbor_id.encode("utf8")) link_info_re = (neighbor_id.encode("utf8"), device_name) jj = 0 flag = 1 while ii > jj: if link_info_dic[jj] == link_info or link_info_dic[jj] == link_info_re: flag = 0 jj = jj + 1 else: jj = jj + 1 if flag == 1: link_info_dic[ii] = link_info ii = ii + 1 else: jj = 0 # return link_info_set return link_info_dic
def inventory_connect(time_out=10.0, time_interval=0.2): """ Mount all unmounted devices and wait for the (asynchronous) connection to occur. Parameters: time_out -- Number of seconds to elapse before time out. time_interval -- Initial time interval between checks. Raise: Exception if any connections are not verified during the time allocated. """ unmounted_device_names = set(inventory_unmounted()) if unmounted_device_names: for device_name in unmounted_device_names: mount_from_settings(device_name) time_accum = 0.0 num_checks = 0 while time_accum < time_out: unconnected_device_names = unmounted_device_names - set( inventory_connected()) num_checks += 1 if not unconnected_device_names: print( '%s network device connection(s) verified after %s check(s) and %s seconds.' % (len(unmounted_device_names), num_checks, time_accum)) return else: # Don't hammer the Controller or it will crash. # This not a denial-of-service (DOS) attack ;-) # Print a message explaining the pause, otherwise user might terminate. expanding_interval = time_interval * num_checks time_accum += expanding_interval print( 'sleep(%s) seconds pending connection to %s network device(s).' % (expanding_interval, len(unconnected_device_names))) time.sleep(expanding_interval) unconnected_device_names = unmounted_device_names - set( inventory_connected()) if unconnected_device_names: raise Exception( 'Expected connection after %s check(s) and %s seconds to network device(s): ' % (num_checks, time_accum) + ', '.join(unconnected_device_names))
def main(): ''' Select a device and demonstrate.''' print(plain(doc(interface_names))) mounted_list = inventory_mounted() connected_list = inventory_connected() device_list = list(set(connected_list) & set(mounted_list)) for device_name in device_list: return demonstrate(device_name) print( 'There are no mounted, connected devices to examine. Demonstration cancelled.' )
def main(): ''' Select a device/interface and demonstrate.''' print(plain(doc(interface_configuration_tuple))) for device_name in inventory_connected(): mgmt_name = management_interface(device_name) for interface_name in interface_names(device_name): # Choose interface on 'data plane' not 'control plane'. if interface_name == mgmt_name: continue return demonstrate(device_name, interface_name) print("There are no suitable network devices. Demonstration cancelled.")
def main(): ''' Select a device/interface and demonstrate.''' print(plain(doc(interface_configuration))) for device_name in inventory_connected(): mgmt_name = management_interface(device_name) for interface_name in interface_names(device_name): # Choose interface on 'data plane' not 'control plane'. if interface_name == mgmt_name: continue return demonstrate(device_name, interface_name) print("There are no suitable network devices. Demonstration cancelled.")
def main(): print(plain(doc(interface_configuration_update))) for device_name in inventory_connected(): mgmt_name = management_interface(device_name) for interface_name in interface_names(device_name): # Avoid modifying the management interface. if interface_name == mgmt_name: continue demonstrate(device_name, interface_name) return EX_OK print("There are no suitable network devices. Demonstration cancelled.") return EX_TEMPFAIL
def main(): print(plain(doc(interface_configuration_update))) for device_name in inventory_connected(): mgmt_name = management_interface(device_name) for interface_name in interface_names(device_name): # Avoid modifying the management interface. if interface_name == mgmt_name: continue demonstrate(device_name, interface_name) return os.EX_OK print("There are no suitable network devices. Demonstration cancelled.") return os.EX_TEMPFAIL
def test_interface_configuration_tuple(self): device_names = inventory_connected() self.assertTrue(device_names, "Expected one or more connected devices.") interface_count = 0 for device_name in device_names: for interface_name in interface_names(device_name): info = interface_configuration_tuple(device_name, interface_name) self.assertEqual(info.name, interface_name) self.assertTrue(info.description is None or isinstance(info.description, str)) self.assertTrue(info.address is None or isinstance(info.address, str)) self.assertTrue(info.netmask is None or isinstance(info.netmask, str)) interface_count+=1 self.assertNotEqual(0, interface_count, 'Expected one or more interfaces.')
def sample_interface(): 'Return a tuple of (device_name, interface_name) if possible; otherwise raise LookupError.' for device_name in inventory_connected(): print device_name management_name = management_interface(device_name) print management_name if management_name == None: continue # Uncertain which interface is for management. for interface_name in interface_names(device_name): print interface_name if interface_name == management_name: continue return (device_name, interface_name) raise LookupError("Unable to find a suitable sample device and interface in the inventory.")
def main(): mounted_list = inventory_mounted() if not mounted_list: print('There are no mounted devices to dismount.') else: for device_name in mounted_list: print('device_dismount(' + device_name, end=')\n') device_dismount(device_name) mounted_list = set(mounted_list) sleep_total = 0 remaining_connected = mounted_list & set(inventory_connected()) while remaining_connected: if sleep_total > sleep_interval * 100: print('Time out after %s seconds', sleep_total) return 2 print('Disconnecting', *remaining_connected) sleep(sleep_interval) sleep_total += sleep_interval remaining_connected = mounted_list & set(inventory_connected()) continue print('Dismounted %s device(s), slept for %s seconds' % (len(mounted_list), sleep_total)) return EX_OK return EX_TEMPFAIL
def sample_interface(): 'Return a tuple of (device_name, interface_name) if possible; otherwise raise LookupError.' for device_name in inventory_connected(): print device_name management_name = management_interface(device_name) print management_name if management_name == None: continue # Uncertain which interface is for management. for interface_name in interface_names(device_name): print interface_name if interface_name == management_name: continue return (device_name, interface_name) raise LookupError( "Unable to find a suitable sample device and interface in the inventory." )
def test_description_absent(self): """ Configure any interface to have no description. Attempt the task exactly once. Restore the original description to the interface. """ for device_name in inventory_connected(): for interface_name in interface_names(device_name): original_info = interface_configuration_tuple(device_name, interface_name) interface_configuration_update(device_name, interface_name, None, original_info.address, original_info.netmask, original_info.active, original_info.shutdown) modified_info = interface_configuration_tuple(device_name, interface_name) self.assertIsNone(modified_info.description) interface_configuration_update(device_name, interface_name, original_info.description, original_info.address, original_info.netmask, original_info.active, original_info.shutdown) return self.fail("Expected (at least) one connected device with (at least) one interface.")
def main(): ''' Select a device/interface and demonstrate.''' print(plain(doc(interface_configuration))) foundInterface = False for device_name in sorted(inventory_connected()): print("%s:" % device_name) mgmt_name = management_interface(device_name) for interface_name in sorted(interface_names(device_name)): # Choose interface on 'data plane' not 'control plane'. if interface_name == mgmt_name: continue else: foundInterface = True demonstrate(device_name, interface_name) if not foundInterface: print("There are no suitable network interfaces for this device.")
def main(): """ Select a device/interface and demonstrate.""" print(cleandoc(__doc__)) print() print('Determine which network devices are capable.') device_names = inventory_connected() print_table(device_names, headers='device-name') print() for device_name in device_names: interface_names = demonstrate_all(device_name) if interface_names: demonstrate_one(device_name, interface_names[0]) return EX_OK print("There are no suitable network devices and interfaces. Demonstration cancelled.") return EX_TEMPFAIL
def main(): print(plain(doc(interface_configuration_update))) for device_name in inventory_connected(): mgmt_name = management_interface(device_name) for interface_name in interface_names(device_name): # Choose interface on 'data plane' not 'control plane'. if interface_name == mgmt_name: continue interface_config = interface_configuration(device_name, interface_name) if not interface_config.address: continue if not interface_config.shutdown: continue demonstrate(device_name, interface_config) return os.EX_OK print("There are no suitable network devices/interfaces. Demonstration cancelled.") return os.EX_TEMPFAIL
def main(): """ Select a device/interface and demonstrate.""" print(cleandoc(__doc__)) print() print('Determine which network devices are capable.') device_names = inventory_connected() print_table(device_names, headers='device-name') print() for device_name in device_names: interface_names = demonstrate_all(device_name) if interface_names: demonstrate_one(device_name, interface_names[0]) return EX_OK print( "There are no suitable network devices and interfaces. Demonstration cancelled." ) return EX_TEMPFAIL
def main(): inventory_set = set(inventory()) inventory_connected_set = set(inventory_connected()) inventory_not_connected_set = set(inventory_not_connected()) inventory_mounted_set = set(inventory_mounted()) inventory_unmounted_set = set(inventory_unmounted()) empty_set = set() print("The set of 'connected' devices is a subset of the inventory:", inventory_connected_set <= inventory_set) assert inventory_connected_set <= inventory_set print( "The set of 'not connected' devices is also a subset of the inventory:", inventory_not_connected_set <= inventory_set) assert inventory_not_connected_set <= inventory_set print( "There are no network devices in both the 'connected' set and the 'not connected' set:", inventory_not_connected_set & inventory_connected_set == empty_set) assert inventory_not_connected_set & inventory_connected_set == empty_set print( "Every network device in the inventory is in either the 'connected' set or the 'not connected' set:", inventory_connected_set | inventory_not_connected_set == inventory_set) assert inventory_connected_set | inventory_not_connected_set == inventory_set print() print("The set of 'mounted' devices is a subset of the inventory:", inventory_mounted_set <= inventory_set) assert inventory_mounted_set <= inventory_set print( "The set of 'unmounted' devices has no intersection with the inventory:", inventory_unmounted_set & inventory_set == empty_set) assert inventory_unmounted_set & inventory_set == empty_set, 'Expect no intersection, got %s' % ( inventory_unmounted_set & inventory_set) print( "There are no network devices in both the 'mounted' set and the 'unmounted' set:", inventory_unmounted_set & inventory_mounted_set == empty_set) assert inventory_unmounted_set & inventory_mounted_set == empty_set
def test_interface_configuration_tuple(self): device_names = inventory_connected() self.assertTrue(device_names, "Expected one or more connected devices.") interface_count = 0 for device_name in device_names: for interface_name in interface_names(device_name): info = interface_configuration_tuple(device_name, interface_name) self.assertEqual(info.name, interface_name) self.assertTrue(info.description is None or isinstance(info.description, str)) self.assertTrue(info.address is None or isinstance(info.address, str)) self.assertTrue(info.netmask is None or isinstance(info.netmask, str)) interface_count += 1 self.assertNotEqual(0, interface_count, 'Expected one or more interfaces.')
def match(device_name, interface_network): """ Discover matching interface on a different device.""" for other_device in inventory_connected(): if other_device == device_name: continue for interface_name in interface_names(other_device): interface_config = interface_configuration_tuple(other_device, interface_name) if interface_config.address is None: # Skip network interface with unassigned IP address. continue other_network = to_ip_network(interface_config.address, interface_config.netmask) if other_network == interface_network: print( "Match %s/%s/%s to %s/%s" % (device_name, interface_config.address, interface_config.netmask, other_device, interface_network) ) # return (other_device,interface_config.name) return other_device return None
def main(): inventory_set = set(inventory()) inventory_connected_set = set(inventory_connected()) inventory_not_connected_set = set(inventory_not_connected()) inventory_mounted_set = set(inventory_mounted()) inventory_unmounted_set = set(inventory_unmounted()) empty_set = set() print("The set of 'connected' devices is a subset of the inventory:", inventory_connected_set <= inventory_set) assert inventory_connected_set <= inventory_set print("The set of 'not connected' devices is also a subset of the inventory:", inventory_not_connected_set <= inventory_set) assert inventory_not_connected_set <= inventory_set print("There are no network devices in both the 'connected' set and the 'not connected' set:", inventory_not_connected_set & inventory_connected_set == empty_set) assert inventory_not_connected_set & inventory_connected_set == empty_set print("Every network device in the inventory is in either the 'connected' set or the 'not connected' set:", inventory_connected_set | inventory_not_connected_set == inventory_set) assert inventory_connected_set | inventory_not_connected_set == inventory_set print() print("The set of 'mounted' devices is a subset of the inventory:", inventory_mounted_set <= inventory_set) assert inventory_mounted_set <= inventory_set print("The set of 'unmounted' devices has no intersection with the inventory:", inventory_unmounted_set & inventory_set == empty_set) assert inventory_unmounted_set & inventory_set == empty_set, 'Expect no intersection, got %s' % (inventory_unmounted_set & inventory_set) print("There are no network devices in both the 'mounted' set and the 'unmounted' set:", inventory_unmounted_set & inventory_mounted_set == empty_set) assert inventory_unmounted_set & inventory_mounted_set == empty_set
def test_interface_names(self): device_names = inventory_connected() self.assertTrue(device_names, "Expected one or more connected devices.") for device_name in device_names: interfaces = interface_names(device_name) self.assertGreater(len(interfaces), 1, 'Expected multiple interfaces, got %d' % len(interfaces))
def get_all_devices_loopback(): #def main(): for device_name in inventory_connected(): loopback_container[device_name] = get_loopback(device_name) print(loopback_container)
def cdp_enable_network(): for device_name in inventory_connected(): cdp_enable_device(device_name)
def test_interface_names(self): device_names = inventory_connected() self.assertTrue(device_names, "Expected one or more connected devices.") for device_name in device_names: interfaces = interface_names(device_name) self.assertGreater(len(interfaces), 1, "Expected multiple interfaces, got %d" % len(interfaces))
def main(): global devices devices = sorted(inventory_connected()) global matrix matrix = capability_matrix(devices)
def test_interface_names(self): for device_name in inventory_connected(): print('test: interface_names(' + device_name, end=')') interfaces = interface_names(device_name) print(', got:', *interfaces) self.assertGreater(len(interfaces), 1, 'Expected multiple interfaces, got %d' % len(interfaces))
def main(): print(_doc) print(inventory_connected())
def main(): for device_name in inventory_connected(): for capability_name in capability(device_name): print(device_name, capability_name)
def demonstrate(): cdp_enable_network() for device_name in inventory_connected(): cdp_neighbors_json(device_name)