简体   繁体   中英

Python a secure way to get the database access?

I'm having some doubts about how can I "secure" the database's information to connect. There is someway that I can get the access to the database in a more secure way? A Rest Api? Or if someone can tell me a more secure that sending the access on the code

Thanks in advance

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()

One way is to use an external config file to store the user, password, and other sensitive information.

Then use your operating system's permission system to restrict access to that file such that your application can read the file, but other unprivileged users can not.

Also make sure that you use a SSL connection to the database.

You should also look at authentication plugins.

I'm guessing your question is how to not have to include the DB information (host, port, password, etc.) in the code. I would say the two easiest ways are:

  • Environment variables
  • Separate configuration files

Environment variables

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',
}

Configuration file

import json

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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