python - 如何使用 python 保护 mysql 连接

标签 python mysql security

我正在编写使用 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/

相关文章:

python - 在 Tensorflow 中使用字符串标签

python - 如何检测字典中的任何元素是否发生变化?

python - 在没有 pygame 的情况下监听按键、按键和按键释放事件的最佳方式是什么

mysql - Protractor :sql 查询中的 webdriverjs 命令看不到元素

mysql将数据从一个模式插入到另一个模式

python - 如何读取 Databricks 中的 Azure CosmosDb 集合并写入 Spark DataFrame

c# - 使用 LINQ 进行两个查询的完全外部联接的更好方法? C#

java - jbpm 6.1 中围绕运行时引擎的安全问题?

java - Spring 全局方法安全性和 Aspectj

java - HashLoginService 和 Jetty9