将python程序安全地连接到mysql [英] Connecting python program to mysql safely
问题描述
我想使用 MySQLdb 从我的 python 程序连接到 MySQL.
I want to connect to MySQL from my python program using MySQLdb.
我很担心,因为我需要将用户名和密码放在 .py
中才能连接到 MySQL 数据库,以及进入 inno setup.
I am worried because I need to put username and password in the .py
in order to connect to MySQL database, as well into inno setup.
没有人能找到用户名和密码并访问我的数据库吗?我该如何解决这个问题?我是否以某种方式创建了一个访问受限的 sql 用户?(我是 html/css/MySQL 的新手).
Couldn't anybody find the user name and password and get access to my database? How do I solve this problem? Do I make a sql user with limited access somehow? (I am new to html/css/MySQL).
推荐答案
首先,确保您的 MySQL 用户/密码与您的用户名和密码不同.
First, make sure your MySQL user/password is different than your username and password.
接下来,创建一个名为 config.py
的文件,并将其放置在您的 PYTHONPATH 目录中:
Next, make a file called, say, config.py
and place it in a directory in your PYTHONPATH:
USER='zzzzzzzz'
PASS='xxxxxxxx'
HOST='yyyyyyyy'
MYDB='wwwwwwww'
更改文件的权限,以便只有您(和 root)可以读取它.例如,在 Unix 上:
Change the permissions on the file so only you (and root) can read it. For example, on Unix:
chmod 0600 /path/to/config.py
现在,当您使用 MySQLdb
编写脚本时,您会编写
Now, when you write a script using MySQLdb
you'd write
import config
connection = MySQLdb.connect(
host = config.HOST, user = config.USER,
passwd = config.PASS, db = config.MYDB)
因此您的用户名和密码不会出现在您的任何脚本中.
So your username and password will not appear in any of your scripts.
您也可以将 config.py
放在加密目录和/或 U 盘上,这样文件只有在安装驱动器时才能访问.
You could also put config.py
in an encrypted directory, and/or on a USB thumb drive, so the file is only accessible when the drive is mounted.
这篇关于将python程序安全地连接到mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!