如何在Python环境的Jupyter Notebook中隐藏敏感信息?求替代方案
Great question! Storing sensitive information outside your Jupyter working directory is a smart security practice, and besides the external JSON file approach you’re considering, there are several robust alternatives tailored to different use cases:
1. Environment Variables (with or without .env files)
This is one of the most common and portable methods. You can either set variables directly in your system environment, or use a .env file to keep all your secrets organized in one place (without cluttering system-wide variables).
System environment variables:
On Linux/macOS, add this to your~/.bashrcor~/.zshrc:export DB_PASSWORD="your_secret_pass" export PLOTLY_API_KEY="your_plotly_key"On Windows, use the System Properties > Environment Variables UI to add them.
Then in your notebook:
import os db_password = os.getenv("DB_PASSWORD") plotly_key = os.getenv("PLOTLY_API_KEY").envfile +python-dotenv:
Install the package first:pip install python-dotenvCreate a
.envfile outside your Jupyter directory with:DB_PASSWORD="your_secret_pass" PLOTLY_API_KEY="your_plotly_key"Then load it in your notebook:
from dotenv import load_dotenv import os # Load the .env file from the parent directory load_dotenv("../.env") db_password = os.getenv("DB_PASSWORD")
2. INI-style Config Files with configparser
If you prefer a more structured configuration (with sections for different services), use Python’s built-in configparser module with an .ini file.
Create a config.ini file outside your Jupyter folder:
[Database] host = db.example.com password = your_db_secret port = 5432 [Plotly] api_key = your_plotly_key
Then read it in your notebook:
import configparser config = configparser.ConfigParser() config.read("../config.ini") db_password = config["Database"]["password"] plotly_key = config["Plotly"]["api_key"]
3. Jupyter/Ipython Magic Commands (%store)
For temporary or session-specific secrets, you can use IPython’s %store magic to persist variables across notebook sessions without writing files.
In one notebook (or IPython session):
%store db_password "your_secret_pass" %store plotly_key "your_plotly_key"
Then in your working notebook:
%store -r db_password %store -r plotly_key
Note: Stored variables are saved to a local file (~/.ipython/profile_default/db/autorestore) in plaintext, so this is less secure than other methods for long-term storage.
4. Encrypted Configuration Files
If you’re concerned about plaintext config files being exposed, encrypt your secrets file and decrypt it on-the-fly when loading. The cryptography library makes this straightforward.
Install the library:
pip install cryptography
You can write a small helper function to encrypt/decrypt your config (e.g., a JSON or INI file). Here’s a simplified example for encrypting a JSON file:
from cryptography.fernet import Fernet # Generate a key (do this once and store it securely, not in your notebook!) key = Fernet.generate_key() with open("../secret_key.key", "wb") as key_file: key_file.write(key) # Encrypt your config file fernet = Fernet(key) with open("../config.json", "rb") as f: raw_data = f.read() encrypted_data = fernet.encrypt(raw_data) with open("../encrypted_config.json", "wb") as f: f.write(encrypted_data) # Then in your notebook, decrypt and load: with open("../secret_key.key", "rb") as key_file: key = key_file.read() fernet = Fernet(key) with open("../encrypted_config.json", "rb") as f: encrypted_data = f.read() decrypted_data = fernet.decrypt(encrypted_data) # Load the decrypted JSON import json config = json.loads(decrypted_data) db_password = config["db_password"]
Important: Store the encryption key separately from the encrypted config file (e.g., in an environment variable or secure key vault).
5. Managed Secret Services (For Team/Production)
If you’re working in a team or production environment, use a dedicated secret management service to avoid storing secrets locally entirely. Examples include:
- HashiCorp Vault
- AWS Secrets Manager
- Azure Key Vault
These services let you retrieve secrets via API calls, so your notebook only needs authentication credentials (which can themselves be managed via environment variables or IAM roles). For example, with AWS Secrets Manager:
import boto3 client = boto3.client("secretsmanager") response = client.get_secret_value(SecretId="my-db-secrets") secrets = json.loads(response["SecretString"]) db_password = secrets["password"]
Each method has its pros and cons—pick the one that best fits your security needs, workflow, and environment!
内容的提问来源于stack exchange,提问作者João Paulo Leite Nascimento

