0

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

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
A. Sègla
  • 11
  • 2

1 Answers1

1

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.

Kendas
  • 1,963
  • 13
  • 20
  • The second form ( xxx.format(pw) ) worked well. The first send same error again. So i use the second. Thank you so much – A. Sègla Oct 12 '18 at 09:37