如何在Python项目中安全存储MySQL数据库连接的敏感凭据
解决方案
你可以通过以下几种方案安全存储数据库敏感参数,同时我也修复了你原有代码中的SQL注入风险:
方案1:使用环境变量存储参数
把数据库连接参数配置到运行环境的系统环境变量中,代码中直接读取环境变量即可,不会在代码中泄露明文参数。
读取环境变量的示例代码:
import os import mysql.connector mac = "你需要查询的mac值" try: # 直接从环境变量读取参数 connection = mysql.connector.connect( host=os.environ.get("MYSQL_HOST"), database=os.environ.get("MYSQL_DB"), user=os.environ.get("MYSQL_USER"), password=os.environ.get("MYSQL_PWD") ) # 修复原有SQL注入风险,使用参数化查询 sql_select_Query = "select * from AuthSys WHERE mac = %s" cursor = connection.cursor() cursor.execute(sql_select_Query, (mac,)) row_headers=[x[0] for x in cursor.description] records = cursor.fetchall() except mysql.connector.Error as e: return [e] finally: if 'connection' in locals() and connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")
Windows和Linux系统都可以自定义设置环境变量,使用脚本的用户没有配置对应环境变量的话无法直接连接数据库,也无法从代码中获取到你的明文权限信息。
方案2:使用本地配置文件+忽略规则
如果不想配置系统环境变量,可以用独立的本地配置文件存储参数,同时把配置文件加入版本控制的忽略列表,避免配置文件被上传到代码仓库泄露。
操作步骤:
- 安装
python-dotenv库:pip install python-dotenv - 在项目根目录新建
.env文件,写入配置内容:
MYSQL_HOST=localhost MYSQL_DB=USER MYSQL_USER=root MYSQL_PWD=password
- 在项目的
.gitignore文件中添加.env规则,确保该文件不会被提交到代码仓库 - 代码中加载配置文件读取参数:
import os import mysql.connector from dotenv import load_dotenv # 加载.env配置文件 load_dotenv() mac = "你需要查询的mac值" try: connection = mysql.connector.connect( host=os.getenv("MYSQL_HOST"), database=os.getenv("MYSQL_DB"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PWD") ) # 参数化查询避免SQL注入 sql_select_Query = "select * from AuthSys WHERE mac = %s" cursor = connection.cursor() cursor.execute(sql_select_Query, (mac,)) row_headers=[x[0] for x in cursor.description] records = cursor.fetchall() except mysql.connector.Error as e: return [e] finally: if 'connection' in locals() and connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")
更高安全等级方案
如果需要更高的安全级别,可以对配置文件内容进行对称加密,运行时通过独立的密钥解密读取参数,密钥不要存储在项目代码中,单独分发即可。
内容的提问来源于stack exchange,提问作者Bijaya Kumar Tiadi
相关产品推荐
相关产品推荐

