簡體   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