def __init__(self, searchstring): """Method initializing the class. Args: searchstring: search string to look for Returns: None """ # Initialize key variables self._search = [] self.config = configuration.Config() # Generate various possible strings that could be used for searches self._search = _search_list(searchstring) # Read ifindex file self.ifindex_data = general.read_yaml_file(self.config.ifindex_file()) # Read host file self.arp_data = general.read_yaml_file(self.config.arp_file()) # Read ifalias file self.ifalias_data = general.read_yaml_file(self.config.ifalias_file())
def __init__(self, config): """Initialize the class. Args: None Returns: None """ # Get configuration mac_address_file = config.mac_address_file() self.oui = {} # Read file with open(mac_address_file, 'r') as csvfile: spamreader = csv.reader(csvfile, delimiter=':') for row in spamreader: mac_address = row[0] manufacturer = row[1] self.oui[mac_address] = manufacturer # Read ARP, RARP tables self.rarp_table = general.read_yaml_file(config.rarp_file()) self.arp_table = general.read_yaml_file(config.arp_file())
def test_read_yaml_file(self): """Testing method / function read_yaml_file.""" # Initializing key variables dict_1 = { 'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, } # Create temp file with known data directory = tempfile.mkdtemp() file_data = [(('{}/file_1.yaml').format(directory), dict_1)] for item in file_data: filename = item[0] data_dict = item[1] with open(filename, 'w') as filehandle: yaml.dump(data_dict, filehandle, default_flow_style=False) # Get Results result = general.read_yaml_file(filename) # Test equivalence for key in result.keys(): self.assertEqual(data_dict[key], result[key]) # Clean up filelist = [ next_file for next_file in os.listdir(directory) if next_file.endswith('.yaml') ] for delete_file in filelist: delete_path = ('{}/{}').format(directory, delete_file) os.remove(delete_path) os.removedirs(directory)
def _idle(): """Add ifindex idle information. Args: None Returns: None """ # Initialize key variables config = CONFIG idle_history = {} # Send log message log_message = ('Evaluating port idle times for devices.') log.log2info(1069, log_message) # Cycle through list of files in directory for filename in os.listdir(config.temp_topology_directory()): # Initialize idle dictionary idle_since = {} # Examine all the '.yaml' files in directory if filename.endswith('.yaml'): devicename = filename[0:-5] # Log message log_message = ( 'Starting port idle times for device {}.'.format(devicename)) log.log2debug(1034, log_message) # Read file and add to string filepath = config.temp_topology_device_file(devicename) device_dict = general.read_yaml_file(filepath) # Get all the status of all the Ethernet ports if 'layer1' in device_dict: for ifindex, data_dict in device_dict['layer1'].items(): if 'jm_ethernet' in data_dict: if data_dict['jm_ethernet'] is True: idle_since[ifindex] = int(time.time()) if data_dict['ifOperStatus'] == 1: if data_dict['ifAdminStatus'] == 1: idle_since[ifindex] = None # Read data from idle file idle_filepath = ('{}/{}.yaml'.format(config.idle_directory(), devicename)) if os.path.isfile(idle_filepath) is True: idle_history = general.read_yaml_file(idle_filepath) # Update idle_since values depending on history for ifindex, timestamp in idle_since.items(): if ifindex in idle_history: # Initialize key variables timestamp_historical = idle_history[ifindex] if bool(timestamp) is False: # Do nothing if the timestamp is None # Interface is operational pass else: if bool(timestamp_historical) is True: # Update history value idle_since[ifindex] = min(timestamp, timestamp_historical) else: # Do nothing. Use current idle_since value pass # Update idle_since file general.create_yaml_file(idle_since, idle_filepath) # Log message log_message = ( 'Completed port idle times for device {}.'.format(devicename)) log.log2debug(1042, log_message) # Send log message log_message = ('Completed port idle times for devices.') log.log2info(1058, log_message)
def data(self): """Return data for the device's ports. Args: None Returns: rows: List of Col objects """ # Initialize key variables rows = [] idle_history = {} config = self.config # Get idle data for device idle_filepath = ('{}/{}.yaml'.format(config.idle_directory(), self.hostname)) if os.path.isfile(idle_filepath) is True: idle_history = general.read_yaml_file(idle_filepath) # Create rows of data for ifindex, port_data in sorted(self.device_data.items()): # Filter results if required if bool(self.ifindexes) is True: if int(port_data['ifIndex']) not in self.ifindexes: continue # Assign values for Ethernet ports only name = port_data['ifName'] label = port_data['ifAlias'] # Get port data port = _Port(port_data) speed = port.speed() inactive = self._inactive(ifindex, idle_history) vlan = port.vlan() state = port.state() duplex = port.duplex() trunk = port.trunk() cdp = port.cdp() lldp = port.lldp() mac_addresses = port.mac_addresses() # Get HTML related to the MAC address html = self.lookup.html(mac_addresses) manufacturer = html['manufacturer'] ip_address = html['ip_address'] hostname = html['hostname'] mac_address = html['mac_address'] # Adjust non-trunk output depending on packet activity if port.is_trunk() is False: if bool(html['mac_address']) is False: if state == 'Active': mac_address = 'Active port. No recent packets.' # Append row of data rows.append( PortRow([ name, vlan, state, inactive, speed, duplex, label, trunk, cdp, lldp, mac_address, manufacturer, ip_address, hostname ])) # Return return rows