My goal is to use getpass to hide the entry of my password when I connect to a postgresql database via python3.
I use python3 on jyputer notebook.
This work well :
connect = psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password='123456'")
cur = connect.cursor()
But when I try to enter the password with a separate variable, it does not work anymore :
pw = getpass.getpass()
####Python ask me to tape password and i tape the same '123456'
To verify :
'123456'
connect=psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password=pw")
cur=connect.cursor()
" OperationalError: FATAL: password authentication failed for user
FATAL: password authentication failed for user "
received error message
Thanks you for your help
What you're doing is passing a string to the connect function. This string has the value of "dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password=pw". The psycopg2 module has no way of knowing what pw is. I suspect it will be converted to a string ('pw'), but I'm not sure.
Anyway, the correct approach would be to pass keyword arguments to the connect function like so:
connect = psycopg2.connect(dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password=pw)
# Notice the lack of double-quotes in the arguments
This way, you will be passing the contents of the pw variable to the function, instead of the name pw.
It is possible to pass the contents of the pw variable in string form as well, like so:
connect = psycopg2.connect("dbname='db_toto' user='dad' host='xx.xx.xxx.x' port='5432' password='{}'".format(pw))
The first form should be preferred.
Related
i'm beginner in sqlalchemy, i want to reflect my table in database to object, but always return invalid password, even though the password is correct. I dont understand why this happend. When i try to inspect they return my table name, so my password, connection string or on create_engine is correct.
when my database have no password is fine i can reflect it to Object, that's so weird.
but why when i reflect database with password it's error, always return "Not a valid password" ??,
My MS. Access Tbl 1
My MS. Access Tbl 2
Error in Reflect but My Table name is returned
This is my Code
because I was curious I also made a test select data, and it turned out to be successful in retrieving the data
it's returned my data and success created connection
when i add some code for testing
I think all it's correct but why cannot reflect??, Please Help.
My Reference connection_string
My Reference SqlAlchemy Automap Reflect
I have just released sqlalchemy-access version 1.1.1 to address this issue. Note that as described in Getting Connected if you want to use a pass-through ODBC connection string with an encrypted database you need to supply the password in two places:
driver = "{Microsoft Access Driver (*.mdb, *.accdb)}"
db_path = r"C:\Users\Public\test\sqlalchemy-access\gord_test.accdb"
pwd = "tiger"
connection_string = (
f"DRIVER={driver};"
f"DBQ={db_path};"
f"PWD={pwd};"
f"ExtendedAnsiSQL=1;"
)
connection_uri = (
f"access+pyodbc://admin:{pwd}#/"
f"?odbc_connect={urllib.parse.quote_plus(connection_string)}"
)
engine = sa.create_engine(connection_uri)
I am following along with lecturer's code and videos. He has this set up, and I have followed exactly. His works, mine doesn't and I cant figure out why. It is set up as user "root" and password is blank. I have tried pip install mysql-connector-python. I want to keep the same user and password as his so as to follow along better. I am using python and mysql via Wampserver64. When I try to run the python file through cmd I get the error "mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'#'localhost' (using password: YES)". I am new to this so trying to figure it out as I go along. Does the (using password: YES) mean that the passwords match? And how to I get script to connect to mysql?
db = mysql.connector.connect(
host = "localhost",
user= "root",
password = " "
#database ='datarepresentation'
)
#print ("connection made")
cursor = db.cursor()
cursor.execute("CREATE DATABASE datarepresentation")
The same problem occurred when my friend tried to run a python script in the Ubuntu Windows Linux Subsystem that uses a MySQL database set up.
We fixed the problem by running the following three commands in the MySQL 8.0 Command Line Client and then restarting the machine to reboot everything. We are using Flask in our project and not Wamp so hopefully it will work the same. These commands were found here.
SELECT user, authentication_string, plugin, host FROM mysql.user;
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'Current-Root-Password';
FLUSH PRIVILEGES;
According to MySQL documentation(MySQL Documentation), it states that (using password: YES) just means that you are in fact using a password. If you would have tried to login without using a password, it would say 'NO'.
As far as how to connect your script to your database, you pretty much have it. You can write a query to retrieve something from the database to check. Here is an example using the database you mentioned to retrieve some kind of data and make sure it's in the table.
cnx = mysql.connector.connect(
host="localhost",
user='root',
password=" ",
database='datarepresentation')
cursor = cnx.cursor()
query = ("SELECT * FROM table-name WHERE key1 = %s")
dataName = 'randomValue'
cursor.execute(query, (dataName))
result = cursor.fetchone()
if result[0] == 1:
return True
else:
return False
Don't assign any value to password argument and pass as i.e password=''
try to create new user
mysql> CREATE USER 'monty'#'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'#'localhost'
-> WITH GRANT OPTION;
mysql> CREATE USER 'monty'#'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'#'%'
-> WITH GRANT OPTION;
I also encountered it and solve such as below.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
#remove this line or password=""
)
It's remove the line of the password. if you want to insert the line of the password,it's unwanted the spase(for instance,password="", this isn't password=" ").
this program is (using password: YES).
Why can't i solve?
I thought that this error is indicating already "The passwords match."
so,description of the password is unwanted in mydb=mysql.connector.connect( ) .
I have specified how to solve on my site [troubleshooting] ProgrammingError: **** (*****): Access denied for user 'root'#'localhost' (using password: YES) mysql-connector of python.
I want to connect to a remote Postgresql (installed on raspberry pi) DB in Python. I have followed the example from the link below:
https://opensource.com/article/17/10/set-postgres-database-your-raspberry-pi
using the following code:
conn = psycopg2.connect('host=192.xxx.x.x user=pi password = raspberry dbname = test')
Not sure what goes wrong. Anybody a solution.
Unfortunately I get the following error:
psycopg2.OperationalError: FATAL: password authentication failed for user "pi"
FATAL: password authentication failed for user "pi"
I strongly recommend supplying the credentials as keyword arguments for better readability:
psycopg2.connect(
user="...",
password="...",
dbname="...",
host="...",
)
Also, as #peterh mentioned in the comments, your provided credentials might be parsed incorrectly (not in this case though). You can use psycopg2's own parser to confirm the output:
psycopg2._psycopg.parse_dsn('host=192.xxx.x.x user=pi password = raspberry dbname = test')
Which returns:
{'user': 'pi',
'password': 'raspberry',
'dbname': 'test',
'host': '192.xxx.x.x'}
All things considered, your error suggests that the User/Password combination is incorrect.
I have code to read the credentials from an external config file,
configParser = ConfigParser.RawConfigParser()
configFilePath = r'docs/credentials.cfg'
configParser.read(configFilePath)
AnD
User = configParser.get('your-config', 'user')
Pswd = configParser.get('your-config','pswd')
Host = configParser.get('your-config','hostdps')
db = pymysql.connect(host=Host, user=User, password=Pswd, db='xyz', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor,local_infile=True)
The password contains special characters like : #?f8h!3, How to make connect statement understand these chars.?
I have already tried adding backslashes, passing it in connect string, not sure how to get this?
The mistake was adding quotes before the start of password string in the config file.
I was using : configParser = ConfigParser.RawConfigParser() so, it was treating " as part of the password.
Quite silly.
I've been trying to automate the installation of an Open Street Map Server since no one has published one yet and the task is pretty tedious. In order to do this I'm dealing with PostgreSQL databases in a script, which I left Python in charge of.
Here's the situation: Basically I'm running python scripts dealing with the database throughout bash code. I'm trying to make the install as user friendly as possible, part of that is automating the PostgreSQL setup. I prompt the user, in bash, for a password they would like to use for the postgres database that already comes with PostgreSQL. I then send their password as a command line argument to a Python script.
This is the part of the script I'm having problems with:
import psycopg2
import sys
con = None
code = sys.argv[1]
try:
con = psycopg2.connect(database='postgres', user='postgres')
cur = con.cursor()
cur.execute("ALTER USER postgres WITH PASSWORD '%s'" % code)
Basically: On the bottom line where I change the password for the postgres database, it doesn't actually work. I know this because later I am prompted in my bash script to enter the password and it results in an authentication failure.
I'm pretty new to this, so if anyone has some good advice, it would be greatly appreciated.
Please use the below code, you can generate random passwords and update them
NOTE: For this code to work, the readwrite1 user has to be present in database prior using this
from psycopg2 import Error
import psycopg2
import random
#password generation
def password_generator(password_length):
# maximum length of password needed
characters = string.ascii_letters + string.digits + '!##$%^&*()'
password = ''.join(random.choice(characters) for i in range(password_length))
return password
#define a function that handles and parses psycopg2 exceptions
def print_psycopg2_exception(err):
err_type, err_obj, traceback = sys.exc_info()
# get the line number when exception occured
line_num = traceback.tb_lineno
# print the connect() error
print ("\npsycopg2 ERROR:", err, "on line number:", line_num)
print ("psycopg2 traceback:", traceback, "-- type:", err_type)
# psycopg2 extensions.Diagnostics object attribute
print ("\nextensions.Diagnostics:", err.diag)
# print the pgcode and pgerror exceptions
print ("pgerror:", err.pgerror)
print ("pgcode:", err.pgcode, "\n")
def update_password():
password=password_generator(10)
try:
con = psycopg2.connect(host="host here",database="dbhere", user="username",password="password")
cur = con.cursor()
cur.execute("alter user readwrite1 with password %(password)s;", {'password': password})
con.commit()
except Exception as err:
# pass exception to function
print_psycopg2_exception(err)
exit(1)
finally:
print('password is: ', password)
if con:
con.close()
return password