import webapp2
import MySQLdb
import os
class MainPage(webapp2.RequestHandler):
def get(self):
if (os.getenv('SERVER_SOFTWARE') and
os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
db = MySQLdb.connect(unix_socket='/cloudsql/fluent-outlet-604:test-db' , db='guestbook', user='root',passwd='root')
# connect to the cloud SQL
else:
db = MySQLdb.connect(host='173.194.248.221', port=3306, db='guestbook', user='root',passwd='root')
cursor = db.cursor()
cursor.execute('SELECT guestName, content, entryID FROM entries')
data = cursor.fetchall()
db.close()
self.response.write(data)
application = webapp2.WSGIApplication([
('/',MainPage),
],debug=True)
when i deploy this app to the app engine i gain error says
"(1045, "Access denied for user 'root'#'localhost' (using password: YES)")
I had the same problem, and solved it.
This problem is on Google Cloud SQL.
In the prompt console, re-start Cloud SQL like below,
gcloud sql instances --project [app engine project name] restart [sql instance name]
You should not specify the root password (even if you have set), when connecting from AppEngine.
Remove the passwd param from line 9 of your code so that it looks like:
db = MySQLdb.connect(unix_socket='/cloudsql/fluent-outlet-604:test-db' , db='guestbook', user='root')
The example code in this article also shows this.
I saw this problem when I didn't specify the hostname in the database URI:
SQLALCHEMY_DATABASE_URI = (
'mysql+pymysql://<user-name>:<password>#/<database-name>'
'?unix_socket=/cloudsql/<connection_name>'
Changing it to the following fixed it:
SQLALCHEMY_DATABASE_URI = (
'mysql+pymysql://<user-name>:<password>#<host-name>/<database-name>'
'?unix_socket=/cloudsql/{connection_name}'
Related
I enabled SSL in a MySQL Cloud SQL instance. In order to connect to the instance , I downloaded the necessary certficates and can connect fine using mysql command. The CloudSQL instance is running with Private IP on a sharedVPC network .
$ mysql -h 192.168.0.3 --ssl-ca=server-ca.pem --ssl-cert=client-cert.pem --ssl-key=client-key.pem -u testuser -p
Enter password:
Now to test connectivity from a code to connect to SQL instance I deployed the following in Cloud Functions
import pymysql
from sqlalchemy import create_engine
def sql_connect(request):
engine = create_engine('mysql+pymysql://testuser:<password>#192.168.0.3/mysql',echo=True)
tab = engine.execute('show databases;')
return str([t[0] for t in tab])
It shows "Access Denied" error as shown below
Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging Details:
(pymysql.err.OperationalError) (1045, "Access denied for testuser'#'192.168.60.4' (using password: YES)")
When I disable SSL it works fine as shown below
['information_schema', 'mysql', 'performance_schema', 'sys', 'testdb']
A) To enable SSL in code I did the following
ssl_args = {'sslrootcert':'server-ca.pem','sslcert':'client-cert.pem','sslkey':'client-key.pem'}
engine = create_engine('mysql+pymysql://testuser:<password>#192.168.0.3/mysql',echo=True,connect_args=ssl_args)
but it is failing with below error
__init__() got an unexpected keyword argument 'sslrootcert'
B) Also tried disabling ssl=False in code but it is failing with below error
Invalid argument(s) 'ssl' sent to create_engine(), using configuration MySQLDialect_pymysql/QueuePool/Engine
UPDATE:
Changed the code for SSL as follows:
ssl_args = {'ssl': {'ca':'./server-ca.pem', 'cert':'./client-cert.pem', 'key':'./client-key.pem'}}
Uploaded the certs to cloud function source
Added 0.0.0.0/0 as authorized networks in CloudSQL to allow connecting from Cloud functions
Now seeing the following error
"Can't connect to MySQL server on 'X.X.X.181' ([SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for 'X.X.X.181'. (_ssl.c:1091))") . However can connect using the same certificates using `mysql` command
Need help to resolve both A) fixing the error as observed so that the code is integrated with SSL and B) Modify code so that it does not uses SSL
Use ssl_ca for the root, ssl_cert for the cert and ssl_key for the key
ssl_args = {'ssl_ca':'server-ca.pem','ssl_cert':'client-cert.pem','ssl_key':'client-key.pem'}
engine = create_engine('mysql+pymysql://testuser:<password>#192.168.0.3/mysql',echo=True,connect_args=ssl_args)
Use SSL parameter in the form ssl = {"ssl":{"ca":"server-ca.pem"}} within the connect function
from pymysql import connect
from sqlalchemy import create_engine
import os
SQLALCHEMY_DATABASE_URI='mysql+pymysql://testuser:<password>#192.168.0.3/mysql?ssl_ca=server-ca.pem'
engine = create_engine(SQLALCHEMY_DATABASE_URI)
args, kwargs = engine.dialect.create_connect_args(engine.url)
# Create connection to the DB
db_conn = connect(kwargs["host"], kwargs["user"], kwargs["passwd"], kwargs["db"], ssl = {"ssl":{"ca":kwargs["ssl"]["ca"]}})
cursor = db_conn.cursor()
# Execute query
cursor.execute("show tables")
cursor.fetchall()
I'm developing a script in RStudio which connects to local MySQL Server using the R package RMariaDB (not RMySQL - for other reasons though the outcome is the same).
I can both connect via storing the password in the script like:
localuserpassword <- "password"
all_projectsDb <- dbConnect(RMariaDB::MariaDB(), user='user', password=localuserpassword, dbname='projects', host='localhost')
or by way of a .my.cnf using credentials:
[client]
[mygroup]
host=127.0.0.1
user=user
password=password
port=3306
database=projects
and R code as
settingsfile = '/Users/oscar_w/.my.cnf'
all_projectsDb <- dbConnect(RMariaDB::MariaDB(), default.file = settingsfile, group="mygroup", dbname = 'projects')
The above work just fine but if I want to connect with .mylogin.cnf created in mysql_config_editor and looks like
[client]
[mygroup]
user = user
password = *****
host = 127.0.0.1
port = 3306
with the R script code like
# define location of config file
settingsfile = '/Users/oscar_w/.mylogin.cnf'
all_projectsDb <- dbConnect(RMariaDB::MariaDB(), default.file = settingsfile, group="mygroup", dbname = 'projects', password = NULL, user = NULL)
I get the error
Error: Failed to connect: Access denied for user 'root'#'localhost' (using password: NO)
I have tried various combinations of arguments expressing null or otherwise. And have entered my password with mysql_config_editor with double quotes around it. In https://cran.r-project.org/web/packages/RMariaDB/RMariaDB.pdf it specifies the use of .mylogin.cnf but I cannot find a way to make it work. Does anyone know a solution to this or has the same issue? Thanks
It looks like you're trying to log in both with and without a password, which isn't allowed. The RMariaDB documentation says that if the password argument is NULL or omitted, only users without a password can log in.
I can connect to mysql using cli like this:
mysql -u cwaugh -p******** -h example.com mydb
However, when I try to use python3 with the same parameters, I get an error: mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'cwaugh'#'xxx.xxx.xxx.xxx' (with my ip where the x should be)
My code for python looks like this:
import mysql.connector
import datetime
thinknode = mysql.connector.connect(
host = "example.com",
user = "cwaugh",
passwd = "********",
db = "mydb")
The credentials also work in javascript, but only if I used ssl: "Amazon RDS" when I created the connection (the database is on AWS RDS).
What do I need to do to connect from python? I can connect from other applications on this same computer, so I can rule out AWS Security Groups and MySQL host limits. This seems to only happen with python. Does this have something to do with ssl like it did with javascript?
You need to add the ssl_ca argument to the mysql.connector.connect function. Eg.
thinknode = mysql.connector.connect(
host = "example.com",
user = "cwaugh",
passwd = "********",
db = "mydb",
ssl_ca = "./rds-combined-ca-bundle.pem")
I'm not sure why javascript wass able to use "Amazon RDS", and it would be a lot easier if python did too, but it doesn't.
I am using my old script, which used to work just fine, but now I'm receiving following error:
Error while connecting to the database.
Can't connect to MySQL server on 'some.remote.host.com' (65)
I can't figure out what the real error is, my connect data is surely correct, because I can login to PhPMyadmin with the given username and password.
Here is my code:
# encoding: UTF-8
require 'mysql2'
require 'csv'
def initialize_data
puts "Initializing database, username, password and host..."
#database = "database_name"
#username = "database_user"
#password = "my_secret_password"
#host = "remote.host.com"
end
def connect
puts "Trying to connect to the database."
begin
#client = Mysql2::Client.new(host: #host, username: #username, password: #password, database: #database)
rescue => e
puts "Error while connecting to the database."
puts e.message
end
end
I wasn't able to find any info on this 65 error. Rescuing with e.message does not help at all.
Can someone point me at least in what direction to dig? I'm struggling with this simple script second day in a row now. Is there any way to receive more detailed error messages? Like Rails' error.full_messages.each
You can look up MySQL error codes with perror:
$ perror 65
OS error code 65: No route to host
That might mean the MySQL server is on a network you can't currently reach. If so, you haven't reached the point where the username and password matters. An easy way to test if the problem is with your code or with accessing the database is to use the command-line tool. If you can't reach the database from the command line you are running Ruby from, the problem isn't your code.
Another test would be to run MySQL locally. (Or run your script on the same machine as the MySQL database, if possible.) If the script works as expected, check to see if there's been a recent change in network or database configuration.
I have just moved a database from our test server to the live server by creating an empty database and restoring a backup to it.
Despite adding the Login correctly, I am getting the following error:
The server principal "myUser" is not able to access the database
"myDatabase" under the current security context.
I have tried clicking F7 in Object Explorer Details with no luck. I can get the error simply by running:
> USE myDatabase
> GO
>
> EXECUTE AS LOGIN = 'myUser'
Running the following script (from a related question) shows the user correctly
select princ.type_desc
, princ.name
, perm.permission_name
, perm.state_desc
, object_name(perm.major_id)
from sys.database_permissions perm
left join
sys.database_principals princ
on princ.principal_id = perm.grantee_principal_id
SQL_USER myUser CONNECT GRANT
Any suggestions???
Try using sp_change_users_login with the "Auto_Fix" action to resync the logins between the server and the database.
exec sp_change_users_login #Action = 'Auto_Fix', #UserNamePattern = 'myUser'