|
/Coding/python:
Using Python to Connect to MySQL Over SSL
Assuming you have already setup your MySQL server to accept external SSL connections[1], with the MySQLdb module and the help of a little documentation[2][3] getting Python to talk to the MySQL server is fairly straightforward:
#!/usr/bin/python import MySQLdb ssl_settings = {'ca': 'db/cacert.pem', 'cert': 'db/cert.pem', 'key': 'db/key.pem' } try: db=MySQLdb.connect(host="www.yoursite.com", user="SSLremote", passwd="yourpassword", db="databasename", ssl=ssl_settings ) except: print " ERROR: could not connect to database." c=db.cursor() c.execute("""SELECT * FROM thistablename""") while True: row = c.fetchone() if row == None: break else: print "
" print row
Point your web browser at this piece of code (you probably have to name it "something.cgi" and put it a folder where your web server is enabled for cgi). This code will connect to the MySQL server and dump the contents of table thistablename into your browser window. If you get "ERROR: could not connect to database." then execute the same code in a terminal on the Python interpreter command line to see the actual MySQL error returned.
Note that the path specification and permissions of the SSL files specified in "ssl_settings" are quite sensitive, as the web server must have access to them. I have stored the files with my code to allow a relative path. For security, these files should be "chmod 600" with the owner set to www-data (or whatever user name your webserver runs under....)
[1] http://blog.langex.net/index.cgi/Admin/MySQL/
[2] http://riskable.com/2009/02/12/how-to-use-ssl-with-the-python-mysqldb-module
[3] http://mysql-python.sourceforge.net/MySQLdb.html
posted at: 23:32 | path: /Coding/python | permanent link to this entry