Python MySQLdb can't connect to remote host? - python

I am connecting to another system's MySQL in our local network. This is what I did:
import MySQLdb
db = MySQLdb.connect('192.168.100.30','nvnew','nvnew','disdb')
cur = db.cursor()
This is the error I got:
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '192.168.100.30' (111)")
I have created the user 'nvnew', granted all the privileges, even manually logged in by that user name to test, so i don't know why the error is coming. I searched google and read all the answers still unable to solve this as everywhere, they show this syntax as correct.
I read somewhere to comment the line
bind-address = 127.0.0.1
in /etc/mysql/my.cnf file. I did that but still I am getting the same error. Also, while connecting to remote system's mysql from my system's terminal using.
mysql -h 192.168.100.30 -u nvnew -p
I was unable to get connected to that.
Can you help?

Try to bind it to exact IP 192.168.100.30 (guess, it is static address) instead of commenting
bind-address = 192.168.100.30

Did you restart the remote MySQL daemon after editing the configuration?
(You can use netstat -ltpn to find out if it's listening on 127.0.0.1 or 0.0.0.0.)
Also, be sure you understand the implications of having MySQL bind to all addresses instead of 127.0.0.1 only.

Related

"OperationalError : no password supplied", when linking python and sql [duplicate]

This is probably a silly error but I cannot seem to find a satisfying solution.
When running db.create_all(), I got the following error.
sqlalchemy.exc.OperationalError: (OperationalError) fe_sendauth: no password supplied None None
My database link is set as
'postgresql://localhost/db_name'
This worked fine on my Mac and Heroku, but is not OK on ubuntu (digitalocean).
Any ideas what I might be doing wrong?
You probably just need to remove "localhost" from your connection string:
'postgresql:///db_name'
That tells psycopg2 to use Unix-domain sockets. Your default configuration will use "ident" so you'll be connecting as the user that runs the script. In the default configuration, "md5" only applies to TCP connections.
URL pattern should be:
postgresql://user:password#localhost:5432/database_name
pip install psycopg2
the user should be postgres or any other user you have created and intend to use
similarly for mySql it would be:
mysql://user:pass#localhost:3306/database_name
pip install mysql-python
On your Mac, PostgreSQL was set up for trust or peer authentication for connections from localhost.
On your Ubuntu box it's set up for md5 authentication for connections from localhost.
You'll want to configure a password, or change the authentication mode. See pg_hba.conf, and the Ubuntu guide for PostgreSQL (there's a section about this error).
Below worked for me. Your connection to your postgres database requires a password; thus, below is what you should write..
pg_user = "magicmike"
pg_pwd = "test123"
pg_port = "5432"
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://{username}:{password}#localhost:{port}/foodversity_db".format(username=pg_user, password=pg_pwd, port=pg_port)
First make sure that the database server is connected and then run the command again.Silly, but it worked for me.
For Remote Server
remote server => postgresql://<username>:<password>#<ipaddress>:<port>/<database>
For Local in configuration use
local db => postgressql:///<database>

sqlalchemy engine trying to connect to 127.0.0.1 instead of provided IP

I'm writing here because I can't find any other information on this specific bug.
Whenever I try to connect to my remote DB using
engine = sqlalchemy.create_engine(f'mysql+pymysql://{creds.user}:{creds.dbpassword}#{creds.host}:{creds.port}/{creds.database}')
It tells me:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '127.0.0.1' ([WinError 10061] No connection could be made because the target machine actively refused it)")
(Background on this error at: http://sqlalche.me/e/e3q8)
I explicitly have creds.host set to the IP of the sever as well as I get the same error when I put it directly into the engine. This works on the remote machine under root but does not work for me and it works for a partner who runs the exact same code. Some of the links I found was suggesting to change the bind-address in the mysql config. I uninstalled my local mariadb/mysql server and went and found the config file with bind-address and uncommented it so it was bind-address=0.0.0.0 after a reboot its still not working so I have to think that it is my machine that is not letting me connect to the server.
New info: My partner can no-longer connect through pymysql. I can still connect through datagrip and mysql workbench. The port is open and mysql is listening on port 3306. I have appropriate permissions as I know this because I can connect through datagrip and mysql workbench. I'm thinking this is an us problem and not a server problem but I just don't know why because nothing has changed before the issue started.

pymysql cannot connect to mysql

I am trying to use pymsql to connect to MySQL db, the host is '115.28.236.225', and using the default port: 3306. The code is as bellow (db_connect.py):
import pymysql
def connDB():
conn=pymysql.connect(host='115.28.236.225',user='root',passwd='xxx',db='yyy',charset='utf8', port=3306)
cur=conn.cursor();
return (conn,cur);
conn,cur=connDB()
I use python db_connect.py to run, however, I got the error message pymysql.err.OperationalError: (1045, u"Access denied for user 'root'#'58.196.159.221' (using password: YES)") , I don't know where the host '58.196.159.221' comes from, which does not correspond to the one in the code.
(I have tried to use MySql Workbench to connect to MySQL, and that worked, so, I am sure it must be something wrong with the python code).
How can I solve this? Thanks in advance!
pymysql is awesome because it is a implemented purely in python - no external dependencies.
I'm willing to bet that you don't have the proper permissions set for the root account from external sources.
The reason why you are seeing pymysql.err.OperationalError: (1045,u"Access denied for user 'root'#'58.196.159.221' is because you probably only have access to mysql from 'root'#'localhost', 58.196.159.221 is the IP address of the system your python program is running from - don't believe me? run ifconfig and check your IP address.
fix:
Connect to the mysql console and run the following:
GRANT ALL ON root.* TO 'root'#'58.196.159.221' IDENTIFIED BY 'ENTER_PASSWORD_HERE' ;
FLUSH PRIVILEGES;
This will allow for remote access to mysql.
If you want to only access mysql from the local host you'd run this:
GRANT ALL ON root.* TO 'root'#'localhost' IDENTIFIED BY 'ENTER_PASSWORD_HERE' ;
FLUSH PRIVILEGES;
If you want to grant access from any IP address:
GRANT ALL ON root.* TO 'root'#'%' IDENTIFIED BY 'ENTER_PASSWORD_HERE' ;
FLUSH PRIVILEGES;
FLUSH PRIVILEGES reloads the privileges from the mysql database, which is necessary after you make a change to user permissions.
58.196.159.221 is most likely the address of the client that is running the script. It does not have permission to access your remote database; you will have to configure that in MySQL itself.

SSH Tunnel for Python MySQLdb connection

I tried creating a SSH tunnel using
ssh -L 3306:localhost:22 <hostip>
Then running my python script to connect via localhost
conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test')
However, I receive the following error
(2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
How can I make sure I'm hitting the correct host and not just some problem with the bind?
Try changing "localhost" to "127.0.0.1", it should work as you expect. This behavior is detailed in the manual:
UNIX sockets and named pipes don't
work over a network, so if you specify
a host other than localhost, TCP will
be used, and you can specify an odd
port if you need to (the default port
is 3306):
db=_mysql.connect(host="outhouse", port=3307, passwd="moonpie", db="thangs")
If you really had to, you could
connect to the local host with TCP by
specifying the full host name, or
127.0.0.1.
Does mysqld run on port 22 on the remote? Call me ignorant but I think what you're trying to do is
ssh -n -N -f -L 3306:localhost:3306 remotehost
Then making MySQL connections on local machine will transparently get tunneled over to the target host.
You can't specify localhost as the hostname, as this suggests that MySQLdb should try to use a UNIX socket. Use 127.0.0.1 for the host instead.
If you want to make sure the connection works, you can use the standard mysql client.

Weird MySQL Python mod_wsgi Can't connect to MySQL server on 'localhost' (49) problem

There have been similar questions on StackOverflow about this, but I haven't found quite the same situation. This is on a OS X Leopard machine using MySQL
Some starting information:
MySQL Server version 5.1.30
Apache/2.2.13 (Unix)
Python 2.5.1
mod_wsgi 3
mysqladmin also has skip-networking listed as OFF
I am able to connect to mysql from the python command line. But when I try to do it through mod_wsgi using code that is copy and pasted or via Django I receive the generic connection refusal
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (49)")
I've looked at the mysql manual and tried its troubleshooting tips such as
telnet localhost 3306
and I do get a connection.
I am not trying to connect as root, either.
Any ideas on what else I could check?
Thanks in advance!
I came across this error and it was due to an SELinux denial. /usr/bin/httpd didn't have permission to connect to port 3306. I corrected the issue with:
setsebool httpd_can_network_connect_db on
Seems to work great and should be more secure than just disabling SELinux. As Avinash Meetoo points out below, you can use:
setsebool -P httpd_can_network_connect_db
To make the selinux change persist across reboots.
I was getting the exact same error message in Django:
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (49)")
To fix it, I had to explicitly set the mysql port to 3306 in the django settings file.
Not too much out there on this. Just a random guess but try using:
DATABASE_HOST = 'localhost'
instead of 127.0.0.1
and/or try commenting out in your my.ini:
bind-address 127.0.0.1
worth a shot.
Bit odd that the telnet connection works. Maybe some more ways to trouble shot:
shell> perror 49
OS error code 49: Can't assign requested address
I would check the localhost interface first, check if it has IPv4 address. Far fetched maybe, but I had troubles ones when I didabled IPv6.
shell> ifconfig lo0
Maybe the name resolution doesn't work correctly from within Apache/mod_wsgi/etc..
import python
print socket.gethostbyname('localhost')
print socket.gethostbyaddr('127.0.0.1')
Maybe to get you going (something I contributed to Django) try the UNIX Socket in Django, it works setting the database host to the path (start with forward-slash):
DATABASE_HOST = '/tmp/mysql.sock'
Or where ever your socket file is.
Last, check the MySQL error log if there are any weird messages, like it failing to bind on the IP address or port.
Hope this helps a bit.

Categories