Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Psycopg2 peer authentication for user postgres

I seem to have correctly installed PostgreSQL 9.5.5. and Psycopg2 on Ubuntu 16.04, and can log in via:

sudo -u postgres psql

If I then issue \conninfo, I get the following:

You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".

Surely I should be able to connect via psycopg2 in the same fashion as shown here, but the script:

#!/usr/bin/python
import psycopg2
conn = psycopg2.connect("dbname=postgres user=postgres") 
conn.close()

gives me:

psycopg2.OperationalError: FATAL:  Peer authentication failed for user "postgres"

I only want PostgreSQL for personal usage, so I don't want to enable TCP authentication.

How do I correctly use peer authentication with user "postgres" in Psycopg2?

like image 779
Yuri Lifanov Avatar asked Nov 10 '16 21:11

Yuri Lifanov


People also ask

What is Postgres peer authentication?

The peer authentication method works by obtaining the client's operating system user name from the kernel and using it as the allowed database user name (with optional user name mapping). This method is only supported on local connections.

What is peer and MD5?

peer means it will trust the identity (authenticity) of UNIX user. So not asking for a password. md5 means it will always ask for a password, and validate it after hashing with MD5 . trust means it will never ask for a password, and always trust any connection.

How do you change peer to MD5?

Find that PostgreSQL configuration file by typing: 'sudo nano /etc/postgresql/11/main/pg_hba. conf'. look for the user 'postgres' in white and look to the right for the 'md5'. That's where you set the authentication method for that PostgreSQL user.


2 Answers

You need to supply the host

conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'")
like image 145
moohaad Avatar answered Oct 05 '22 19:10

moohaad


Peer authentication works by comparing the Postgres username in your connection string to the name of the Linux user who is running the script.

Try running your Python script with sudo -u postgres.

like image 22
Nick Barnes Avatar answered Oct 05 '22 19:10

Nick Barnes