我正在编写使用 mysql 数据库的 python 脚本。我想保护 mysql 连接的安全,并且本地用户将无法访问数据库。有没有好的方法来实现这一点?
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","username","password","db")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
cursor.execute("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, userid VARCHAR(30),
activity_id VARCHAR(30), date_time VARCHAR(30), screenshot_filename VARCHAR(255), screenshot_md5 VARCHAR(255), num_clicks INT, num_of_mouse_movements INT, num_pause INT );")
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
最佳答案
MySQL 支持 SSL 连接,如“https”(Web 服务器和 Web 浏览器之间的安全连接)。需要修改客户端代码才能建立连接。这使得其他用户看不到您的数据。需要修改客户端才能建立安全连接,如下所示。摘自http://www.mysqlperformanceblog.com/2013/06/22/setting-up-mysql-ssl-and-secure-connections/
[root@centos6 ~]# cat mysql-ssl.py
#!/usr/bin/env python
import MySQLdb
ssl = {‘cert’: ‘/etc/mysql-ssl/client-cert.pem’, ‘key’: ‘/etc/mysql-ssl/client-key.pem’}
conn = MySQLdb.connect(host=’127.0.0.1′, user=’ssluser’, passwd=’pass’, ssl=ssl)
cursor = conn.cursor()
cursor.execute(‘SHOW STATUS like “Ssl_cipher”‘)
print cursor.fetchone()
关于python - 如何使用 python 保护 mysql 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20324469/