【问题标题】:how to secure mysql connection using python如何使用python保护mysql连接
【发布时间】:2013-12-02 09:08:54
【问题描述】:

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

【问题讨论】:

    标签: python mysql security


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      执行此操作的标准方法是让 Web/应用程序服务器通过专用(本地)网络访问数据库服务器,而不是通过公共网络(Internet)。

      如果数据库服务器与 Web/应用程序服务器在同一台机器上,您可以将数据库服务器托管在环回 IP 地址 (127.0.0.1) 上,该地址只能从同一台机器直接访问。

      【讨论】:

        猜你喜欢
        • 2012-02-18
        • 1970-01-01
        • 1970-01-01
        • 2014-09-20
        • 2015-08-18
        • 1970-01-01
        • 2013-01-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多