Develop a Python script to anonymize sensitive data in a database.
- User
Develop a Python script to anonymize sensitive data in a database.
- Assistant
Develop a Python script to anonymize sensitive data in a database.
Designing an anonymization script
I’m thinking about creating a script, possibly named anonymize.py. First, I’ll import the necessary libraries. Then, I'll define a mapping of anonymization functions. I need to load the config from a YAML file, which consists of database URLs and table mappings that map to strategies. However, since the user asked for just a Python script, they might prefer the code itself without an external config file. I'll aim for a simple self-contained script but include options for JSON/YAML if needed.Creating the configuration and functions
I'm drafting a configuration dictionary for a database connection, which includes the database URL and mappings for various tables, starting with a 'users' table. This structure outlines columns like 'email', 'first_name', 'last_name', and 'phone', each linked to specific anonymization functions.
For instance, the function email_hash_preserve_domain hashes the email while preserving the domain. I’ll also set up Faker functions for generating fake names using a seeded approach to maintain consistency without the threading issues associated with Faker's global seed. For random phones, I’ll generate random digits.Implementing the main logic
I’m setting up the main section of the script by creating an engine using the database URL from the config. I’ll loop through each table in the configuration to extract the necessary parameters like the identifier column and batch size.
Instead of complicated joins or calculations, I’ll opt for a simpler approach using SELECT with OFFSET and LIMIT for iteration in chunks. While this works for demonstration purposes, I realize that for larger tables, performance might suffer. So, using the primary key with a filter on the last seen ID would be the better option.Processing records in batches
I’m thinking about how to implement the batch processing of records. I’ll initialize last_id to track processed entries. In a loop, I’ll execute a SQL statement to select records where the ID is greater than the last processed ID, setting limits for batch size.
If I don’t retrieve any rows, I’ll break the loop. For each row, I’ll apply the corresponding anonymization strategies and prepare updates. Also, it seems best to manage transactions for each batch using engine.begin() within the loop, ensuring I’m not nesting transactions. Each batch will then be processed correctly.Refining the approach
I’m reevaluating the batch processing method. Using a while True loop with a context manager ensures that each chunk is processed with transaction handling. If there are no rows retrieved, it’s fine to break without committing anything.
I’m considering adding a 'dry_run' parameter for safety, even though the user hasn’t asked for it; providing this moderate flexibility seems beneficial. It's also essential to trust the numeric ID format used. Additionally, I’ll emphasize the importance of testing on a non-production copy. The final response will include prerequisites, the full script 'anonymize_db.py', and installation instructions, while ensuring we don't hard-code credentials. I also want to mention the potential for duplicates in email handling, and now I’ll proceed to implement the code! Below is a self-contained example of a Python anonymization script that you can adapt to your database and schema. It:
You will need to adjust:
DATABASE_URL.ANON_CONFIG mapping (tables and columns).pip install sqlalchemy psycopg2-binary faker
# or for MySQL:
# pip install sqlalchemy pymysql faker
anonymize_db.pySet DB connection:
DATABASE_URL directly in the script, orexport DATABASE_URL="postgresql+psycopg2://user:pass@host:5432/mydb"
Define which columns to anonymize:
ANON_CONFIG:
"id_column": primary key column (numeric works best)."columns": mapping column_name -> strategy_name.Example:
"orders": {
"id_column": "order_id",
"batch_size": 2000,
"columns": {
"billing_address": "fake_address",
"shipping_address": "fake_address",
"customer_email": "email_hash_preserve_domain",
},
},
Choose / extend strategies:
email_hash_preserve_domainfake_first_name, fake_last_name, fake_full_name, fake_addressrandom_phone, random_stringhash_valuenullSTRATEGIES.Run:
python anonymize_db.py --dry-run
python anonymize_db.py
hash_value, random_*, or null-based strategies over deterministic Faker-based pseudonyms.If you share your DB type (PostgreSQL/MySQL/etc.) and which tables/columns contain sensitive data, I can tailor the script exactly to your schema.
#!/usr/bin/env python3
"""
Generic database anonymization script.
- Configure DATABASE_URL and ANON_CONFIG below.
- Run on a COPY of your production database first.
"""
import os
import hashlib
import random
import string
from typing import Any, Callable, Dict
from sqlalchemy import create_engine, text
from sqlalchemy.engine import Engine
from faker import Faker
# ---------------------------------------------------------------------------
# CONFIGURATION
# ---------------------------------------------------------------------------
# Prefer environment variable for security; fallback to placeholder
DATABASE_URL = os.environ.get(
"DATABASE_URL",
"postgresql+psycopg2://user:password@localhost:5432/mydb",
# Examples:
# "postgresql+psycopg2://user:pass@host/dbname"
# "mysql+pymysql://user:pass@host/dbname"
# "mssql+pyodbc://user:pass@dsn"
)
# Which tables/columns to anonymize and how
# Strategy names must exist in STRATEGIES dictionary below.
ANON_CONFIG: Dict[str, Dict[str, Any]] = {
"users": {
"id_column": "id",
"batch_size": 1000,
"columns": {
"email": "email_hash_preserve_domain",
"first_name": "fake_first_name",
"last_name": "fake_last_name",
"phone": "random_phone",
},
},
"customers": {
"id_column": "customer_id",
"batch_size": 1000,
"columns": {
"email": "email_hash_preserve_domain",
"full_name": "fake_full_name",
"address": "fake_address",
},
},
# Add more tables here...
}
# ---------------------------------------------------------------------------
# ANONYMIZATION STRATEGIES
# ---------------------------------------------------------------------------
faker = Faker()
def _deterministic_seed(value: str) -> int:
"""Derive a deterministic seed from a string."""
if value is None:
return 0
h = hashlib.sha256(str(value).encode("utf-8")).hexdigest()
return int(h[:8], 16) # 32-bit seed
def email_hash_preserve_domain(value: Any) -> Any:
"""Hash email local-part; preserve domain when available."""
if not value:
return value
value = str(value)
local, _, domain = value.partition("@")
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:10]
if domain:
return f"user_{digest}@{domain}"
else:
# Fallback domain if original missing/invalid
return f"user_{digest}@example.com"
def fake_first_name(value: Any) -> Any:
"""Deterministic fake first name based on original value."""
if value is None:
return value
seed = _deterministic_seed(str(value))
f = Faker()
f.seed_instance(seed)
return f.first_name()
def fake_last_name(value: Any) -> Any:
"""Deterministic fake last name based on original value."""
if value is None:
return value
seed = _deterministic_seed(str(value))
f = Faker()
f.seed_instance(seed)
return f.last_name()
def fake_full_name(value: Any) -> Any:
"""Deterministic fake full name based on original value."""
if value is None:
return value
seed = _deterministic_seed(str(value))
f = Faker()
f.seed_instance(seed)
return f.name()
def fake_address(value: Any) -> Any:
"""Deterministic fake address based on original value."""
if value is None:
return value
seed = _deterministic_seed(str(value))
f = Faker()
f.seed_instance(seed)
return f.address().replace("\n", ", ")
def random_phone(value: Any) -> Any:
"""Non-deterministic random phone number (irreversible)."""
# You can customize this format to match local conventions.
return f"+1-{random.randint(200, 999)}-{random.randint(200, 999)}-{random.randint(1000, 9999)}"
def random_string(value: Any, length: int = 10) -> Any:
"""Random alphanumeric string (irreversible)."""
chars = string.ascii_letters + string.digits
return "".join(random.choice(chars) for _ in range(length))
def hash_value(value: Any) -> Any:
"""Generic irreversible hash (hex)."""
if value is None:
return value
return hashlib.sha256(str(value).encode("utf-8")).hexdigest()
def null_value(value: Any) -> Any:
"""Set sensitive field to NULL."""
return None
# Map strategy name -> function
STRATEGIES: Dict[str, Callable[[Any], Any]] = {
"email_hash_preserve_domain": email_hash_preserve_domain,
"fake_first_name": fake_first_name,
"fake_last_name": fake_last_name,
"fake_full_name": fake_full_name,
"fake_address": fake_address,
"random_phone": random_phone,
"random_string": random_string,
"hash_value": hash_value,
"null": null_value,
}
# ---------------------------------------------------------------------------
# CORE LOGIC
# ---------------------------------------------------------------------------
def get_engine() -> Engine:
return create_engine(DATABASE_URL)
def anonymize_table(engine: Engine, table_name: str, cfg: Dict[str, Any], dry_run: bool = False) -> None:
id_col = cfg.get("id_column", "id")
batch_size = cfg.get("batch_size", 1000)
col_strategies: Dict[str, str] = cfg["columns"]
columns = list(col_strategies.keys())
select_cols = [id_col] + columns
last_id = None
total_updated = 0
while True:
with engine.begin() as conn:
if last_id is None:
select_sql = text(
f"SELECT {', '.join(select_cols)} "
f"FROM {table_name} "
f"ORDER BY {id_col} ASC "
f"LIMIT :limit"
)
params = {"limit": batch_size}
else:
select_sql = text(
f"SELECT {', '.join(select_cols)} "
f"FROM {table_name} "
f"WHERE {id_col} > :last_id "
f"ORDER BY {id_col} ASC "
f"LIMIT :limit"
)
params = {"last_id": last_id, "limit": batch_size}
rows = conn.execute(select_sql, params).mappings().all()
if not rows:
break
for row in rows:
row_id = row[id_col]
updates = {}
for col, strategy_name in col_strategies.items():
if strategy_name not in STRATEGIES:
raise ValueError(f"Unknown strategy '{strategy_name}' for {table_name}.{col}")
func = STRATEGIES[strategy_name]
orig_value = row[col]
# Some strategies might take additional args; adapt if needed.
new_value = func(orig_value)
updates[col] = new_value
if not dry_run:
set_clause = ", ".join(f"{col} = :{col}" for col in updates.keys())
update_sql = text(
f"UPDATE {table_name} "
f"SET {set_clause} "
f"WHERE {id_col} = :_id"
)
params = updates.copy()
params["_id"] = row_id
conn.execute(update_sql, params)
total_updated += 1
last_id = row_id
# End of batch: transaction auto-committed by context manager
print(f"Table '{table_name}': anonymized {total_updated} rows{' (dry run)' if dry_run else ''}.")
def anonymize_database(dry_run: bool = False) -> None:
engine = get_engine()
for table_name, cfg in ANON_CONFIG.items():
anonymize_table(engine, table_name, cfg, dry_run=dry_run)
# ---------------------------------------------------------------------------
# ENTRY POINT
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Anonymize sensitive data in a database.")
parser.add_argument(
"--dry-run",
action="store_true",
help="Do not write changes, just simulate.",
)
args = parser.parse_args()
# SAFETY NOTICE
print("WARNING: Always run this script against a backup or non-production copy first.")
print(f"Database URL: {DATABASE_URL}")
if args.dry_run:
print("Running in DRY RUN mode (no changes will be written).")
anonymize_database(dry_run=args.dry_run)