pymysql cannot connect to mysql - python

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.

Related

sqlalchemy not working????..what is the problem here? [duplicate]

I tried to deploy web application on my server and I am getting this mysql database exception
Access denied for user 'root'#'localhost' (using password: YES) (Mysql::Error)
I tried to access the database from the command prompt using mysql -u root -p I am able to do all the database operations.
what is the error
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:771)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3649)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1176)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2558)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:620)
at java.sql.DriverManager.getConnection(DriverManager.java:200)
at com.mpigeon.DbConnection.DbConn(DbConnection.java:26)
at com.mpigeon.CheckLoginHome.doGet(CheckLoginHome.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
You need to grant access to root from localhost. Check this ubuntu help
try using root like..
mysql -uroot
then you can check different user and host after you logged in by using
select user,host,password from mysql.user;
check you are putting blank space in password.
From my answer here, thought this might be useful:
I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:
Step 1: Identify the Database Version
$ mysql --version
You'll see some output like this with MySQL:
$ mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
Or output like this for MariaDB:
mysql Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.
Step 2: Stopping the Database Server
To change the root password, you have to shut down the database server beforehand.
You can do that for MySQL with:
$ sudo systemctl stop mysql
And for MariaDB with:
$ sudo systemctl stop mariadb
Step 3: Restarting the Database Server Without Permission Checking
If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.
To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.
Start the database without loading the grant tables or enabling networking:
$ sudo mysqld_safe --skip-grant-tables --skip-networking &
The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.
Now you can connect to the database as the root user, which should not ask for a password.
$ mysql -u root
You'll immediately see a database shell prompt instead.
MySQL Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
MariaDB Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Now that you have root access, you can change the root password.
Step 4: Changing the Root Password
mysql> FLUSH PRIVILEGES;
Now we can actually change the root password.
For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:
mysql> ALTER USER 'root'#'localhost' IDENTIFIED BY 'new_password';
For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
mysql> SET PASSWORD FOR 'root'#'localhost' = PASSWORD('new_password');
Make sure to replace new_password with your new password of choice.
Note: If the ALTER USER command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET to reset the root password instead.
[IMPORTANT] This is the specific line that fixed my particular issue:
mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
Remember to reload the grant tables after this.
In either case, you should see confirmation that the command has been successfully executed.
Query OK, 0 rows affected (0.00 sec)
The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
Step 5: Restart the Database Server Normally
The tutorial goes into some further steps to restart the database, but the only piece I used was this:
For MySQL, use:
$ sudo systemctl start mysql
For MariaDB, use:
$ sudo systemctl start mariadb
Now you can confirm that the new password has been applied correctly by running:
$ mysql -u root -p
The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.
Conclusion
You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.
I faced the same error after upgrading MySQL server from 5.1.73 to 5.5.45
There is another way to fix that error.
In my case I was able to connect to MySQL using root password but MySQL actively refused to GRANT PRIVILEGES to any user;
Connect to MySQL as root
mysql -u root -p
then enter your MySQL root password;
Select database;
use mysql;
Most probably there is only one record for root in mysql.user table allowing to connect only from localhost (that was in my case) but by the default there should be two records for root, one for localhost and another one for 127.0.0.1;
Create additional record for root user with Host='127.0.0.1' if it's not there;
SET #s = CONCAT('INSERT INTO mysql.user SELECT ',
REPLACE((SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'user' AND TABLE_SCHEMA = 'mysql')
,"Host","'127.0.0.1'"),
' FROM mysql.user WHERE User="root"');
PREPARE stmt FROM #s;
EXECUTE stmt;
Additionally to that you can execute mysql_upgrade -u -p
to see if everything is ok.
This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.
But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:
1) Run with --skip-grant-tables as said above.
If it doesnt works then add the string skip-grant-tables in section [mysqld] of /etc/mysql/mysql.conf.d/mysqld.cnf. Then do sudo service mysql restart.
2) Run mysql -u root -p, then (change "PWD"):
update mysql.user
set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password"
where User='root' and Host='localhost';
flush privileges;
quit
then sudo service mysql restart. Check: mysql -u root -p.
Before restart remove that string from file mysqld.cnf, if you set it there.
#bl79 is the author of this answer, i've just reposted it, because it does help!
My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.
I solved this problem by deleting the empty users creating by MySQL. I only have root user and my own user. I deleted the rest.
Update the empty password in the table mysql.user of mysql
use mysql;
select host,user,password from mysql.user;
update mysql.user set password = PASSWORD('123456') where password = '';
flush privileges;
Update user table in mysql DB. And set some password where it is blank, i was using root user so i set password for root user.
update mysql.user set password = PASSWORD('123456') where password = '';
flush privileges;
And then again tried from ATG CIM by providing password and it worked fine.
http://i.stack.imgur.com/3Lchp.png
I got this problem today while installing SugarCRM (a free CRM).
The system was not able to connect to the database using the root user. I could definitively log in as root from the console... so what was the problem?
I found out that in my situation, I was getting exactly the same error, but that was because the password was sent to mysql directly from the $_POST data, in other words, the < character from my password was sent to mysql as < which means the password was wrong.
Everything else did not help a bit. The list of users in mysql were correct, including the anonymous user (which appears after the root entries.)
I googled a lot but did not find a definite answer to my problem. I used KeyPass to generate a strong password and could use it successfully on mysql workbench to connect but not from the command line. So I changed the psw to an easy one and it worked on the command line. I have managed to create a strong password that was able to connect from the terminal. So my advise is, try with an easy password first before trying all kind of things.
I was running UTs and I started receiving error messages. I am not sure what was the problem. But when I changed my encoding style in INTELLIJ to UTF8 it started working again.
access denied for user 'root'#'localhost' (using password yes)
hibernate
this is my URL
db.url=jdbc:mysql://localhost:3306/somedb?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8&characterEncoding=utf8
Add a user option in msyql.
GRANT PROXY ON ''#'' TO 'root'#'localhost' WITH GRANT OPTION;
and this link will be useful.

"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>

Python MySQLdb can't connect to remote host?

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.

Python Anywhere access denied to MySQL database

I started to use Python Anywhere today. I created the database MySQL following the instructions. The problem is I can't do a simple manage.py syncdb because I get access denied error for my user 'irgmedeiros' in my mysql database. I can't grant privileges to my user neither create another user with privileges. How to solve it? Couldn't find solution in their forum and I'm waiting a answer from email. Anybody experienced this before?
Some possible troubleshooting steps:
check the server address - mysql.server
double-check the password - is it the same as the one you configured on the pythonanywhere MySQL config screens
double-check the database name - this follows the format username$database_name
check if you can open a normal mysql console, firstly from the MySQL tab, and then manually in a bash shell with
.
mysql -u my_username -h mysql.server -p
[edit] - the final solution was:
* double-check the database name - this follows the format username$database_name
don't forget that username$ folks!

Django syncdb error for blog tables

i'm following this tutorial: http://www.programmersbook.com/page/21/Django-Beginner-Tutorial-Part-I/
and I added the database details (running django.db.backends.postgresql_psycopg2) and i added the template dirs. But when i do
./manage.py syncdb
i get:
self.connection = Database.connect(**conn_params)
psycopg2.OperationalError: could not connect to server: Permission denied
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
Any suggestions on how i can fix this please?
Before connecting to database you need to install database server, and configure it for any user to access.
If you want just follow tutorial use SQLite -it's most simple to configure.
Otherwise, install database server of your choose, create database, configure access, make sure that connection details are correct, and/or DB server is up and running.
Best way is try to connect to server via command line.

Categories