Connect on remote MySQL database through Python - python

I have tried the following script but unfortunately doesn't work. I am using a free MySQL database provider. Any ideas?
import MySQLdb
myDB = MySQLdb.connect(host="208.11.220.249",port=3306,user="XXXXX",passwd="XXXXX",db="XXXXX")
cHandler = myDB.cursor()
cHandler.execute("SHOW DATABASES")
results = cHandler.fetchall()
for items in results:
print items[0]
Currently, I am getting the following error:
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1044, "Access denied for user 'XXXXX'#'%' to database 'XXXXX'")

GRANT ALL
ON *.*
TO user#192.168.39.17 -- client ip address
IDENTIFIED BY 'pwd';
Edit
This is SQL that you'd run on the database in order to ensure that the user has access to everything. pwd is the user's password.
Basically, this answer assumes that the connection issue is a credentials issue.

This is what I would do
See if the port is actually open on that machine.
On the machine you are connecting from, open console/cmd/terminal and see if you can connect using mysql -u XXXX -h 208.11.220.249 -p. If your mysql client can not connect, then there is no way you can connect using python

You don't have permission for connecting to database with this user.
Follow these steps:
1.try connecting to mysql DB:
mysql -h208.11.220.249 -uXXXXX -pXXXXX XXXXX
2.If you don't have permission for connecting to DB ,try creating user that has remote permission
GRANT ALL
ON DB.* -- Database name
TO user#ip -- client ip address
IDENTIFIED BY 'pwd';
3.on the last check my.cnf . "bind-address" must be 0.0.0.0 If you want to connect all remote addresses.

open your database in mysql and type the following :
mysql> GRANT ALL ON *.* TO root#'x' IDENTIFIED BY 'Your-password'
where x is the ip address of the user that wants to access your db.
use this link for more information:
How to Allow MySQL Client to Connect to Remote MySQL server

Related

Connecting to CloudSQL from Dataflow in Python

I'm trying to connect to CloudSQL with a python pipeline.
Actual situation
I can do it without any problem using DirectRunner
I can not connect using DataflowRunner
Connection function
def cloudSQL(input):
import pymysql
connection = pymysql.connect(host='<server ip>',
user='...',
password='...',
db='...')
cursor = connection.cursor()
cursor.execute("select ...")
connection.close()
result = cursor.fetchone()
if not (result is None):
yield input
The error
This is the error message using DataflowRunner
OperationalError: (2003, "Can't connect to MySQL server on '<server ip>' (timed out)")
CloudSQL
I have publicIP (to test from local with directrunner) and I have also trying to activating private IP to see if this could be the problem to connect with DataflowRunner
Option2
I have also tried with
connection = pymysql.connect((unix_socket='/cloudsql/' + <INSTANCE_CONNECTION_NAME>,
user='...',
password='...',
db='...')
With the error:
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)")
Take a look at the Cloud SQL Proxy. It will create a local entrypoint (Unix socket or TCP port depending on what you configure) that will proxy and authenticate connections to your Cloud SQL instance.
You would have to mimic the implementation of JdbcIO.read() in Python as explained in this StackOverflow answer
With this solution I was able to access to CloudSQL.
For testing purpose you can add 0.0.0.0/0 to CloudSQL publicIP without using certificates
I created a example using Cloud SQL Proxy inside the Dataflow worker container, connection from the Python pipeline using Unix Sockets without need for SSL or IP authorization.
So the pipeline is able to connect to multiple Cloud SQL instances.
https://github.com/jccatrinck/dataflow-cloud-sql-python
There is a screenshot showing the log output showing the database tables as example.

How to connect to ProxySQL from application

I have Percona XtraDB Cluster running in 3 nodes (node1, node2, node3). I've configured ProxySQL in the 4th node (admin).
I have an python application code trying to access the cluster.
While connecting to 3306 port of node1, I'm able to connect.
import MySQLdb as mdb
db = mdb.connect(host="node1", port=3306,user="root", passwd="*****", db="percona")
In order to achieve load balancing, the application should point to the ProxySQL port 6032.
import MySQLdb as mdb
db = mdb.connect(host="admin", port=6032,user="admin", passwd="*****", db="percona")
While trying to connect, I'm getting the following error:
OperationalError: (1045, "ProxySQL Error: Access denied for user 'admin'#'' (using password: YES)")
I used the grant privilages command in the proxysql
grant all privileges on percona.* to 'admin'#'%' identified by password 'bullet';
Unfortunately, I got the following error,
ERROR 1045 (#2800): near "grant": syntax error
Correct me if I'm wrong.
Should I use some other configuration to connect to the Percona XtraDB Cluster?
Port 6032 is for the administrative CLI.
Instead, you would instead want to connect to port 6033 which listens to all traffic and does load balancing towards the backend PXC nodes.
Good luck!

Remote connection issues with psycopg2 and postgresql

I'm trying to connect to a postgresql database using the following python code:
try:
conn = psycopg2.connect("host = '10.47.65.237' dbname = 'testDB' user = 'pi' password = 'raspberry'")
except:
print("Unable to connect to testDB at 10.47.65.237. Sending Alert.")
This code works with localhost 127.0.0.1 but when I go to a different machine and try to run it with its ip above it won't connect.
Things I've done:
1. Port 5432 is open
2. edited postgresql.conf by adding the line "listen_addresses='10.47.65.138'"
3. edited pg_hba.conf by adding the following configuration "host all all 10.47.65.138 md5"
Any other things I could try or I'm missing?
Running telnet 10.47.65.237 5432 on the client should result in a Connection Refused error, which indicates that the problem has nothing to do with psycopg2.
You have misconfigured the server. listen_addresses controls which IPs the server will answer on, not which IPs the server will permit connections from. Your server's postgresql.conf should have either listen_addresses='10.47.65.237' or listen_addresses='*'. Edit the configuration and restart PostgreSQL on the server, then you should be able to connect successfully using telnet and psycopg2.

python: use 'MySQLdb' module to connect to remote mysql server

I have two virtual machines. One is used as Agent, One is used as Master. A Mysql Server is installed on Master(Mysql Client is forbidden to be installed on Master which means I can't use mysql command line on Master). The Mysql server has a default user 'root'. Now I want to write a python script which use 'MySQLdb' module on Agent. The test code is easy. just see as bellow:
#!/usr/bin/python
import MySQLdb
def main():
try:
conn=MySQLdb.connect(host=master ip,user='root',passwd='xxx',db='xxx',port=3306)
cur=conn.cursor()
count = cur.execute('select * from table')
print count
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
if __name__ == "__main__":
main()
however, when I execute it on Agent, there is an error:
Mysql Error 1045: Access denied for user 'root#Agent ip'(using password: YES)
So I don't know why the user is 'root#Agent ip', not the default user of Mysql server on Master. Anyone knows how to solve this problem?
There is a command named GRANT in MySQL. You have to grant permission for root#AgentIP (Where AgentIP is the IP of the system from which you have to access the db.)
The command to be run in the mysql client of the server:
GRANT ALL on mydb.* to 'root'#'YourIP' identified by 'YourPassword'
Only then the MySQL server running in the remote system will grant access to the database.
If not sure of the IP details, you can also specify 'root'#'%' ,
which will allow all requests from user named root from anywhere. This is not a recommended way, but there is such an option.

Python-PostgreSQL: How to connect database via network IP

For my Django project I am using 'postgresql_psycopg2' and my DB is residing at a common server on the network. How can I connect to that DB using the IP address as 'host' like we do in MySQL? I have tried but it always shows the following error:
OperationalError at /
could not connect to server: Connection refused
Is the server running on host "" and accepting TCP/IP connections on port 5432?
Your problem is not related to Django, you just need to simply put the database server's ip in DATABASES['default']['host'], as you did.
The problem is postgresql denies remote access by default. You have to first edit the pg_hba.conf file on your database server and put a line like this in it:
host db_name user_name 192.168.1.1/32 md5
where you put your target database and user (same as those you enter in django settings) and specify the ip range of the allowed hosts to connect to that database via that user. Then you restart postgresql and now you can remotely connect to the your database. Also check if there isn't any firewall blocking you to access that port on the database server.
For more detailed instructions, see [1] or [2].

Categories