Skip to content
Advertisement

Postgresql/psycopg2 password authentication error even though user and password are correct

I am new to web development in Python and would really appreciate some help. I am trying to set up psycopg2/peewee on WSL (Windows machine). In my Python code I store all of the info I’ll need to access a Postgres database, and then attempt to connect to the database as follows:

JavaScript

I am certain that I have a Postgres user named ‘postgres’ with a password of ‘postgres’. Those are the credentials I use to start up a Postgres server once I have changed into the postgres user on my machine using su - postgres.

When I launch my Python virtual environment using pipenv shell and then run python3 main.py I get the following error:

JavaScript

I am confused as to why the authentication is failing for a valid user/password combo!

I have tried testing the connection string in the Python3 shell as well:

JavaScript

and I get the same error. I would much appreciate any insight as to why I can’t connect my Python code to Postgres!

My pg_hba.conf file has the following:

JavaScript

From the command line, ps ax |grep postgres shows:

JavaScript

After running psql -d postgres -U postgres -h 127.0.0.1 and inspecting the Postgres log, I see:

JavaScript

Lines 85-90 of pg_hba.conf:

JavaScript

Settings for port and listen_addresses in /main/postgresql.conf

JavaScript

Advertisement

Answer

The short version of the answer is that there where two instances of Postgres running in two different OS’es. The longer answer is as follows. In WSL(2) the Postgres instance pg_hba.conf had local set to peer for user postgres and md5 for all. There where md5 auth connections for localhost IPV4 and IPV6. This is why Allison could connect as database userpostgres user from system user postgres account. Changing the local settings to trust allowed for connecting from any system account when not using -h. The password connection issue with localhost remained though. The strange part was there was no record of those connections in the Postgres logs. There was no other instance of Postgres running in WSL. After too long a thought process on my part it became apparent that there had to be a server running in Windows proper. That was the case and it was the one grabbing the localhost connections and throwing the password errors. Shutting it down was a step to solving this. As it turns the Windows Postgres was running on port 5432 and the WSL instance 5433 and the WSL instance was only listening on localhost. Changing the port to 5432 and listen_addresses to ‘*’ allowed for localhost connection without specifying a port and local connections.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement