フラットログファイルから重要なデータをマスクするPythonスクリプトの作成

フラットログファイルから重要なデータをマスクするPythonスクリプトの作成

フラットログファイルのすべての種類の機密データ(ユーザー名、パスワード、APIキー、データベース接続文字列、エンドポイント、秘密、秘密を含むカスタム変数まで)をマスクしたいです。

現在使用中のスクリプトは次のとおりです。

import re

def mask_secrets(log_file):
    # Read the log file
    with open(log_file, 'r') as file:
        log_data = file.read()

    # Define the pattern to search for sensitive data
    pattern = r'\b(\w+)\b:\s*(\w+)'

    # Mask the sensitive data in the log data
    log_data = re.sub(pattern, r'\1: ********', log_data)

    # Write the masked log data back to the file
    with open(log_file, 'w') as file:
        file.write(log_data)

# Usage example
log_file = 'path/to/your/log/file.txt'
mask_secrets(log_file)

ただし、タイムスタンプの時間フィールドをマスクし、データベース接続文字列、データベースパスワード、およびシークレットを含むカスタム変数など、一部のシークレットはマスクしません。

2022-01-01 12: ********:00 - User login successful - username: ********.doe, password: ********
2022-01-02 09: ********:15 - API request made - endpoint: /api/data, api_key: ********
2022-01-03 14: ********:22 - User login failed - username: ********.smith, password: ********
2022-01-04 18: ********:10 - API request made - endpoint: /api/data, api_key: ********
2022-01-06 17: ********:22 - DB Connection failed - DB String=guad8b237d7$vu87s, DB password=isbdihkaw978vw8a783wgfb
2022-01-07 19: ********:10 - API request made - endpoint: /api/data, api_key= xyz789s87dv7ghs
2022-01-07 19: ********:10 - User login failed - foo=uyai6d3ibdqi%*^^@%, bar=862479dhb7656%^&^%%^))_=

このスクリプトで使用される正規表現はそれに応じて変更する必要があります。理想的には、右側のすべての値をマスクしたいと思います=。これは可能ですか?

ベストアンサー1

おすすめ記事