繁体   English   中英

Python是获取数据库访问权限的安全方法?

[英]Python a secure way to get the database access?

我对如何“保护”数据库信息进行连接有一些疑问。 有某种方式可以使我以更安全的方式访问数据库吗? 休息的阿皮? 或者,如果有人可以告诉我更安全的方法,那就发送代码访问权限

提前致谢

config = {
    'user': 'user',
    'password': 'password.',
    'host': 'localhost',
    'database': 'files_to_check',
    'raise_on_warnings': True,
}

try:
    # Try to connect to database
    cnx = mysql.connector.connect(**config)


    # Pointer of the sql
    cursor = cnx.cursor()

    # Query to get the files from the database
    query = ("SELECT filename FROM filenames")
    queryhash = ("SELECT hash FROM filenames")

    # Execute the query
    cursor.execute(query)

    # select all the filenames from database
    # array to fill with the files from the database
    files_to_check = [str(row[0]) for row in cursor.fetchall()]
    cursor.close()

    cursor = cnx.cursor()
    cursor.execute(queryhash)
    # array to fill with the hash from the database
    hash_to_check = [str(row[0]) for row in cursor.fetchall()]

# Error definition on connection
except mysql.connector.Error as err:
    # Check username and password
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("[*] Username or password are invalid")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        # Check if database that are connection exists
        print("[*] Database does not exist")
    else:
        print(err)
else:
    cnx.close()

一种方法是使用外部配置文件存储用户,密码和其他敏感信息。

然后,使用操作系统的权限系统来限制对该文件的访问,以使您的应用程序可以读取该文件,而其他非特权用户则不能。

还要确保您使用与数据库的SSL连接。

您还应该查看身份验证插件。

我猜您的问题是,如何在代码中不必包含数据库信息(主机,端口,密码等)。 我会说两种最简单的方法是:

  • 环境变量
  • 单独的配置文件

环境变量

import os

config = {
    'user': os.getenv('DB_USER'),
    'password': os.getenv('DB_PASSWORD'),
    'host': os.getenv('DB_HOST'),
    'database': os.getenv('DB_DATABASE'),
    'raise_on_warnings': os.getenv('DB_DATABASE', 'true') == 'true',
}

配置文件

import json

with open('config.json') as file:
    config = json.load(file)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM