how to secure mysql connection using python - python

I'm writing python script which uses a mysql db. I want to secure mysql connection and the database will not be accessible to local user . Is there a good way to product this?
#!/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 supports SSL connection like 'https' (secure connection between Web Server and Web Browser). Client code need to be modified for making connection. This makes your data invisible by other user. a client needs to be modified for making secure connection as follows. excerpted from 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()

The standard way to do this is to have the web/application server access the database server over a private (local) network, rather than over a public network (Internet).
If the database server is on the same machine as the web/application server, you can host the database server on the loopback IP address (127.0.0.1), which is only directly accessible from the same machine.

Related

Issue Connecting to GCP SQL with python-mysql: don't want to use a port

`db = MySQLdb.connect(
host = '12.34.567.891',
user = 'root',
passwd = '',
db = 'testdb',
port = "something-that-works")`
Very Simple Can I somehow make it so that it connects only to the ip '12.34.567.891'. Google is forwarding the port to 80 but you can't request port 80 or it ends up in an endless loop.
port=null or port = none will cause and error.
I have no issues connecting from my cli mysql client
Thank you,
I expected to be able to connect to the server no issues if I am able to do so from my cli - I need some way to send the connecting request to the raw IP no port. It may be possible python-mysql can't do this
3306 is the default MySQL port and it seems that you are using MySQL, so that should work. https://cloud.google.com/sql/docs/mysql/connect-overview
You will have an easier time connecting with the Cloud SQL Python Connector a library built purely for connecting to Cloud SQL with Python.
Looks like this:
from google.cloud.sql.connector import Connector
# build connection
def getconn() -> pymysql.connections.Connection:
with Connector() as connector:
conn = connector.connect(
"project:region:instance", # Cloud SQL instance connection name
"pymysql",
user="my-user",
password="my-password",
db="my-db-name"
)
return conn
# create connection pool
pool = sqlalchemy.create_engine(
"mysql+pymysql://",
creator=getconn,
)
# insert statement
insert_stmt = sqlalchemy.text(
"INSERT INTO my_table (id, title) VALUES (:id, :title)",
)
# interact with Cloud SQL database using connection pool
with pool.connect() as db_conn:
# insert into database
db_conn.execute(insert_stmt, id="book1", title="Book One")
# query database
result = db_conn.execute("SELECT * from my_table").fetchall()
# Do something with the results
for row in result:
print(row)

How to connect to MS-SQL server without database name using pyodbc python?

I need to connect to the ms-sql database and then create a new database there using python script.
I have the user credentials for the login. So how to create the connection to the ms-sql server using python.
If you do not have database name then use the connection string as mentioned in the code below. Create a database after connection and use the database finally.
import pyodbc
# if you have user id and password then try with this connection string
connection_string = f"DRIVER={SQL Server};SERVER={server_name};UID={user_id};PWD={password}"
# if using in the local system then use the following connection string
connection_string = f"DRIVER={SQL Server};SERVER={server_name}; Trusted_Connection=True;"
connection= pyodbc.connect(connection_string)
cursor = connection.cursor()
sql_create_database = f"CREATE DATABASE {database_name}"
cursor.execute(sql_create_database)
set_database = f"USE {database_name}"
cursor.execute(set_database)

How to restore MySQL database using Python

I have a sql file generated during database backup process and I want to load all database content from that sql file to a different MySQL database (secondary database).
I have created a python function to load the whole database in that sql file but when I execute the function, I get an error
'str' object is not callable
Below is python script
def load_database_dump_to_secondary_mysql(file_path='db_backup_file.sql'):
query = f'source {file_path}'
try:
connection = mysql_hook.get_conn() # connection to secondary db
cursor = connection.cursor(query)
print('LOAD TO MYSQL COMPLETE')
except Exception as xerror:
print("LOAD ERROR: ", xerror)
NB: mysql_hook is an airflow connector that contains MySQL DB connection info such as Host, user/passwd, Database name. Also, I don't have connection to the primary database, I'm only receiving sql dump file.
What I'm I missing?
source is a client builtin command: https://dev.mysql.com/doc/refman/8.0/en/mysql-commands.html
It's not an SQL query that MySQL's SQL parser understands.
So you can't execute source using cursor.execute(), because that goes directly to the dynamic SQL interface.
You must run it using the MySQL command-line client as a subprocess:
subprocess.run(['mysql', '-e', f'source {file_path}'])
You might need other options to the mysql client, such as user, password, host, etc.
try this
import mysql.connector as m
# database which you want to backup
db = 'geeksforgeeks'
connection = m.connect(host='localhost', user='root',
password='123', database=db)
cursor = connection.cursor()
# Getting all the table names
cursor.execute('SHOW TABLES;')
table_names = []
for record in cursor.fetchall():
table_names.append(record[0])
backup_dbname = db + '_backup'
try:
cursor.execute(f'CREATE DATABASE {backup_dbname}')
except:
pass
cursor.execute(f'USE {backup_dbname}')
for table_name in table_names:
cursor.execute(
f'CREATE TABLE {table_name} SELECT * FROM {db}.{table_name}')

MySQL not responding after I execute SELECT statement

I have a Python code where I am having database statements to establish a database connection and insertion statement. Below is the code which I have written. The program is running correctly but when I open MySQL and run SELECT statement, there is no response from database. It's stuck for a long time.
import MySQLdb
dsn_database = "project"
dsn_hostname = "localhost"
dsn_port = 3306
dsn_uid = "root"
dsn_pwd = "pwd"
conn = MySQLdb.connect(host=dsn_hostname, port=dsn_port, user=dsn_uid, passwd=dsn_pwd, db=dsn_database)
conn.query("""DROP TABLE IF EXISTS cars""")
conn.query("""CREATE TABLE cars(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price INT)""")
conn.query("""INSERT INTO cars VALUES(1,'Audi',52642)""")

MySQLdb: how to connect with phpMyAdmin

I have a LAMP server and then I installed MySQLdb for my Python scripts. Now I can't access the MySQL (from LAMP) from Python scripts because it isn't connecting to the MySQLdb, and also I can't access the MySQLdb with phpMyAdmin with (root root). I got "#2002 Cannot log in to the MySQL server" error. Is it possible to connect to one db with Python and phpMyAdmin?
Here is my Python code, which can't connect to the LAMP MySQL, but can connect to the MySQLdb:
db = MySQLdb.connect(host="localhost", port=3303, user="root", passwd="rootroot", db="test")
cursor = db.cursor()
sql = "CREATE TABLE TT(ID int NOT NULL AUTO_INCREMENT PRIMARY KEY)"
cursor.execute(sql)
db.commit()
db.close()
If you're getting #2002 Cannot log in to the MySQL server when logging in to phpmyadmin, then edit phpmyadmin/config.inc.php file and change:
$cfg['Servers'][$i]['host'] = 'localhost';
to:
$cfg['Servers'][$i]['host'] = '127.0.0.1';
You might want to visit this link:
http://blog.ryantremaine.com/2011/03/2002-cannot-log-in-to-mysql-server.html
UPDATE:
you wud not have configured your php.ini well and so that it cannot connect to mysql server.
Wrong path for the mysql.sock
mysql.sock is the instance of the mysql, so first you have to find where does it place at.
You may find it at "/tmp/mysql.sock" or "/var/mysql/mysql.sock".
Go to your php.ini and make sure the value for "pdo_mysql.default_socket", "mysql.default_socket", "mysqli.default_socket" is the right path.
Then restart your web server and try again.
ELSE
Try this:
Go to config.inc.php and check for the following line:
$cfg['Servers'][$i]['user'] = 'YOUR USER NAME IS HERE';
$cfg['Servers'][$i]['password'] = 'AND YOU PASSWORD IS HERE';
Check whether the user name and password that you gave is present or not

Categories

Resources