1. import re
  2. def flag_config_anomalies(config_file, anomaly_patterns):
  3. """
  4. Flags potential anomalies in a configuration file.
  5. Args:
  6. config_file (str): Path to the configuration file.
  7. anomaly_patterns (dict): A dictionary where keys are anomaly names
  8. and values are regular expression patterns.
  9. Returns:
  10. list: A list of flagged anomalies with their line numbers. Empty list if no anomalies found.
  11. """
  12. flagged_anomalies = []
  13. try:
  14. with open(config_file, 'r') as f:
  15. lines = f.readlines()
  16. except FileNotFoundError:
  17. print(f"Error: File not found: {config_file}")
  18. return []
  19. for i, line in enumerate(lines):
  20. for anomaly_name, pattern in anomaly_patterns.items():
  21. if re.search(pattern, line):
  22. flagged_anomalies.append({"anomaly": anomaly_name, "line": i + 1, "line_content": line.strip()})
  23. return flagged_anomalies
  24. if __name__ == '__main__':
  25. # Example usage:
  26. anomaly_patterns = {
  27. "HardcodedPassword": r"password=.*", # Look for lines containing "password="
  28. "UnusualPort": r"port=(\d{3}(?!\s*:\d+))", #Look for port values that do not have a colon after it
  29. "MissingSecurity": r"security=.*comment" #look for security settings with a comment
  30. }
  31. config_file = "config.txt" # Replace with your config file
  32. # Create a sample config file for testing
  33. with open(config_file, 'w') as f:
  34. f.write("database_url = localhost\n")
  35. f.write("port=8080\n")
  36. f.write("password=secret\n")
  37. f.write("#Security settings\n")
  38. f.write("security=some_value #comment\n")
  39. f.write("another_setting = value\n")
  40. anomalies = flag_config_anomalies(config_file, anomaly_patterns)
  41. if anomalies:
  42. print("Anomalies found:")
  43. for anomaly in anomalies:
  44. print(f" Anomaly: {anomaly['anomaly']}, Line: {anomaly['line']}, Content: {anomaly['line_content']}")
  45. else:
  46. print("No anomalies found.")

Add your comment