1. import re
  2. import sys
  3. def extract_tokens(log_line):
  4. """Extracts authentication tokens from a log line using regex."""
  5. # Define a regex pattern to match common token formats. Adjust as needed.
  6. token_pattern = r"Bearer ([\w-]+)" # Example: "Bearer <token>"
  7. match = re.search(token_pattern, log_line)
  8. if match:
  9. return match.group(1) # Return the token value
  10. else:
  11. return None
  12. def monitor_tokens(log_file):
  13. """Reads a log file and extracts authentication tokens."""
  14. try:
  15. with open(log_file, 'r') as f:
  16. for line in f:
  17. token = extract_tokens(line)
  18. if token:
  19. print(token) # Output the token. Can be modified to store/process.
  20. except FileNotFoundError:
  21. print(f"Error: Log file '{log_file}' not found.")
  22. sys.exit(1)
  23. except Exception as e:
  24. print(f"An error occurred: {e}")
  25. sys.exit(1)
  26. if __name__ == "__main__":
  27. if len(sys.argv) != 2:
  28. print("Usage: python token_extractor.py <log_file>")
  29. sys.exit(1)
  30. log_file = sys.argv[1]
  31. monitor_tokens(log_file)

Add your comment