Find and read the file using Python

The following python script reads mongod.conf file and returns some settings.


import sys
import yaml
import json

def read_mongodb_conf(file_path):
    # Define the settings we're interested in reading from mongod.conf
    # If a setting is not set or commented out, then "Not Set" is displayed
    settings = [
        "net.bindIp", "net.tls.mode","replication.replSetName", "replication.oplogSizeMB", "net.port",
        "security.authorization", "security.keyFile", "storage.dbPath", "systemLog.path", "systemLog.logAppend",
        "storage.engine", "storage.journal.enabled", "storage.journal.commitIntervalMs",
        "operationProfiling.mode", "operationProfiling.slowOpThresholdMs", "operationProfiling.slowOpSampleRate",
        "storage.wiredTiger.engineConfig.cacheSizeGB", "storage.wiredTiger.engineConfig.directoryForIndexes"
    ]

    # Initialize a dictionary with "Not Set" as default for all settings and empty comments
    # These will be updated with the actual values, if they exist
    values = {setting: "Not Set" for setting in settings}

    try:
        # Open the file and load the YAML data
        with open(file_path, 'r') as file:
            config = yaml.safe_load(file)
            
            # Loop through the settings in the file
            for setting in settings:
                keys = setting.split('.')
                value = config
                
                # Navigate through the nested keys
                for key in keys:
                    if key in value:
                        value = value[key]
                    else:
                        value = None
                        break
                # If the value is not None, then update the dictionary
                # with the actual value.
                if value is not None:
                    values[setting] = value
    # Handle exceptions
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
        return
    except yaml.YAMLError:
        print(f"Error: Invalid YAML format in '{file_path}'.")
        return

    return values

if __name__ == "__main__":
    # Set the default path to the MongoDB configuration file
    # and the output file.
    default_path = "/etc/mongod.conf"
    output_file = "/tmp/mongoverification.json"
    
    # If the user passes -h or --help, then display the help message
    if len(sys.argv) == 2 and sys.argv[1] in ["-h", "--help"]:
        print("Usage: python script_name.py [path_to_mongod.conf]")
        print(f"Default path if not specified: {default_path}")
        print("Example: python script_name.py /path/to/your/mongod.conf")
    else:
        file_path = sys.argv[1] if len(sys.argv) > 1 else default_path
        values = read_mongodb_conf(file_path)

        if values:
            # Output to the console
            print("{:<30} | {}".format("Setting", "Current Value"))
            print("-" * 65)
            for setting, value in values.items():
                print("{:<30} | {}".format(setting, value))

            # Append the results to the file in JSON format
            with open(output_file, 'a') as json_file:
                json.dump(values, json_file, indent=4)
                json_file.write('\n')  # Separate entries by a newline

            print(f"\nResults appended to: {output_file}")

By Rudy