如何在Python中安全存储网站登录凭证(避免明文存储)?
安全存储Python登录凭证的实用方案
1. 用系统环境变量
- 把用户名、密码存在系统环境变量里,脚本里通过
os.getenv()读取,完全和代码分离,避免不小心提交到版本控制系统。 - 示例代码:
import os username = os.getenv("WEBSITE_LOGIN_USER") password = os.getenv("WEBSITE_LOGIN_PWD")
- 配置方式:
- Linux/macOS:在终端执行
export WEBSITE_LOGIN_USER=你的账号,或者把这条命令加到~/.bashrc/~/.zshrc里持久化。 - Windows:在命令行执行
set WEBSITE_LOGIN_USER=你的账号,或者通过系统设置添加环境变量。
- Linux/macOS:在终端执行
2. 加密配置文件
- 用加密文件存凭证,脚本运行时解密读取,就算文件泄露,没密钥也拿不到明文。推荐用
cryptography库的Fernet模块: - 步骤:
- 先生成密钥(只跑一次,把密钥存好,别放代码里):
from cryptography.fernet import Fernet key = Fernet.generate_key() print(key.decode()) # 把这个字符串存到环境变量或者本地安全位置
- 加密凭证并写入文件:
from cryptography.fernet import Fernet key = b"刚才生成的密钥字节" fernet = Fernet(key) # 加密账号密码 enc_user = fernet.encrypt(b"你的账号") enc_pwd = fernet.encrypt(b"你的密码") # 写入加密文件 with open("creds.enc", "wb") as f: f.write(enc_user + b"\n" + enc_pwd)
- 脚本里解密读取:
import os from cryptography.fernet import Fernet # 从环境变量取密钥 key = os.getenv("CRED_ENCRYPT_KEY").encode() fernet = Fernet(key) with open("creds.enc", "rb") as f: enc_user, enc_pwd = f.read().split(b"\n") username = fernet.decrypt(enc_user).decode() password = fernet.decrypt(enc_pwd).decode()
3. 用系统密钥管理工具
- 直接用系统自带的安全存储,比如Linux的GNOME Keyring、macOS的Keychain、Windows的凭据管理器,比自己加密更可靠。可以用跨平台的
keyring库操作: - 步骤:
- 安装库:
pip install keyring - 存入凭证(单独跑一次这个脚本):
- 安装库:
import keyring # 第一个参数是服务名称,第二个是账号,第三个是密码 keyring.set_password("我的网站登录", "我的账号", "我的密码")
- 登录脚本里读取:
import keyring username = "我的账号" password = keyring.get_password("我的网站登录", username)
4. 配置文件加严格权限(最低防护)
- 如果用普通的JSON/INI文件存,一定要设置严格的文件权限,比如Linux/macOS下执行
chmod 600 creds.json,只有当前用户能读写。 - 示例(JSON文件):
creds.json内容:
{"username": "你的账号", "password": "你的密码"}
脚本读取:
import json with open("creds.json", "r") as f: creds = json.load(f) username = creds["username"] password = creds["password"]
- 注意:这种方式只适合低风险场景,不如前面几种安全。
内容的提问来源于stack exchange,提问作者Crunchy
相关产品推荐
相关产品推荐

